text:
Q: Xamarin Forms Dynamic Listview Binding I'm trying to create this ContentView where it will get different columns from the database based on the ClassID. I'm having a problem when it comes to displaying the correct data. I'm not sure if my approach is the right way? Can I use my variable cType to change the binding of the label inside the ViewCell
How I called the ContentView
        <local:AutoCompleteEntry
            x:Name="vBrand"
            ClassId="brand"
            />

        <local:AutoCompleteEntry
            x:Name="vPart"
            ClassId="part"
            />

XAML
<StackLayout Orientation="Vertical" BackgroundColor="AliceBlue">
    <Entry TextChanged="searchBar_TextChanged"
               BackgroundColor="#f9f9f9"
               TextColor="#FF464859"
               Unfocused="searchBar_Unfocused"
               FontSize="16" PlaceholderColor="#646b7a"
               x:Name="searchBar"
               Placeholder="Type here..."/>
    <ListView x:Name="lvw" IsVisible="False"
                  CachingStrategy="RecycleElement"
                  BackgroundColor="White"
                  ItemTapped="lvw_ItemTapped">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Frame>
                        <StackLayout BackgroundColor="White">
                            <Label Text="{Binding ctype}" FontSize="16" TextColor="Black"/>
                        </StackLayout>
                    </Frame>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

CODE
    ObservableCollection<Item> collection;
    SqliteDB<Item> dbItem = new SqliteDB<Item>(unique.dbPath);
    String ctype="";

    private async Task initLvw()
    {
        ctype = ClassId;
        switch (ClassId)
        {
            case "brand":
                collection = await dbItem.ReadData(e=>e.brand.Contains(searchBar.Text));
                lvw.ItemsSource = collection.Select(i => i.brand);
                break;
            case "part":
                collection = await dbItem.ReadData(e => e.partno.Contains(searchBar.Text));
                lvw.ItemsSource = collection.Select(i => i.partno);
                break;
            case "plgrp":
                collection = await dbItem.ReadData(e => e.plgrp.Contains(searchBar.Text));
                lvw.ItemsSource = collection.Select(i => i.plgrp);
                break;
            case "itemname":
                collection = await dbItem.ReadData(e => e.itemname.Contains(searchBar.Text));
                lvw.ItemsSource = collection.Select(i => i.itemname);
                break;
        }

        lvw.EndRefresh();

    }

A: Since I just need to display 1 column in the listview, I added a new list that will handle the results in the ObjectCollection. that way I don't need to change the binding.
    private async Task initLvw()
    {
        ctype = ClassId;
        switch (ClassId)
        {
            case "brand":
                collection = await dbItem.ReadData(e=>e.brand.ToLower().Contains(searchBar.Text.ToLower()));
                list = new List<string>(collection.Select(i=>i.brand).Distinct());
                break;
            case "part":
                collection = await dbItem.ReadData(e => e.partno.ToLower().Contains(searchBar.Text.ToLower()));
                list = new List<string>(collection.Select(i => i.partno).Distinct());
                break;
            case "plgrp":
                collection = await dbItem.ReadData(e => e.plgrp.ToLower().Contains(searchBar.Text.ToLower()));
                list = new List<string>(collection.Select(i => i.plgrp).Distinct());
                break;
            case "itemname":
                collection = await dbItem.ReadData(e => e.itemname.ToLower().Contains(searchBar.Text.ToLower()));
                list = new List<string>(collection.Select(i => i.itemname).Distinct());
                break;
        }
        lvw.ItemsSource = list;

        lvw.EndRefresh();

    }


text:
Q: hammer.js swipe disabling native pinch to zoom Is it possible to use the native "pinch to zoom" on touch devices while using hammerjs to recognize swipe gestures?
I want users to be able to zoom in on images in the gallery (as they can natively when hammer event handler is not bound) and swiping to display the previous or next image.
hammertime.on('swipe', function(ev) {
    if (ev.direction === 2) {
        nextImage();
    } else if (ev.direction === 4) {
        prevImage();
    }
});

A: Solution was to use touchAction = 'auto'
var hammertime = new Hammer(galleryEl, {touchAction : 'auto'});

Before doing this be sure to read http://hammerjs.github.io/touch-action/

When you set the touchAction to auto it doesnt prevent any defaults, and Hammer would probably break. You have to call preventDefault manually to fix this. You should only use this if you know what you're doing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move an Oracle database by moving the raw data files I have a large Oracle database (~300 GB) and I need to move a copy of the database to a new environment in a short period of time. I was wondering if there is a way to just pick up the raw files Oracle manages and move them to the new box and bypass doing a dump and then another import?
I was looking at http://docs.oracle.com/cd/B28359_01/server.111/b31107/asmcon.htm but not sure if this is what I need. Where are the raw data files stored?

A: This is largely dependent on the differences is Oracle version, and OS version. IF both are at the same version, and Oracle is patched in the same manor then the answer becomes a factor of:
IF all of the database related files will reside in the same place THEN
...do a cold clean shutdown of the database
...copy the datafiles, temp, undo, redo logs, control files AND instance related files (initINST.ora, spfileINST.ora, orapwINST, etc) in $ORACLE_HOME/dbs
...setup the instance in the oratab file (or, if it is Windows, use ORADIM to create the instance related windows service)
...startup normally
IF the file structure will change, but the instance name will not THEN
...do a cold clean shutdown of the database
...copy the datafiles, undo, redo logs AND instance related files (initINST.ora, spfileINST.ora, orapwINST, etc) in $ORACLE_HOME/dbs
...do not copy controlfiles
...setup the instance in the oratab file (or, if it is Windows, use ORADIM to create the instance related windows service)
...startup nomount
...recreate the controlfiles using the "create controlfile reuse ~ noresetlogs" command
...add back in TEMP tablespace
IF the file structure will change AND the instance name will as well THEN
...do a cold clean shutdown of the database
...copy the datafiles, undo, redo logs AND instance related files (initINST.ora, spfileINST.ora, orapwINST, etc) in $ORACLE_HOME/dbs
...do not copy controlfiles, temp or redo logs
...setup the instance in the oratab file (or, if it is Windows, use ORADIM to create the instance related windows service)
...startup nomount
...recreate the controlfiles using the "create controlfile set ~ resetlogs" command
...add back in TEMP tablespace
This is the typical, old-style clone technique. Normally, I am a fan of the RMAN DUPLICATE, but if this is a one time thing, I probably wouldn't worry about it. If this isn't 11g, you would be taking a separate backup, transporting that for use by rman. If it is 11g, duplicate can use the "from active database" clause, so long as the instances can reach each other on the network.

A: Copying the datafiles (while the database is down) from one server to the other is part, but not all, of what would be required.  You'll also need the redo log files, and you'll also need to create a new controlfile on the target system.  If you're moving to another windows machine, there are some other issues at work as well.  You'll naturally need to have the same version of Oracle installed on the target machine with the same patches in place.
If you're using RMAN with a recovery catalog to take backups of your database, it might be easiest to use the DUPLICATE TARGET DATABASE command.


text:
Q: What tool do you use to do burndown charts? do you use a tool?  or just manually make them?

A: We tend to just use a simple shared excel sheet with a graph on one tab and a pivot table on another.

A: I have not used myself, but http://apps.vanpuffelen.net/charts/burndown.jsp presents an api that is even simpler than the google charts api. Example:
http://apps.vanpuffelen.net/charts/burndown.jsp?days=17,18,19,22,23,24,25,26,29,30&work=125,112,104,99,95

gives the following graph:

A: Google charts api/server can make one fairly easily

You specify everything in the URL so it's easy to update:
http://chart.apis.google.com/chart?
chs=600x250& // the size of the chart
chtt=Burndown& // Title
cht=lc& // The chart type - "lc" means a line chart that only needs Y values
chdl=estimated|actual& // The two legends
chco=FF0000,00FF00& // The colours in hex of the two lines
chxr=0,0,30,2|1,0,40,2& // The data range for the x,y (index,min,max,interval)
chds=0,40 // The min and max values for the data. i.e. amount of features
chd=t:40,36,32,28,24,20,16,12,8,4,0|40,39,38,37,36,35,30,25,23,21,18,14,12,9,1 // Data

The URL above plots in intervals of 2 - so work every 2 days. You'll need a bigger size chart for every day. To do this make the data have 30 values for estimated and actual, and change the "chxr" so the interval is 1, not two.
You can plot only the days done more clearly with the "lxy" chart type (the first image). This needs you to enter the X data values too (so a vector). Use -1 for unknown.

A: I did use TargetProcess but I now prefer a more tactile method so I draw it manually on a whiteboard.

A: VersionOne makes the burndown sheets nicely.

A: Like answered in this post What tools provide burndown charts to Bugzilla or Mylyn?
www.in-sight.io (previously burndowncharts) is a great SCRUM analytics tool.
Here are some dashboard examples:
Sprint metrics
Team metrics

A: We use something locally based on http://opentcdb.org/ but that does scrum tracking, and draws pretty graphs.

A: We use the community edition of RallyDev and it makes nice burndown charts.  The problem is that our team has not yet been able to do a solid job of entering in data to keep the burndown information meaningful.

A: We also use the community edition of RallyDev that has nice charts.  I find it to be an excellent tool once you work out which bits of it you really want to use.  There is a huge amount of fields and functionality that most people wouldn't use which could be a confusing problem for bigger teams.

A: We used to use the tools at rallydev.com, but in time we found the tool to simply be to cumbersome for what we wanted.
In time, I moved to just a simple Excel spreadsheet. Every morning before stand up I counted the hours remaining and added the trend line next to an "ideal" burndown line on the chart. I posted it on the wall where we held our morning standups.

A: We you Team Foundation Server and with conchango's scrum templates using the built in burndown through this nice little scrum dashboard
http://www.codeplex.com/scrumdashboard

A: I used google docs and excel.  Templates for both are available at the bottom of this article (and include a number of nice features like automatic calculation of the efficiency factor)
Burn Down Chart Tutorial: Simple Agile Project Tracking


text:
Q: Groovy static methods with dots Why do I have a compilation error for this code:
class SomeList {

    final String field

    SomeList(String field) {
        this.field = field
    }

    static SomeList "Regular name of method"() {
        return new SomeList("Regular name of method")
    }

    static SomeList "Name with.dot"() {
        return new SomeList("Name with.dot")
    }
}

class SomeListTests {

    @Test
    def "some list test"() {
        //given
        SomeList list = SomeList()

        //when
        list."Regular name of method"()

        //then
        //compilation error
    }
}

Error message:

Error:Groovyc: While compiling tests of example-project_test: BUG! exception in phase 'semantic analysis' in source unit '/home/alex/Projects/example-project/src/test/groovy/SomeListTests.groovy' Problem loading class SomeList

I did not find any restrictions in the documentation for method names as String.
When i create main method with GroovyShell and try to start script with this method it compiles.
class Main {
    public static void main(String[] args) {
        GroovyShell shell = new GroovyShell()
        shell.run(new File("path/to/Script.groovy"), Collections.emptyList())
        println "Everything is cool"
    }
}

And this is Script.groovy:
SomeList."Regular name of method"()
SomeList."Name with.dot"()

A: I create Test.groovy file as Groovy Script file in IDEA:
import org.junit.Test

class SomeList {

    final String field

    SomeList(String field) {
        this.field = field
    }

    static SomeList "Regular name of method"() {
        return new SomeList("Regular name of method")
    }

    static SomeList "Name with.dot"() {
        return new SomeList("Name with.dot")
    }
}

class SomeListTests {

    @Test
    void "some list test"() {
        //given
        SomeList list = new SomeList()

        //when
        println list."Regular name of method"()

        //then
        println list."Name with.dot"()
    }
}

And it works fine for me. I'm using Groovy 2.4.15.
The output is:
SomeList@cb51256
SomeList@59906517


text:
Q: Google Calendar API server to server Rails I want insert events in my calendar after some user's actions. That's why I'm want use server-to-server authorization with Google API. I wrote next code:
require 'google/apis/calendar_v3'
require 'googleauth'

require 'google/api_client/client_secrets'
require 'google/api_client'

Initialize the client
client = Google::Apis::CalendarV3::CalendarService.new

load and decrypt private key
key = G.load_from_pkcs12('google_secrets.json', 'notasecret')

generate request body for authorization
client.authorization = Signet::OAuth2::Client.new(
    :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
    :audience             => 'https://accounts.google.com/o/oauth2/token',
    :scope                => 'https://www.googleapis.com/auth/calendar',
    :issuer               => '....',
    :signing_key          => key)

fetch access token
client.authorization.fetch_access_token!

# load API definition
service = client.discovered_api('calendar', 'v3')

# there is a place for variable "event" declaration

client.execute(:api_method => service.event.insert,
               :parameters => { '....'   => 'primary' },
               :event       => event)

But when I try to use that code, i recive next answer:
cannot load such file -- google/api_client (LoadError)

I'm understand that maybe I must use previous version of gem google-api-client(<0.9) for get rid of that error. But don't know how i must make insert event with syntax of < 0.9 google api version.

A: I found solution.
Use for it api v.0.8.2 and see next page:
Rails + Google Calendar API events not created


text:
Q: First Order Logic Formula with quantifiers, needs some help Are these FOL formulae transformations correct?
Every doctor of Central Hospital has a badge
$\forall x \forall y$ $[Doctor(x) \land WorksIn(x,Central Hospital) \Rightarrow$ HasBadge(x,y)]
I think it is not. We need an $\exists y$ instead of $\forall y$ because is right that if x is a doctor and he works for Central he has a badge but the badge must be unique! Can't be true  for every badge of the universe right?
Second:
Every baby with a mother has a parent
$\forall x \forall y \exists z [Baby(x) \land Mother(x,y) \Rightarrow Parent(x,z)]$
Same, i think that we would use the $\exists y$ since only one mother is a mother of a creature and it's not true that every element of the Domain is mother of x.
Many thanks

A: You're right that for the second one you should use a $\exists y$ rather than a $\forall y$.
The second is more tricky! The best thing  to do is exactly what Kenny did, which is to introduce the quantifiers at the time they are referred to, instead of trying to put them all out at the front. So, as Kenny did:
$$\forall x [\operatorname{Baby}(x) \land \exists y \operatorname{Mother}(x,y) \implies \exists z \operatorname{Parent}(x,z)]$$
If you insist on taking the quantifiers out to the front, you need to be very careful, because the rules for these (called the Prenex Laws) are:
Prenex Laws
Where $x$ is not a free variable in $Q$:
$ \forall x \ P(x) \land Q \Leftrightarrow \forall x (P(x) \land Q)$
$ \forall x \ P(x) \land Q \Leftrightarrow \exists x (P(x) \land Q)$
$ \forall x \ P(x) \lor Q \Leftrightarrow \forall x (P(x) \lor Q)$
$\exists x \ P(x) \lor Q \Leftrightarrow \exists x (P(x) \lor Q)$
$\forall x \ Q \rightarrow P(x) \Leftrightarrow \forall x (Q\rightarrow P(x))$
$\exists x \ Q \rightarrow P(x) \Leftrightarrow \exists x (Q\rightarrow P(x))$
$\exists x \ P(x) \rightarrow Q \Leftrightarrow \forall x (P(x) \rightarrow Q)$
$\forall x \ P(x) \rightarrow Q \Leftrightarrow \exists x (P(x) \rightarrow Q)$
Notice in particular the last two equivalences, which show that if you take out a quantifier that is in the antecedent of an implication, then the quantifier changes into the other quantifier! So, if we apply these rules to Kenny's sentence, we get:
$$\forall x [\operatorname{Baby}(x) \land \exists y \operatorname{Mother}(x,y) \implies \exists z \operatorname{Parent}(x,z)] \Leftrightarrow$$
$$\forall x \forall y[\operatorname{Baby}(x) \land  \operatorname{Mother}(x,y) \implies \exists z \operatorname{Parent}(x,z)] \Leftrightarrow$$
$$\forall x \forall y \exists z [\operatorname{Baby}(x) \land  \operatorname{Mother}(x,y) \implies \operatorname{Parent}(x,z)] $$
...so you actually had it right the first place, and you should not change the $\forall y$ into a $\exists y$.  But again, for readability sake, leaving the quantifiers on the inside makes it often more easier to translate in the first place.

A: First one:
$$\forall x [\operatorname{Doctor}(x) \land \operatorname{WorksIn}(x,\text{CentralHospital}) \implies \exists y \operatorname{HasBadge}(x,y)]$$
Second one:
$$\forall x [\operatorname{Baby}(x) \land \exists y \operatorname{Mother}(x,y) \implies \exists z \operatorname{Parent}(x,z)]$$

A:

Every doctor of Central Hospital has a badge

$\forall x \forall y~[\text{Doctor}(x) \land \text{WorksIn}(x,\text{[Central Hospital]}) \Rightarrow \text{HasBadge}(x,y)]$
I think it is not. We need an $\exists y$ instead of $\forall y$ because is right that if x is a doctor and he works for Central he has a badge but the badge must be unique! Can't be true  for every badge of the universe right?

Correct.  But more, you have to assert that $y$ is a badge.
$$\forall x~\exists y~((\operatorname{isDoctor}(x)\wedge \operatorname{WorksIn}(x,C))\to (\operatorname{isBadge}(y)\wedge \operatorname{Has}(x,y)))$$
Or you could merge the predicates.  Either is acceptable, but consistency is best practice.
$$\forall x~\exists y~(\operatorname{isDoctorOf}(x,C)\to \operatorname{isBadgeOf}(y,x))$$

Every baby with a mother has a parent

$\forall x \forall y \exists z [Baby(x) \land Mother(x,y) \Rightarrow Parent(x,z)]$
Same, i think that we would use the $\exists y$ since only one mother is a mother of a creature and it's not true that every element of the Domain is mother of x.

No, you wish to affirm: "For any (x,y): if x is a baby and y is the mother of x, then x has a parent."
$$\forall x~\forall y~\exists z~[(\operatorname{isBaby}(x) \land \operatorname{isMotherOf}(y,x))\to \operatorname{isParentOf}(z,x)]$$
This Prenex form is equivalent to: "for every baby, the existence of a mother implies the existence of a parent."
$$\forall x~[\operatorname{isBaby}(x)\to((\exists y~\operatorname{isMotherOf}(y,x))\to (\exists z~\operatorname{isParentOf}(z,x)))]$$


text:
Q: Small grammatical error I noticed So I was going to accept an answer, and got this:

I know this isn't important... But it should say 1 minute, not 1 minutes. This should be on the "unimportant" fixes, but it's so easy to fix, I figured that I may as well point it out.


text:
Q: Convert List to List, where T is abstract I'm trying to generalize a method that I'll need to call a lot. It takes a List<E extends RealmObject> and return a List<T extends Pojo<E>>. The conversion from E to T is done via
new T().fromRealm(realmObject)

It won't work because T is an abstract class, so I can't instantiate it.
public static <E extends RealmObject, T extends Pojo<E>> List<T> fromRealmList(
        RealmList<E> realmList) {
    List<T> pojoObjects = new ArrayList<>();
    if (realmList != null) {
        for (E realmObject : realmList) {
            try {
                pojoObjects.add(new T().fromRealm(realmObject));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return pojoObjects;
}

I also tried with this answer, but List<T> won't accept the object created with clazz.newInstance().
EDIT: adding Pojo class
public abstract class Pojo<R extends RealmObject> {

@NonNull
public abstract R toRealm();

@NonNull
public abstract Pojo<R> fromRealm(R realmObject);
}

EDIT2: adding an alternate solution, that still doesn't work: Required T, found Pojo<E>.
T newInstance = clazz.getConstructor()
                     .newInstance()
                     .fromRealm(realmObject);
                pojoObjects.add(newInstance);

A: Apart from being an abstract class, T is also a parameter type, which cannot be used in a constructor new T().
A typical solution would be to use reflection:

*

*pass an additional parameter Class<T> clazz to your method fromRealmList

*invoke clazz.getConstructor(...).newInstance(...)
Maybe not perfect but that should work.
--edit-- The below is an example without using type T:
public static <E extends RealmObject> List<Pojo<E>> fromRealmList(
    RealmList<E> realmList, Class<Pojo<E>> clazz) {

   List<Pojo<E>> pojoObjects = new ArrayList<>();
   ...
   Pojo<E> newInstance = clazz.getConstructor(...).newInstance(...).fromRealm(...);
   pojoObjects.add(newInstance);
   ...
}


text:
Q: What happens to the files when they are being decrypted? I have the server's webroot directory mounted on a partition which is being protected with LUKS encryption. I want to know what happens to the files within when that partition is being decrypted. Does

*

*a copy of the unencrypted version of these files goes to the RAM, or;

*a copy of the unencrypted version of these files goes to the temp
directory, or;

*the server decrypts the files upon demand each time they are being
accessed, or;

*other scenarios I have missed?
The reason why I ask this is to have a better understanding on the decryption process and how it affects the server's resource in terms of CPU and RAM and whether disk encryption with LUKS is more efficient compared to file system encryption like eCryptfs.
I tried looking at Wikipedia but could not find any such information. Not sure if this is the best place to ask this question. Feel free to migrate if you think otherwise. Thanks.

A: LUKS is a block device encryption layer which sits on top of a block device and encrypts/decrypts all accesses to that device. No unencrypted data ever touches the physical device.
LUKS then provides a virtual block device which gets used by the system to access the files. It is thus transparent to applications, which have no idea that encryption is taking place.
Consider a trivial system with a single block device and a root file system on /dev/sda1. If we encrypt this with LUKS, then it will handle all direct access to that device, and will provide its own device, for instance /dev/mapper/encrypted-root which will actually be used by the system. This might be in /etc/fstab:
/dev/mapper/encrypted-root  /       ext4    noatime 0 0

So every access to a file on this filesystem will pass through LUKS.
Also note that LUKS does not know or care what data it is processing. Thus you can layer anything on top of it, whether it be a straight filesystem, a software RAID array, an LVM volume, etc. LUKS can also be placed on top of any of these.
Note well that data cached in RAM by the normal caching processes may be unencrypted.


text:
Q: SAS conditional IF-THEN statement not working I am a beginner user of SAS and currently, I'm following one of the Coursera courses. The code given in a lecture doesn't work although I don't see an error. Below the code:
PROC IMPORT DATAFILE ='/home/student123/my_courses/nesarc_pds.csv' OUT = data  REPLACE;

LABEL TAB12MDX ="Tobacco Dependance Past 12 Months"
      CHECK321 ="Smoked Cigarettes in Past 12 Months"
      S3AQ3B1 ="Usual Smoking Frequency"
      S3AQ3C1 ="Usual Smoking Quantity";

IF S3AQ3B1=9 THEN S3AQ3B1=.;
IF S3AQ3C1=99 THEN S3AQ3C1=.;
IF CHECK321=1;
IF AGE LE 25;
PROC SORT; BY IDNUM;
PROC FREQ; TABLES TAB12MDX CHECK321 S3AQ3B1 S3AQ3C1 AGE;
RUN;

The error I see in a log is:
80         IF S3AQ3B1=9 THEN S3AQ3B1=MISSING;
        __
        180
81         IF CHECK321=1;
        __
        180
82         IF AGE LE 25;
        __
        180
ERROR 180-322: Statement is not valid or it is used out of proper order.

I use SAS Studio but I don't know does it matter.
Does anyone know where is an error?

A: *

*You need a data step or procedure to modify data

*You should use DATA= to point the procs to the correct data input

*You only need one RUN but it helps do delineate your code.
PROC IMPORT DATAFILE ='/home/student123/my_courses/nesarc_pds.csv' OUT = data  REPLACE;
RUN;  /*3*/

Data yourData; /*1*/
set data;

LABEL TAB12MDX ="Tobacco Dependance Past 12 Months"
  CHECK321 ="Smoked Cigarettes in Past 12 Months"
  S3AQ3B1 ="Usual Smoking Frequency"
  S3AQ3C1 ="Usual Smoking Quantity";

IF S3AQ3B1=9 THEN S3AQ3B1=.;
IF S3AQ3C1=99 THEN S3AQ3C1=.;
IF CHECK321=1;
IF AGE LE 25;

run;  /*3*/

PROC SORT data=yourData; /*2*/
BY IDNUM;
RUN; /*3*/

PROC FREQ data=yourData; /*2*/
TABLES TAB12MDX CHECK321 S3AQ3B1 S3AQ3C1 AGE;
RUN;

A: You cannot run an IF statement or a LABEL statement in the middle of nowhere. They have to be part of a data step (or pat of a proc step that supports those statements).  You need a DATA step.  (Note it is also a good idea to give your datasets more meaningful names than data.)
PROC IMPORT DATAFILE ='/home/student123/my_courses/nesarc_pds.csv'
  OUT = nesarc_pds REPLACE
;
run;

data youth;
 set nesarc_pds ;
LABEL TAB12MDX ="Tobacco Dependance Past 12 Months"
      CHECK321 ="Smoked Cigarettes in Past 12 Months"
      S3AQ3B1 ="Usual Smoking Frequency"
      S3AQ3C1 ="Usual Smoking Quantity"
;

IF S3AQ3B1=9 THEN S3AQ3B1=.;
IF S3AQ3C1=99 THEN S3AQ3C1=.;
IF CHECK321=1;
IF AGE LE 25;
run;

PROC SORT data=youth; BY IDNUM;
run;

PROC FREQ data=youth; TABLES TAB12MDX CHECK321 S3AQ3B1 S3AQ3C1 AGE;
RUN;


text:
Q: How does the Joule-Kelvin effect apply to the liquefaction process of Hydrogen? Why do we need to cool Hydrogen before taking advantages of this? I am currently writing a report around Hydrogen at a first year university level. On the below section i discuss the liquefaction process of Hydrogen and how the Joule-Kelvin effect is used in the liquefaction process. Have i described this correctly?
"Liquefaction of Hydrogen requires copious amounts of energy as it must be stored at 20.15k and be maintained at this temperature. The liquefaction process takes advantage of the Joule-Kelvin (Joule-Thomson) effect, this effect states if we force a gas through an orifice then as it expands it becomes cooler. To achieve this the system must be adiabatic meaning no heat is transferred between environments as the enthalpy of the system must remain constant; enthalpy referring to the total heat content of said system. This process for most gasses takes place at room temperature but Hydrogen must first be cooled to below 346.15k to take advantage of the phenomenon. This in turn effects the cost as liquid nitrogen is often used to get the Hydrogen to the correct temperature."
Secondly why does Hydrogen need to be cooled first? I believe it has something to do with the "long-range forces in these gases are unusually weak" but am finding it difficult to understand exactly what this means.
Redone section below:
"The liquefaction process takes advantage of the Joule-Kelvin (Joule-Thomson) effect, this effect states if we force a gas through an orifice then as it expands it becomes cooler. To achieve this the system must be adiabatic meaning no heat is transferred between environments as the enthalpy of the system must remain constant; enthalpy referring to the total heat content of said system. Meaning specially constructed vessels are used to try and maintain a constant enthalpy. Additionally, this process for most gasses takes place at room temperature but Hydrogen must first be cooled to ~200k to take advantage of the phenomenon. This temperature is known as the maximum inversion temperature. Hydrogen above this temperature would actually heat up upon expansion as it would do at any temperature above ~200k. This detrimentally effects Hydrogen viability as a fuel as some form of pre-cooling is required to liquify the gas. Translating to higher energy consumption and increased costs. Primarily liquid nitrogen is used as a coolant which must be either purchased or produced. When considering Hydrogens viability as a fuel this must be considered. This factor increases the energy required to get the Hydrogen into a form with the energy densities required to compete with current technologies."


text:
Q: Insert PHP Integer Variable into HTML I have a PHP code that draws my subscriber count from my YouTube channel and sets it as an integer variable, $subs. I need to use the variable $subs in this piece of HTML code.
HTML Code:

Subs

PHP Code:
<?php
    set_time_limit(0);
    function retrieveContent($url){
        $file = fopen($url,"rb");

        if (!$file) return "";
        while (feof ($file)===false) {
            $line = fgets ($file, 1024);
            $salida .= $line;
        }

        fclose($file);
        return $salida;
    }
        {
            $content = retrieveContent("youtube.com/user/geekawhat/about"); $start = strpos($content,'');
            $end = strpos($content,'',$start+1);
            $output = substr($content,$start,$end-$start);
            $subs = (int)$output;
            echo "$output";
         }
?>

It is a counter, and I want it to count to whatever that variable equals. I have placed the variable in the data-to field, which informs the counter what to count upto - how do I get this to work? (This does work btw with a number inserted into the data-to field)

A: Simply echo it out:
data-to="<?php echo $subs; ?>"
or if you have PHP short tags enabled:
data-to="<?= $subs ?>"
http://php.net/manual/en/function.echo.php

A: You can just echo() it:

Output one or more strings

data-to="<?php echo $subs ?>"

Alternatively, you can also use print():

Output a string

data-to="<?php print $subs ?>"

A: use php tag and echo where you want

    <span data-from="100" data-to="<?php echo $subs; ?>" data-refresh-interval="50" data-speed="2000" data-comma="true">

Subs


text:
Q: PHP: Check URL against array of badwords, and output any found I have a database which contains the results of logged network traffic, and I'm building a simple log viewer frontend in PHP. I need to check each URL and see if it contains any of the 'bad words' in an external 'badwords.txt' file, then echo which ones, and color the table row red (the easy bit!)
Thus far I have loaded the badwords.txt file into an array, and fetched the URL from the database. Here is the portion of my code where I am trying to get a positively identified 'bad' url. I ideally want to output which badwords were found, but have simplified everything to just try and get it to work for now.
    // Load the badwords file into an array
    $words = file('badwords.txt');

    //$row[3] is the URL fetched from the database
    $testURL = $row[3];

    foreach ($words as $phrase) {
      if (strrpos($testURL, $phrase)) {
        echo "FOUND";
      }
    }

This is not working for me, and never outputs FOUND, even when the url definitely contains a bad word. I have checked that my $words array is populated correctly with all the badwords, and I have checked that the $testURL is not empty etc.
Can anyone help please? :) I'd be really grateful for any assistance - I have read through so many StackExchange posts on similar topics, but none seem to work for my case.
Thank you!

A: Words array contains newline symbol, so strpos never works. Remove them
$words = file('badwords.txt', FILE_IGNORE_NEW_LINES);

A: Since strrpos() returns numeric position of needle, and boolean false, so code should be
<?php
 // Load the badwords file into an array
  $words = file('words.txt', FILE_IGNORE_NEW_LINES);

//$row[3] is the URL fetched from the database
$testURL = row[3];

foreach ($words as $phrase) {
  if (strrpos($testURL, $phrase)>-1) {
    echo "FOUND";
  }
}


text:
Q: Prove that $\lim_{n\rightarrow \infty} \int_{0}^{1} (f(x))^n dx$ exists if and only if $\mu ( \{x \in [0,1]: f(x)>1 \})=0$ I am trying to solve this problem, but I have not succeeded. Can someone help me? Thanks in advance. The problem is:
Let $f$ be nonnegative measurable function on $[0,1]$. Prove that $lim_{n\rightarrow \infty} \int_{0}^{1} (f(x))^n dx$  exists if and only if $\mu ( \{x \in [0,1]: f(x)>1 \})=0$.

A: Hints: let be $G = \{x\in[0,1]\,:\, f(x) > 1\}$, $G_\epsilon = \{x\in[0,1]\,:\, f(x) > 1+\epsilon\}$.
Case $\mu(G) > 0$: this implies $\mu(G_\epsilon) > 0$ for some $\epsilon > 0$; use that $f\ge(1+\epsilon)\chi_{G_\epsilon}$.
Case $\mu(G) = 0$: this implies that $\lim_{n\to\infty}(f(x))^n$ exists for almost all $x\in[0,1]$; apply the [...] convergence theorem.


text:
Q: Django context doesn't load after post I'm trying to pass "message_name" to index.html through the form but the context does not render after submitting the form. It appears a blank page. I can see through the page inspector that the text was submitted but the content doesn't show.
I imagine this should be really easy but I could not find solution till now.
Thank you in advance for your help.
#views.py
from django.shortcuts import render

from .models import Home, About, Profile, Category, Skills, Item, Audiogil, ImageSkills
from django.core.paginator import Paginator

def index(request):
    # Home
    home = Home.objects.latest('updated')

    # About
    about = About.objects.latest('updated')
    #profiles = Profile.objects.filter(about=about)
    profiles = Profile.objects.all()

    # Skills
    categories = Category.objects.all()

    skillsimage = ImageSkills.objects.latest('updated')

    # Videos
    videos = Item.objects.all()

    # Setup video pagination
    p = Paginator(Item.objects.all(), 2)
    page = request.GET.get('page')
    video_list = p.get_page(page)

    # Audios
    audios = Audiogil.objects.all()

    context = {
        'home': home,
        'about': about,
        'profiles': profiles,
        'categories': categories,
        'videos': videos,
        'video_list': video_list,
        'audios': audios,
        'skillsimage': skillsimage,
    }

    if request.method == "POST":
        message_name = request.POST['message-name']
        message_email = request.POST['message-email']
        message = request.POST['message']

        return render(request, 'index.html', {'message_name':message_name})

    return render(request, 'index.html', context)

#template
....

Contacto - {{ message_name }}

EMAIL

        info.mail.com

      <form action="{% url 'index' %}" class="contact__form" method="post">
        {% csrf_token %}

          <input type="text" placeholder="Nome" name="message-name" class="contact__input" />
          <input type="mail" placeholder="Email" name="message-email" class="contact__input" />

        <textarea
          name="message"
          id=""
          cols="0"
          rows="10"
          class="contact__input"
        ></textarea>

        <input type="submit" value="Enviar" class="contact__button" />
      </form>

A: Change this:
return render(request, 'index.html', {'message_name':message_name})

...to this:
return render(request, 'index.html', context)

...if your intent is to pick up the context dictionary you have declared above your POST method.
If you want to add in additional context such as message_name, you could do something like:
    if request.method == "POST":
        context['message_name'] = request.POST['message-name']
        message_email = request.POST['message-email']
        message = request.POST['message']
        # seems like you're missing (or not showing) more logic here...

...which you can do once you have declared a context dictionary somewhere up above, as you have.
One last word: You have a fair number of model queries going on in this view.  Are any these models related via OneToOne, ForeignKey, or ManyToMany relations?  If so, consider fewer queries with the select_related() and/or prefetch_related() methods for the sake of efficiency.  More about those here and here in the Django docs.  You can access or iterate through related objects in your template, for example:
{{queried_object.related_object.field_value}}


text:
Q: Why is allocation and deallocation of std::vector slower than dynamic array on my machine I was under the impression that std::vector is just a thin wrapper around dynamic arrays, and their performance should be comparable. A search on the Internet and stackoverflow itself gives the same answer as well. However, when I test it myself, I found a huge difference. The code is below. I tried both VC++ 2012 (release build) and MinGW with optimization flag -O2.
The time for new, malloc and calloc is around 0.005 sec, while std::vector takes 0.9 sec on both compilers. Is std::vector inherently slow or my code has some serious flaws?
#define _SCL_SECURE 0
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <time.h>

struct timer
{
    clock_t start;
    timer()
    {
        start=clock();
    }
    ~timer()
    {
        double t=static_cast<double>(clock()-start)/CLOCKS_PER_SEC;
        printf("%lf\n", t);
    }
};

int main()
{
    const size_t len=(1<<28);
    {
        timer t;
        int *d=new int[len];
        printf("%d\n",d[len-1]);//prevent compiler from optimizing away
                                //useless allocation and deallocation
        delete[] d;
    }
    {
        timer t;
        int *d=(int *)malloc(len*sizeof(int));
        printf("%d\n", d[len-1]);
        free(d);
    }

    {
        timer t;
        std::vector<int> d(len);
        printf("%d\n", d[len-1]);
    }
    {
        timer t;
        int *d=(int *)calloc(len, sizeof(int));
        printf("%d\n", d[len-1]);
        free(d);
    }

    return 0;
}

EDIT 1
Per suggestion, I test for additional ways of creating dynamic array

*

*new: 0.005

*malloc: 0.005

*calloc: 0.005

*malloc+memset: 1.244

*vector(len): 1.231

*vector(len, 0): 1.234

*vector.reserve(len): 0.005

So indeed the offender is the zero initialization instead allocation or deallocation. This means that if one needs an zero-initialized array, vector is not the way to go, even if it has a constructor that default initialized all elements.
Besides, this is not just something that pop out of my head. My final project for a class is graded on the time spent, and I used a several vectors to allocate a huge memory buffer instead of new for exception safety and because our textbook encourages use of STL. Not until today did I realize that I lost some points because of this. Sad day.
EDIT 2
Today I tried Clang 3.2 on Ubuntu 13.04 x64, and std::vector no longer takes that time to initialize. In fact, vector is now the fastest! Maybe this is a compiler optimization problem after all, not inherently in design of the std::vector.

A: I believe this is due to allocation of std::vector invoking a copy constructor on each element, where malloc just returns uninitialized memory.
std::vector<int> x(100);

is effectively the same as:
std::vector<int> y(100, int());

See the documentation on the constructor for std::vector
http://en.cppreference.com/w/cpp/container/vector/vector
I often will do something like this:
std::vector<int> x;
x.reserve(100);
// Insert items into x via x.push_back()

A: printf("%d\n",d[len-1]);//prevent compiler from optimizing away

This line reads from an uninitialised object. Instead of preventing the compiler from optimising things, it gives it leeway to do whatever it wants (i.e. the behaviour of the program is undefined).
Let's pretend we fixed that somehow and the behaviour of the program is now well-defined (maybe we added a line initialising d[len-1]).
std::vector<int> d(len);

This line initialises len objects with the value 0. This other line doesn't:
int *d=new int[len];

The only other line that does results in len objects with the value 0 is this one:
int *d=(int *)calloc(len, sizeof(int));

The only conclusion you can draw from the benchmark related to allocation and deallocation performance is that the benchmark is not fit for drawing conclusions related to allocation and deallocation performance.


text:
Q: Can't create a Project with Angular CLI A few days ago I created a new project with Angular CLI and everything worked fine. I'm not able to create any new project now. Below is the error logs in cmd:
 c:\Users\Jesper\Desktop>ng new mytestapp
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
CREATE mytestapp/angular.json (3795 bytes)
CREATE mytestapp/package.json (1316 bytes)
CREATE mytestapp/README.md (1026 bytes)
CREATE mytestapp/tsconfig.json (408 bytes)
CREATE mytestapp/tslint.json (2837 bytes)
CREATE mytestapp/.editorconfig (245 bytes)
CREATE mytestapp/.gitignore (503 bytes)
CREATE mytestapp/src/favicon.ico (5430 bytes)
CREATE mytestapp/src/index.html (296 bytes)
CREATE mytestapp/src/main.ts (372 bytes)
CREATE mytestapp/src/polyfills.ts (3234 bytes)
CREATE mytestapp/src/test.ts (642 bytes)
CREATE mytestapp/src/styles.css (80 bytes)
CREATE mytestapp/src/browserslist (388 bytes)
CREATE mytestapp/src/karma.conf.js (964 bytes)
CREATE mytestapp/src/tsconfig.app.json (166 bytes)
CREATE mytestapp/src/tsconfig.spec.json (256 bytes)
CREATE mytestapp/src/tslint.json (314 bytes)
CREATE mytestapp/src/assets/.gitkeep (0 bytes)
CREATE mytestapp/src/environments/environment.prod.ts (51 bytes)
CREATE mytestapp/src/environments/environment.ts (662 bytes)
CREATE mytestapp/src/app/app-routing.module.ts (245 bytes)
CREATE mytestapp/src/app/app.module.ts (393 bytes)
CREATE mytestapp/src/app/app.component.html (1173 bytes)
CREATE mytestapp/src/app/app.component.spec.ts (1104 bytes)
CREATE mytestapp/src/app/app.component.ts (213 bytes)
CREATE mytestapp/src/app/app.component.css (0 bytes)
CREATE mytestapp/e2e/protractor.conf.js (752 bytes)
CREATE mytestapp/e2e/tsconfig.e2e.json (213 bytes)
CREATE mytestapp/e2e/src/app.e2e-spec.ts (305 bytes)
CREATE mytestapp/e2e/src/app.po.ts (208 bytes)
npm WARN deprecated circular-json@0.5.9: CircularJSON is in maintenance only, flatted is its successor.
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @schematics/update@0.10.5
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of '@angular/cli'
npm ERR! notarget

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Jesper\AppData\Roaming\npm-cache\_logs\2018-11-09T00_31_49_304Z-debug.log
Package install failed, see above.

Here is the output from ng version:
Angular CLI: 7.0.4
Node: 10.13.0
OS: win32 x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.10.4
@angular-devkit/core         7.0.4
@angular-devkit/schematics   7.0.4
@schematics/angular          7.0.4
@schematics/update           0.10.4
rxjs                         6.3.3
typescript                   3.1.3

How come this problem has occurred suddenly and how do I fix it?

A: I just had a similar problem, only in my case, the process froze following the circular-son download. I killed it and ran it again and it worked fine.


text:
Q: php regex replace each character with asterisk I am trying to something like this.
Hiding users except for first 3 characters.
EX)

*

*apple -> app**

*google -> goo***

*abc12345 ->abc*****

I am currently using php like this:
$string = "abcd1234";
$regex = '/(?<=^(.{3}))(.*)$/';
$replacement = '*';
$changed = preg_replace($regex,$replacement,$string);
echo $changed;

and the result be like:
abc*

But I want to make a replacement to every single character except for first 3 - like:
abc*****

How should I do?

A: Don't use regex, use substr_replace:
$var = "abcdef";
$charToKeep = 3;
echo strlen($var) > $charToKeep ?  substr_replace($var, str_repeat ( '*' ,  strlen($var) - $charToKeep), $charToKeep) : $var;

Keep in mind that regex are good for matching patterns in string, but there is a lot of functions already designed for string manipulation.
Will output:

abc***

A: Try this function. You can specify how much chars should be visible and which character should be used as mask:
$string = "abcd1234";

echo hideCharacters($string, 3, "*");

function hideCharacters($string, $visibleCharactersCount, $mask)
{
    if(strlen($string) < $visibleCharactersCount)
        return $string;

    $part = substr($string, 0, $visibleCharactersCount);
    return str_pad($part, strlen($string), $mask, STR_PAD_RIGHT);
}

Output:

abc*****

A: Your regex matches all symbols after the first 3, thus, you replace them with a one hard-coded *.
You can use
'~(^.{3}|(?!^)\G)\K.~'

And replace with *. See the regex demo
This regex matches the first 3 characters (with ^.{3}) or the end of the previous successful match or start of the string (with (?!^)\G), and then omits the characters matched from the match value (with \K) and matches any character but a newline with ..
See IDEONE demo
$re = '~(^.{3}|(?!^)\G)\K.~';
$strs = array("aa","apple", "google", "abc12345", "asdddd");
foreach ($strs as $s) {
    $result = preg_replace($re, "*", $s);
    echo $result . PHP_EOL;
}

A: Another possible solution is to concatenate the first three characters with a string of * repeated the correct number of times:
$text = substr($string, 0, 3).str_repeat('*', max(0, strlen($string) - 3));

The usage of max() is needed to avoid str_repeat() issue a warning when it receives a negative argument. This situation happens when the length of $string is less than 3.


text:
Q: Prove that if there exists $c,M>0$ such that $|a_nc^n|\leq M\forall n$, then $(-c,c)\subseteq\operatorname{Conv}(\sum a_nx^n)$ Prove that if there exists $c,M>0$ such that $|a_nc^n|\leq M\,\forall n$, then $(-c,c)\subseteq \operatorname{Conv}(\sum a_nx^n)$.
I tried to use the ratio test to, but I only get that $c\limsup |\frac{a_{n+1}}{a_n}|\leq 1$ which is useless. I also thougth the root test could be useful, but again I reached nothing.
I'm looking for just a few hints, not complete answers, I only know pretty basic stuff about power series (root/ratio test, limsups/infs and not much more).

A: Hint: For any $x \in \mathbb R,$ $a_nx^n = a_nc^n(x^n/c^n).$


text:
Q: How to compute the monodromy group for a given differential equation. Given a differential equation, say
$\frac{d^2f}{dz^2}+\frac{f}{z-5}=0$. We know that this equation has two linearly independent solutions $f_1(z), f_2(z)$. By analytic continuation, the solution $f_i$ is taken to $g_i$, $i=1, 2$, and $g_i=c_{i1}f_1+c_{i2}f_2$. The set of matrices $(c_{ij})$ form a group called monodromy group. My question is how to compute the monodromy group explicitly?

A: For the sake of simplicity, say you are talking about the equation $\frac{d^2f}{dz^2} = f/z$. For each nonzero $z_0$, one can search for power series at $z_0$ : we look for sequences $(a_n)$ such that $f(z) = \sum a_i (z-z_0)^i$ is a solution near $z_0$. Given the first two coefficients, you can quickly determine all the others. This gives you a linear space of dimension $2$ of solutions near $z_0$ with a radius of convergence probably bounded by $|z_0|$. Suppose for the sake of the argument that nothing especially bad happens away from $0$ and that this radius is always $|z_0|$
Then, if $|z_1 - z_0| \le |z_0|$, you should have a linear map from the solutions near $z_0$ to the solutions near $z_1$, simply by taking a power series at $z_0$ and looking at what it's like at $z_1$
For example, starting from the set of power series at $1$ that are solution to the differential equation near $1$, you get a map to the set of power series at $\exp(2i\pi/8)$, and from there to the set of power series at $\exp(4i\pi/8)$, and so on. In $8$ steps you can do a full loop around $0$ and return back to $1$. This gives you a way to approximate the monodromy map even if you don't have an exact map for each step.
For the case at hand, keeping only $100$ coefficients to compute the maps, and doing those $8$ steps we find that the power series $a + b(z-1) + \ldots$ is sent to $[a+i(k_1a+k_2b)] + [b+i(k_3a-k_1b)](z-1) + \ldots$ where $k_1 = 22.7827821414\ldots, k_2 = -15.8972480162\ldots, k_3 = 32.6506299438\ldots$.
We find that the if $T$ is the corresponding matrix, $\operatorname{tr}(T) = 2$ and $\det(T) = 1$. Its eigenvalues are $1$, and $T$ is equivalent to $\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}$ .
In particular, $k_1^2+k_2k_3=0$, and if $f_1(z) = k_1 + k_3(z-1)\ldots$ then $T(f_1) = f_1$, and if $f_2(z) = k2-(1+i)k_1(z-1) + \ldots$ then $T(f_2) = f_2+k_2f_1$.
If nothing bad happens elsewhere, $f_1$ has a zero at $0$ and is actually an entire function, while $f_2$ is "a function of $\log(z)$", by which I mean that there is an entire function $g_2$ (which is a solution of a corresponding differential equation) such that $g_2(z) = f_2(\exp z)$ on a neighbourhood of $0$. In this setting, $g_1$ is a $2i\pi$-periodic entire function, and the monodromy is just translating by $2i\pi$ so $g_2(z+2i\pi) = g_2(z)+k_2f_1(z)$. And actually, for every solution $g$ there is a constant $k \in \Bbb C$ such that $g(z+2i\pi) = g(z) + kg_1(z)$

From this newfound knowledge, we can look for solutions of the form $f(z) = \sum_{k \ge 0} a_k z^k + \sum_{k \ge 1} b_k z^k \log(z)$ around $0$, and we find some solutions $f_1(z) = \sum_{n \ge 1} \frac {z^n}{n!(n-1)!}$ and $f_2(z) = \sum_{n \ge 1} \frac {z^n (\log(z) + 1 - H_n - H_{n-1})}{n!(n-1)!}$, which are entire (as functions of $\log(z)$). It is quick to check that the monodromy group acts on them by $T(f_1) = f_1$ and $T(f_2) = f_2+2i\pi f_1$


text:
Q: Border lines between labels tcl tk I have a GUI that has a few check buttons and information about the check buttons displayed beside it. The information comes from an array of lists. Each element in the array has multiple categories of information associated with it. I want to place this information in an easy to view GUI. Currently the GUI has the code below. The buttons have no functionality right now, that will come later but what I want to figure out is how to add border lines between each category, basically make the whole thing look more like a table:
set tics(ticket1) [list "status1" "ec1"]
set tics(ticket2) [list "status2" "ec2"]
set tics(ticket3) [list "status3" "ec3"]
set cv [canvas .cs  -yscrollcommand [list .sy set]]
set intro [frame $cv.intro]
set lab [label $intro.lab -text "Please click block"]
wm title . "Warning!"
set frame [frame $cv.frame ]
set l1 [label $frame.l1 -text "Block"  -padx $padding]
set l2 [label $frame.l2 -text "Status"  -padx $padding]
set l3 [label $frame.l3 -text "Effort Category" -padx $padding]
set sy [scrollbar .sy -orient v -command [list $cv yview]]
    pack $cv -expand 1 -fill both -side left
pack $intro $lab
pack $sy -side right -fill y
grid $l1 -row 0 -column 0 -ipadx $padding -sticky $stickiness
grid $l2 -row 0 -column 1 -ipadx $padding -sticky $stickiness
grid $l3 -row 0 -column 2 -ipadx $padding -sticky $stickiness

set row 1
foreach tic [array names tics] {
        set a [checkbutton $frame.f$tic -text $tic]
    set c 0
    foreach element $tics($tic) {
        set t$c [label $frame.l$tic$c -text $element -padx $padding]
        set c [expr $c+1]
    }
    grid $a -row $row -column 0 -ipadx $padding -sticky $stickiness
    grid $t0 -row $row -column 1 -ipadx $padding -sticky $stickiness
    grid $t1 -row $row -column 2 -ipadx $padding -sticky $stickiness

    set row [expr $row+1]
}
pack $frame

A: For the full table effect, use the tktable extension package. It's designed for it.
Alternatively, you can create separator widgets with ttk::separator; they do nothing except draw themselves as a line, either horizontal or vertical (according to how you configure them). Try doing something like this:
button .b1 -text "This is b1"
button .b2 -text "This is b2"
button .b3 -text "This is b3"
button .b4 -text "This is b4"
ttk::separator .s1
ttk::separator .s2

# Basic grid, in pattern style
grid .b1 .s1 .b2
grid .s2  -   -    -sticky ew
grid .b3  x  .b4
# Note that we're *forcing* separator widgets to overlap!
grid configure .s1 -rowspan 3 -sticky ns

Whether this looks OK will depend on the visual style you're using. You can change the colour of rows by putting a frame underneath each of the rows that you want to change (you'll probably have to lower it, and you'll have to force exactly which cells it occupies).
Stacking widgets can lead to some really awesome effects, but it's significantly trickier to get right. If you really want a table, I recommend just using tktable as that actually has a tabular model as opposed to something hacked together.


text:
Q: How to open a non standard port on windows azure virtual machine I can't seem to figure this out and hoping someone can give me some pointers.  I'm unable to open a port on a Azure VM.  After a fresh provision of a Windows 2008 VM I've disabled the Windows Software Firewall for all networks.  Next i went to the azure management portal and added a TCP endpoint for port 9090 (both public and private).
While connected to the server via RDP i visit http://www.canyouseeme.org/ to test if port 9090 is open.  But it comes back as error cannot see the port 9090.
As far as I can tell this is a standalone VM not connected to any domains or special networks.
Any ideas what is missing?

A: This was a strange problem that i "fixed" by changing the VM size from extra small > small and back again.  For some reason something was reset and i could open the port again.


text:
Q: Checkear si una variable es undefined en Angular Traigo una petición de un servidor, el cual trae información. Alguna de estas variables, según la petición que hago, vienen como "undefined".
Necesito mostrar en html un formulario u/o otro según el valor de estas variables.
Estoy intentando esto a raiz de que null==undefined Sacado de aquí la conclusión
*ngIf="variable != null"
*ngIf="variable" //TAMPOCO FUNCIONA

Pero parece no funcionar, ya que siempre me muestra el formulario.
¿Alguna idea?

A: El problema es que estás malinterpretando algunas cosas. Si bien la respuesta que aparece en S.O. dice textualmente:

Because null == undefined is true

Realmente no se refiere a que sean iguales y puedas compararlas alegremente, de hecho te sugiero que en lo posible no hagas ese tipo de comparaciones. (Comparación de conversión de tipos)
Para solucionar tu problema tienes algunas opciones:

*

*Usar simplemente el operador ! ante puesto a tu variable. En este caso te interesa ponerlo 2 veces. Más adelante explico el porqué. Sin embargo esto tiene un problema, ya que si la variable que recibes es numérica, y el cero (0) es un valor válido para mostrar el elemento, esta técnica no te servirá.

*Usar la comparación estricta. Esto tal vez sea lo más adecuado, ya que de esta forma te aseguras que sólo mostrarás el elemento si la variable es diferente de undefined en todo sentido.

Dicho esto, tienes estas dos formas de realizar la tarea:
// usando doble negación

// usando comparación estricta

En el primer caso se realiza una doble negación, que realiza una conversión de la variable a un tipo boolean, cuyo valor será true si la variable es truthy (valor verdadero), y será false si la misma es falsy(valor no verdadero).
En el segundo caso, estamos realizando una comparación estricta. Dicha comparación (!==) devolverá false únicamente si la variable es de tipo undefined, cualquier otro tipo distinto que tenga la variable, devolverá true. Así, el elemento sólo se mostrará si la variable recibida es distinta de undefined.
Espero que esto responda tu duda.

A: La opción más corta seria usar un metodo para el ngIf
Prueba esto *ngIf="variableNula()" en la vista
y luego del lado del controlador armas el metodo
variableNula(){
if ( variable == null || variable == undefined || variable == "null" || variable == "undefined") { return false } else { return true }
}
Este metodo se fija de distintas formas si la variable es nula, si es nula retorna un false al ngIf, si esto ocurre no se mostrará la variable, pero si la variable trae algo que no sea null o undefined, va a retornar un true al ngIf, esto hará que se muestre la variable en la vista.
Espero te sirva.


text:
Q: What is the catch when introducing measure theory using $\sigma$-ring instead of $\sigma$-algebra? I am currently using Matthew A Pons book Real Anaysis for Undergrad for introduction of measure theory
In my opinion this book is unbelievably clear for almost all the sections EXCEPT the section where measure is introduced. And the reason is because the author insists on using something called $\sigma$-ring for all the definitions, but litters the sections with ring and $\sigma$-algebra so in the problem section you will see that one question is with respect to $\sigma$-ring another is with respect to $\sigma$-algebra
And you will see some quite convoluted parts like:

Also let's ignore for the time being that almost all the books written post 2000s deals with $\sigma$-algebra. This book was published in 2014.
So the main question is what is the catch when developing measure theory from the perspective of $\sigma$-ring instead of $\sigma$-algebra? I know that for a ring, the condition $A^c \in \mathcal{R}$ does not hold (not closed under complement). Can someone contrast the difference in the ways that key properties of the measure are derived (or proven) with respect to a $\sigma$-ring instead of a $\sigma$-algebra?

A: There is no real catch. The concept of $\sigma$-ring is a slightly more general than the concept of $\sigma$-algebra. In fact, it is easy to see that, given a $\sigma$-ring $\Sigma$ on a set $\Omega$, then  $\Sigma$ is a  $\sigma$-algebra if and only if $\Omega\in \Sigma$.
So you might think: "why don't we develop Measure Theory based on  $\sigma$-rings?"  Surely it can be done, and very good books follow this track. For instance: Halmos, Measure Theory. HOWEVER, using  $\sigma$-rings makes the definition of measurable functions more complex and with some non-intuitive results.
As I wrote to answer another question some time ago:
Measure Theory using $\sigma$-rings will lead to a more complex notion of measurable function, with some non-intuitive results.
Let $\Omega$ be a set and let $\Sigma$ be a $\sigma$-algebra. Let $f$ be a function from $\Omega$ to $\mathbb{R}$. We say that $f$ is measurable if for every Borel set $B$ in $\mathbb{R}$, $f^{-1}(A)\in \Sigma$.
Now, suppose that $\Sigma$ is a  $\sigma$-ring and we try to use the same definition. Then, since $\Omega=f^{-1}(\mathbb{R})$, either $\Sigma$ is a  $\sigma$-algebra or there will be no measurable function from $(\Omega,\Sigma)$.
So, when working with $\sigma$-rings, we need a slightly different definition (as we find in Halmos' book). We say that $f$ is measurable if for every Borel set $B$ in $\mathbb{R}$, $[f\neq 0]\cap f^{-1}(A)\in \Sigma$.
This second definition allows the existence of measurable functions even if $\Sigma$ is just a $\sigma$-ring and not a $\sigma$-algebra. However, it leads to a few non-intuitive results. For instance: assume $\Sigma$ is just a $\sigma$-ring and not a $\sigma$-algebra. Then any non-zero constant function is NOT mensurable. As a consequence, if $f$ is measurable, then it is easy to prove, for instance, that $f+1$ is NOT measurable.
So, the theory of measurable and integrable functions is more naturally developed by using $\sigma$-algebras, instead of just $\sigma$-rings.
You may also be interested in reading my answer in Two different definitions of General Measurable Function .


text:
Q: add swipe tab to fragment Hi everybody,this is my app

I wanna add 2 swipe tab Accounts Activity and Chart to a fragment_accounts.xml layout.
I have navigation drawer menu too.
this is fragment_accounts.xml:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></android.support.v4.view.ViewPager>

and this is AccountsFragment.java:
I get this error

Error:(44, 33) error: incompatible types: android.app.ActionBar cannot
  be converted to android.support.v7.app.ActionBar

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.rastari.salar.mymetarialbank.R;
import com.rastari.salar.mymetarialbank.adapter.TabsPagerAdapter;

public class AccountsFragment extends FragmentActivity implements ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = {"Accounts Acctivity", "Chart Activity"};

    public AccountsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        // Inflate the layout for this fragment
        return rootView;
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }
}

and this is TabsPagerAdapter: I get this error:

Error:(25, 24) error: incompatible types: AccountsActivityFragment
  cannot be converted to Fragment

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.rastari.salar.mymetarialbank.activity.AccountsActivityFragment;
import com.rastari.salar.mymetarialbank.activity.ChartActivity;

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
            case 0:
                return new AccountsActivityFragment();

            case 1:
                return new ChartActivity();

        }
        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 2;
    }
}

I searched whole the internet to find how to create an app with navigation drawer menu and swipe tabs tutorial, but i found nothing.
please help this is very important to me.
thank you.

A: For your actionBar
You should be calling getSupportActionBar() instead of getActionBar()
For your fragment, make sure they both extend the android.support.v4.Fragment and not the android.app.Fragment


text:
Q: MAX of a Date column using HQL with inner join I am trying to find the maximum value of a Date column in mySQL DB using hibernate query language with inner join
@Query("select u, CAST(MAX(o.last_modified AS DATE)) from com.dw.model.user.User as u left join com.dw.domain.order.Order as o on u.username=o.techid group by o.techid")
List<User> findUsers();

i am getting this error :-
expecting CLOSE, found 'AS' near line 1, column 36 [select u, CAST(MAX(o.last_modified AS DATE)) from com.dw.model.user.User as u left join com.dw.domain.order.Order as o on u.username=o.techid group by o.techid]
Can anyone please help me out by telling me how to write this in Hibernate?

A: A couple of issues with the query.
1) A table alias u was being selected. Because, you are grouping by o.techid, i assume you would need it in the select. If you need some columns from u, explicitly specify them in the select and group by those columns.
2) CAST(MAX(o.last_modified AS DATE)) should have been CAST(MAX(o.last_modified) AS DATE)
select o.techid, CAST(MAX(o.last_modified) AS DATE)
from com.dw.model.user.User as u
left join com.dw.domain.order.Order as o on u.username=o.techid
group by o.techid


text:
Q: vbc.exe takes up all free memory when debugging I recently encountered a problem debugging my asp.net webforms application programmed in vb.net
When a particular form is opened during debugging, the vbc.exe process takes all available memory and locks the entire system until msvmon hangs.
This process is repeated again and again until vbc.exe and w3wp.exe are killed manually
I'm using Visual Studio 2012 Professional, debugging on local machine with IIS
Any ideas?

A: Solved. It was because of an orfan div close tag between ContentTemplate and UpdatePanel closing tags.


text:
Q: What's stopping us from supporting Windows NT applications on Linux? Disclaimers:
First off, I'm not 100% sure if I'm in the right StackExchange community for this question, but I couldn't find one for generic operating system questions. Please let me know if I should move this elsewhere.
Secondly, please excuse my ignorance if this is a stupid question - my knowledge on the inner workings of operating systems at this point is limited to what I've learned over the years randomly and an undergrad "operating systems" course that taught basic concepts like memory management and CPU control using XINU.
Question:
What is the issue (or some of the issues) that prevent us from developing a single kernel that supports both Linux Kernel and Windows NT system calls? At an extremely basic level, I would expect that it would be possible (if time-consuming) for me to create a modified version of the linux kernel that also supports Windows-style system calls.
If I were to make the aforementioned frankenstein kernel (and tell it how to interpret microsoft's '.exe' executable format), would I then be able to run both windows-based and unix-based executables?
I'm not super knowledgeable on WINE, but I imagine it does something like this, acting as a sort of compatibility layer that converts the windows calls into their linux equivalents. So what's stopping us from adding this sort of functionality into the kernel itself (thus skipping the overhead)?
Is it a copyright issue with Microsoft? Is it just that the two operating systems are so vastly different under the hood that this cant be done at all?
I've searched for information about this (or at least explanations of why it can't/hasn't been done) but didn't find much. I did come across a project called Longene where it looks like a group in China was attempting to do exactly this, but it seems to have died as quickly as it started.
My thinking is that maybe something like this would just be too large of an undertaking/too much maintenance to be worth it. However, I'd like to get some input from people who have a deeper understanding of operating systems, and this seems like the right place for that (considering there can't be a community for Windows kernel developers, as it's all proprietary).

A: In one sense it has been or is being attempted. The REACT OS is an attempt to clone the Win 95 OS and the problems they have encountered are representative of any attempt that might be made to clone NT.

*

*Microsoft purposely develops updates and changes faster than programmers can reveres engineer clones. Microsoft has always started
development of their next generation OS before the current one is
released and keeps the features and code proprietary. Before Win 7 was released, they had already started Win 10, and Win 11 was started before the release of Win 10. (And yes they lied that Win 10 was the last OS!) They are working on their next two generations as we speak.

*Microsoft products are not generally appealing enough to a large
enough audience to take the time to clone. Rather most people want
something "better" or different.

*The REACT OS mentioned above is still fairly unstable after 20+
years of development. Additionally, hardware changes at such a rapid
state that even if they had a stable version 5-10 years ago, new
hardware requirements would probably over tax the groups
accomplishments.
Imagine the effort that would be needed just to maintain compatibility with all the new sound and video cards and chips! It would be a never ending thankless job :(

A:
What is the issue (or some of the issues) that prevent us from developing a single kernel that supports both Linux Kernel and Windows NT system calls?

*

*Developerhours available.

*there's a few ways in which Windows and Linux are different; If you guarantee "concurrent write access to files always comes in ordered at all readers" for one API and for the other you guarantee "no write access might ever be blocked by another write", then you got a logical conflict (I don't know whether this example applies to the two OSes, btw.). You can abstract one away from the other, but often, you lose some capabilities on the way.

At an extremely basic level, I would expect that it would be possible (if time-consuming) for me to create a modified version of the linux kernel that also supports Windows-style system calls.

WindowsNT has a POSIX API, i.e. a UNIX-style API (since NT4!), and Linux (pretty much) also does. So, in a way, that operating system exists, and it's Windows.

I'm not super knowledgeable on WINE, but I imagine it does something like this, acting as a sort of compatibility layer that converts the windows calls into their linux equivalents.

Yep! Translates a few syscalls, offers (parts of) the userland libraries that come with windows, among other things.

Is it a copyright issue with Microsoft?

Probably not. Oracle vs Google on the Java API has court-proven that you can't copyright an API (in the US). I'm not a lawyer, though, and it's hard to see how well this would extend to the Windows API. But WINE's not gotten into trouble, so it's probably hard to start enforcing this now.

If I were to make the aforementioned frankenstein kernel (and tell it how to interpret microsoft's '.exe' executable format), would I then be able to run both windows-based and unix-based executables?

Ignoring the word "kernel" in there: together with WINE and the Linux kernel's binfmt_misc, you can do this (for quite some Windows software) today. It's quite commonly done!


text:
Q: File Upload to HTTP server in iphone programming Can anyone provide me some links or examples to upload files to the HTTP server using
  iphone APIs.

A: The code below uses HTTP POST to post NSData to a webserver. You also need minor knowledge of PHP.
NSString *urlString = @"http://yourserver.com/upload.php";
NSString *filename = @"filename";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:YOUR_NSDATA_HERE]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"%@", returnString);

A: I used ASIHTTPRequest a lot like Jane Sales answer but it is not under development anymore and the author suggests using other libraries like AFNetworking.

Honestly, I think now is the time to start looking elsewhere.

AFNetworking works great, and let you work with blocks a lot (which is a great relief).
Here's an image upload example from their documentation page on github:
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

A: ASIHTTPRequest is a great wrapper around the network APIs and makes it very easy to upload a file. Here's their example (but you can do this on the iPhone too - we save images to "disk" and later upload them.
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

A: This is a great wrapper, but when posting to a asp.net web page, two additional post values need to be set:
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    //ADD THESE, BECAUSE ASP.NET is Expecting them for validation
    //Even if they are empty you will be able to post the file
    [request setPostValue:@"" forKey:@"__VIEWSTATE"];
    [request setPostValue:@"" forKey:@"__EVENTVALIDATION"];
    ///

    [request setFile:FIleName forKey:@"fileupload_control_Name"];
    [request startSynchronous];

A: Try this.. very easy to understand & implementation...
You can download sample code directly here https://github.com/Tech-Dev-Mobile/Json-Sample
- (void)simpleJsonParsingPostMetod
{

#warning set webservice url and parse POST method in JSON
    //-- Temp Initialized variables
    NSString *first_name;
    NSString *image_name;
    NSData *imageData;

    //-- Convert string into URL
    NSString *urlString = [NSString stringWithFormat:@"demo.com/your_server_db_name/service/link"];
    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    //-- Append data into posr url using following method
    NSMutableData *body = [NSMutableData data];

    //-- For Sending text

        //-- "firstname" is keyword form service
        //-- "first_name" is the text which we have to send
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@",first_name] dataUsingEncoding:NSUTF8StringEncoding]];

    //-- For sending image into service if needed (send image as imagedata)

        //-- "image_name" is file name of the image (we can set custom name)
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    //-- Sending data into server through URL
    [request setHTTPBody:body];

    //-- Getting response form server
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    //-- JSON Parsing with response data
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Result = %@",result);
}

A: This isn't an alternative solution; rather a suggestion for Brandon's popular answer (seeing as though I don't have enough rep to comment on that answer).  If you're uploading large files; you're probably going to get a mmap malloc exception on account of having to read the file into memory to post it to your server.
You can tweak Brandon's code by replacing:
[request setHTTPBody:postbody];

With:
NSInputStream *stream = [[NSInputStream alloc] initWithData:postbody];
[request setHTTPBodyStream:stream];

A: I thought I would add some server side php code to this answer for any beginners that read this post and are struggling to figure out how to receive the file on the server side and save the file to the filesystem.
I realize that this answer does not directly answer the OP's question, but since Brandon's answer is sufficient for the iOS device side of uploading and he mentions that some knowledge of php is necessary, I thought I would fill in the php gap with this answer.
Here is a class I put together with some sample usage code. Note that the files are stored in directories based on which user is uploading them. This may or may not be applicable to your use, but I thought I'd leave it in place just in case.
<?php

class upload
{
    protected $user;

    protected $isImage;
    protected $isMovie;

    protected $file;
    protected $uploadFilename;
    protected $uploadDirectory;
    protected $fileSize;
    protected $fileTmpName;
    protected $fileType;
    protected $fileExtension;

    protected $saveFilePath;

    protected $allowedExtensions;

function __construct($file, $userPointer)
{
    // set the file we're uploading
    $this->file = $file;

    // if this is tied to a user, link the user account here
    $this->user = $userPointer;

    // set default bool values to false since we don't know what file type is being uploaded yet
    $this->isImage   = FALSE;
    $this->isMovie   = FALSE;

    // setup file properties
    if (isset($this->file) && !empty($this->file))
    {
        $this->uploadFilename   = $this->file['file']['name'];
        $this->fileSize         = $this->file['file']['size'];
        $this->fileTmpName      = $this->file['file']['tmp_name'];
        $this->fileType         = $this->file['file']['type'];
    }
    else
    {
        throw new Exception('Received empty data. No file found to upload.');
    }

    // get the file extension of the file we're trying to upload
    $tmp = explode('.', $this->uploadFilename);
    $this->fileExtension        = strtolower(end($tmp));

}

public function image($postParams)
{
    // set default error alert (or whatever you want to return if error)
    $retVal = array('alert' => '115');

    // set our bool
    $this->isImage = TRUE;

    // set our type limits
    $this->allowedExtensions    = array("png");

    // setup destination directory path (without filename yet)
    $this->uploadDirectory      = DIR_IMG_UPLOADS.$this->user->uid."/photos/";

    // if user is not subscribed they are allowed only one image, clear their folder here
    if ($this->user->isSubscribed() == FALSE)
    {
        $this->clearFolder($this->uploadDirectory);
    }

    // try to upload the file
    $success = $this->startUpload();

    if ($success === TRUE)
    {
        // return the image name (NOTE: this wipes the error alert set above)
        $retVal = array(
                        'imageName' =>  $this->uploadFilename,
                        );
    }

    return $retVal;
}

public function movie($data)
{
    // update php settings to handle larger uploads
    set_time_limit(300);

    // you may need to increase allowed filesize as well if your server is not set with a high enough limit

    // set default return value (error code for upload failed)
    $retVal = array('alert' => '92');

    // set our bool
    $this->isMovie = TRUE;

    // set our allowed movie types
    $this->allowedExtensions = array("mov", "mp4", "mpv", "3gp");

    // setup destination path
    $this->uploadDirectory = DIR_IMG_UPLOADS.$this->user->uid."/movies/";

    // only upload the movie if the user is a subscriber
    if ($this->user->isSubscribed())
    {
        // try to upload the file
        $success = $this->startUpload();

        if ($success === TRUE)
        {
            // file uploaded so set the new retval
            $retVal = array('movieName' => $this->uploadFilename);
        }
    }
    else
    {
        // return an error code so user knows this is a limited access feature
        $retVal = array('alert' => '13');
    }

    return $retVal;
}

//-------------------------------------------------------------------------------
//                          Upload Process Methods
//-------------------------------------------------------------------------------

private function startUpload()
{
    // see if there are any errors
    $this->checkForUploadErrors();

    // validate the type received is correct
    $this->checkFileExtension();

    // check the filesize
    $this->checkFileSize();

    // create the directory for the user if it does not exist
    $this->createUserDirectoryIfNotExists();

    // generate a local file name
    $this->createLocalFileName();

    // verify that the file is an uploaded file
    $this->verifyIsUploadedFile();

    // save the image to the appropriate folder
    $success = $this->saveFileToDisk();

    // return TRUE/FALSE
    return $success;
}

private function checkForUploadErrors()
{
    if ($this->file['file']['error'] != 0)
    {
        throw new Exception($this->file['file']['error']);
    }
}

private function checkFileExtension()
{
    if ($this->isImage)
    {
        // check if we are in fact uploading a png image, if not return error
        if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'image/png' || exif_imagetype($this->fileTmpName) != IMAGETYPE_PNG)
        {
            throw new Exception('Unsupported image type. The image must be of type png.');
        }
    }
    else if ($this->isMovie)
    {
        // check if we are in fact uploading an accepted movie type
        if (!(in_array($this->fileExtension, $this->allowedExtensions)) || $this->fileType != 'video/mov')
        {
            throw new Exception('Unsupported movie type. Accepted movie types are .mov, .mp4, .mpv, or .3gp');
        }
    }
}

private function checkFileSize()
{
    if ($this->isImage)
    {
        if($this->fileSize > TenMB)
        {
            throw new Exception('The image filesize must be under 10MB.');
        }
    }
    else if ($this->isMovie)
    {
        if($this->fileSize > TwentyFiveMB)
        {
            throw new Exception('The movie filesize must be under 25MB.');
        }
    }
}

private function createUserDirectoryIfNotExists()
{
    if (!file_exists($this->uploadDirectory))
    {
        mkdir($this->uploadDirectory, 0755, true);
    }
    else
    {
        if ($this->isMovie)
        {
            // clear any prior uploads from the directory (only one movie file per user)
            $this->clearFolder($this->uploadDirectory);
        }
    }
}

private function createLocalFileName()
{
    $now = time();

    // try to create a unique filename for this users file
    while(file_exists($this->uploadFilename = $now.'-'.$this->uid.'.'.$this->fileExtension))
    {
        $now++;
    }

    // create our full file save path
    $this->saveFilePath = $this->uploadDirectory.$this->uploadFilename;
}

private function clearFolder($path)
{
    if(is_file($path))
    {
        // if there's already a file with this name clear it first
        return @unlink($path);
    }
    elseif(is_dir($path))
    {
        // if it's a directory, clear it's contents
        $scan = glob(rtrim($path,'/').'/*');
        foreach($scan as $index=>$npath)
        {
            $this->clearFolder($npath);
            @rmdir($npath);
        }
    }
}

private function verifyIsUploadedFile()
{
    if (! is_uploaded_file($this->file['file']['tmp_name']))
    {
        throw new Exception('The file failed to upload.');
    }
}

private function saveFileToDisk()
{
    if (move_uploaded_file($this->file['file']['tmp_name'], $this->saveFilePath))
    {
        return TRUE;
    }

    throw new Exception('File failed to upload. Please retry.');
}

}

?>

Here's some sample code demonstrating how you might use the upload class...
// get a reference to your user object if applicable
$myUser = $this->someMethodThatFetchesUserWithId($myUserId);

// get reference to file to upload
$myFile = isset($_FILES) ? $_FILES : NULL;

// use try catch to return an error for any exceptions thrown in the upload script
try
{
    // create and setup upload class
    $upload = new upload($myFile, $myUser);

    // trigger file upload
    $data   = $upload->image();     // if uploading an image
    $data  = $upload->movie();      // if uploading movie

    // return any status messages as json string
    echo json_encode($data);
}
catch (Exception $exception)
{
    $retData = array(
            'status'    => 'FALSE',
            'payload'   => array(
                            'errorMsg' => $exception->getMessage()
                            ),
                );

    echo json_encode($retData);
}

A: I have made a lightweight backup method for the Mobile-AppSales app available at github
I wrote about it here http://memention.com/blog/2009/11/22/Lightweight-backup.html
Look for the - (void)startUpload method in ReportManager.m

A: An update to @Brandon's answer, generalized to a method
- (NSString*) postToUrl:(NSString*)urlString data:(NSData*)dataToSend withFilename:(NSString*)filename
{
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:dataToSend]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];

    NSError* error;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (returnData) {
        return [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    }
    else {
        return nil;
    }
}

Invoke like so, sending data from a string:
[self postToUrl:@"<#Your url string#>"
           data:[@"<#Your string to send#>" dataUsingEncoding:NSUTF8StringEncoding]
   withFilename:@"<#Filename to post with#>"];


text:
Q: Any possibility of adding new UI components within the Kibana Dashboard? Let's say I'm having few Kibana dashboards created upfront, and what I need to know is that will it be possible for me to add a UI component, for example a print button  within the dashboard itself, in order for the user to print the dashboard externally?  Apart from the feature to export it as a PDF, which is given by Kibana implicitly.
Any help could be appreciated. :)


text:
Q: Show that there are $(\alpha_m)_{m\in\mathbb{N}}$ and $(A_m)_{m\in\mathbb{N}}$ such that $f(x) = \sum_{m=1}^\infty\alpha_m\chi_{A_m}(x)$ Assignment:

Let $f: \mathbb{R}^n \rightarrow [0,\infty]$ be measurable. Show that, there is non-negative sequence $(\alpha_m)_{m\in\mathbb{N}} \subset [0,\infty)$ and a sequence $(A_m)_{m\in\mathbb{N}}$ of measurable subsets $A_m \subset \mathbb{R}^n$ such that
  $$f(x) = \sum_{m=1}^\infty\alpha_m\chi_{A_m}(x)$$

I understand the idea behind the simple functions but I am unsure on how to begin.
I'd appeciate any help.

A: This can be done in a rather elegant way. The primary thing to note is this means that the set of $A_m$ such that $x\in A_m$ must entirely determine the value of $f(x)$. Suppose we wrote out a sequence, $(k_m)_{m\in\mathbb N}$ defined by
$$k_m=\chi_{A_m}(x)$$
which basically just lists what sets $x$ is a part of. We would then have that $\sum_m \alpha_mk_m=f(x)$. So we are trying to, from a sequence of bits, determine a number. So, letting the sum run over all of $\mathbb{Z}$ instead of just $\mathbb{N}$ (which is easily justified), we could set $\alpha_m=2^m$ and then we have
$$\sum_{m\in\mathbb Z}2^mk_m=f(x)$$
meaning that $k_m$ would be exactly the binary representation of $f(x)$. Thus, if we define $A_m$ to be the set of $x$ such that $f(x)$ has a $1$ at the $m^{th}$ digit of its binary expansion, we have put $f$ in the desired form. Moreover, we can write
$$A_m=f^{-1}\left[\bigcup_{i=0}^{\infty}[2^{m}(2i+1),2^{m}(2i+2))\right]$$
where the inner set is measurable, implying so is the preimage $A_m$.


text:
Q: Convert PHAsset/AVAsset to mp4 video in Nativescript app I use the nativescript-imagepicker-plugin for a filepicker.
This returns a PHAsset.
I have to copy it to a temporary directory to upload it.
Im new in iOS, so I tried a bit:
const options = PHVideoRequestOptions.new();
options.version = PHVideoRequestOptionsVersion.Current;
PHImageManager
    .defaultManager()
    .requestAVAssetForVideoOptionsResultHandler(
        phAsset
        , options
        , (avAsset, audioMix, info) => {
            try {

                const tempFilePath = path.join(tempFolderPath, `${Date.now()}.mp4`);
                const targetURL = NSURL.fileURLWithPath(tempFilePath);
                const exportSession = AVAssetExportSession.alloc(avAsset, AVAssetExportPresetPassthrough);
                exportSession.outputUrl = targetURL;
                exportSession.outputFileType = AVFileTypeMPEG4;
                exportSession.exportAsynchronouslyWithCompletionHandler(() => {
                    console.log(exportSession.status);
                });
            }
            catch (e) {
                console.log(e);
            }
        }
    );

My code crashes without error, so I don't know where to start to debug.
I want a MP4, to show it in web too.
At the end I need a string (path) to a mp4 file to upload id with nativescript-background-http.

A: Your syntax seems to be wrong
const exportSession = AVAssetExportSession.alloc().initWithAssetPresetName(avAsset, AVAssetExportPresetPassthrough);
exportSession.outputURL = targetURL;


text:
Q: VB.NET and ASP.NET DLL line numbers don't appear in production error logs I can see line numbers in my error logs in our development environment, in which VB.NET 2005 and ASP.NET components are compiled in debug mode, with PDB files copied to the server on deployment.
I don't see line numbers in production, where things are compiled in release mode, and presumably no PDB files are created or deployed? Can someone explain a way to compile and release production-ready components that show the line number in a stack trace? Debug code that works in dev below:
st = New StackTrace(err, True)

For i As Integer = 0 To st.FrameCount - 1
  Dim sf As StackFrame = st.GetFrame(i)
  system.diagnostics.debug.print sf.GetFileLineNumber
Next i

A: Take a look at this article. Basically you need to configure your project to still output PDBs even when running in release mode.


text:
Q: Using QBWeb Connector to Sync Customers I am facing this issue, when i am trying to create new customer in Quick Books.
I was having actual name of Customer at my php side was "IbáñezOmar" and when it converts to UTF-8 encoding, it becomes "IbáñezOmar".
But when this customer created in Quick Books the name totally changes to "Ib????ezOmar"
Please can anyone help how can i fix this issue?
<?xml version="1.0" encoding="utf-8"?><?qbxml version="11.0"?>
<QBXML>
  <QBXMLMsgsRq onError="continueOnError">
    <CustomerAddRq>
      <CustomerAdd>
        <Name >IbáñezOmar</Name>
        <IsActive >1</IsActive>
        <CompanyName >IbáñezOmar</CompanyName>
        <Salutation ></Salutation>
        <FirstName >Omar</FirstName>
        <LastName >Ibáñez</LastName>
        <Contact >Omar Ibáñez</Contact>
      </CustomerAdd>
    </CustomerAddRq>
  </QBXMLMsgsRq>
</QBXML>


text:
Q: Components of vector in symbol computation I want to define a $3d$ vector $\gamma^{j}_{i}$ (here $i$ is the space node index, and $j$ is the time node index, in other words, suppose we have a time-space grid, and $\gamma$ is the vector variable in this gird).
Here is a simple example, if $\gamma^{j}_{i}$ and $\gamma^{j+1}_{i}$ have some relationship, um, like $\gamma^{j+1}_{i} - \gamma^{j}_{i} = [1,2,3]^T$, can i write in MMA to get the components expression?
I have tried to define $\gamma^{j+1}_i$ in components form like $\gamma^{j+1}_{1,i}$,$\gamma^{j+1}_{2,i}$ ,$\gamma^{j+1}_{3,i}$.
So in MMA, Subscript[\[Gamma], i]^(j + 1) =  Transpose[{Subscript[\[Gamma], 1, i]^(j + 1), Subscript[\[Gamma], 2,  i]^(j + 1), Subscript[\[Gamma], 3, i]^(j + 1)}]
But MMA tells me the tag power in $\gamma^{j+1}_i$ protect! I know I can define $\gamma$ like $\gamma = \{a,b,c\}^T$.
The reason I want to use subscript and superscript here is to make the output more intuitive When the vector variable has a complicated relationship.
Can I Let the MMA symbol computation result be what you see is what you get? in this example is $$\gamma^{j+1}_{1,i} - \gamma^{j}_{1,i} = 1, $$ $$\gamma^{j+1}_{2,i} - \gamma^{j}_{2,i} = 2,$$ $$ \gamma^{j+1}_{3,i} - \gamma^{j}_{3,i} = 3 $$
Any comments will be very appreciated, and wish you have a good day!

A: In Mathematica notation, ^ means raising to a power, so for a certain $j$, say $j = 1$, Subscript[\[Gamma], i]^2 = Subscript[\[Gamma], i] * Subscript[\[Gamma], i] and so on.  This is why the assignment fails.
One way around can be to define a vector function defined on integer values of arguments, such as g[i,j].  Then it is possible to write things like
g[i_, j_ + 1 ] = g[ i ,j ] + { 1,2,3 }

Note that Mathematica does not distinguish between column and row vectors (a tutorial on this).


text:
Q: python storing a live variable on disk I am using python 3, and have heavy variables in memory, I would like to seamlessly allowing myself to write them to disk, and load them when I actually need them, without the need for pickling and reading from disk explicitly any time I need them. Is that at all possible and how?
I tried RDFlip but this does not seem to work
It's a store that you need to explicitly approach, and I am trying to make it seamless.

A: You might want to look into something like an Object Relational Mapping (ORM) library that lets you store the objects to a database, and retrieve them by using Python method/function calls (rather than SQL statements). SQLAlchemy is one of the most popular ORMs for python, and has tons of documentation and community support available online. You would have to do the "explicit" work you are talking about only once, when defining your database tables and configuring DB connectivity, etc for SQLAlchemy, But then after that, you could just use a single method call to write your variables to disk (in the DB), and another for retrieving them. And unlike pickle, you can store any binary object in your database, so you aren't limited as far as what kind of data you can serialize/store.

A: have you tried HDF5. I think this will be something what you are looking for.
HDF5