Why do Juice cartons fail on opening?

Question: When I open a simple juice carton I fail on opening. I always seem to waste some of the concentrated juice on the kitchen sink and I wonder – do I do it wrong or is it the package that does not have a useful design?
Comment: if the average juice-drinker can't open it... bad design. maybe their mgmt only drinks freshly-squeezed.
Comment: Absolutely right, @jberger! The fundamental thing to do would be to test your product before release, or sell a handy tool to increase the after sales market.
Answer: The problem is that the seal needs to be good enough to keep the juice inside, throughout its journey to your fridge. At the same time, the opening process needs to be easy enough to tear by hand. In many cases, this balance is not reached, because it is too hard to open.
The process of manually opening a juice carton involves holding tight and tearing ( or cutting ). It is quite an aggressive action. In the process of making this hole in the packaging, there is a likelihood of the package shaking, spilling the juice.
Most of the more advanced methods - as Liam indicated - remove the need to grip the carton so tightly. But, of course, they cost a bit more.
Comment: True that, I'd love to have a non-contaminated juice as it arrives to my fridge. On the same time I want to be able to open the carton without losing the juice or have to clean up the kitchen afterwards. That's a really tough design issue which needs to be addressed, and I imagine is what engineers in the field are struggling with every day. I'd love to have a more advanced carton and pay the extra quarter, but I might not belong to the majority with that opinion?
Comment: @BennySkogberg some do, but they often want better quality juice to, and so pay the extra 10% for better juice AND better opening. On the budget end, this is not cost-justifiable.
Answer: Definitely poor design! I avoid those types of juice containers for that very reason.
Another design that seems like it should be good, but always seems to leak, is this one:

Screw-top FTW.
Comment: I agree Liam, these carton openings is just as bad. Even when you try to open them you should use force to break the paper and enable the juice to pour out of the carton. Thanx for your reply!
Answer: Cartons definitely need re-design. The case is being:

Material - Cartons are light in weight to take the load against Tin cans which takes little bit of load and pressure.
Load and Pressure - Cartons take pressure laterally and vertically, which pulls the juice out of it in rapid fashion. Lateral pressure comes in with your hand already placed on the carton walls at its center, and Vertical pressure comes in when the carton is teared upon, so as while the tearing ends, you naturally keep applying force to it laterally, as the juice comes out of the torn portion.

Solution towards this should be strengthen the material used or redesign taking the pressure fact into consideration.
Cartons as far as I seen are one with "tearable slot" as it is with tin cans, other way of cartons are one which are sealed and have or do not have "tearable slot", with tearable slots either at the top of the cartons or at the end of it - forming a triangle pattern.

Best way to address this problem is that the Cartons should have a firm wall at the center, as you even though apply pressure, it does not affect the liquid inside it.
Have a taller carton such as atleast 0.3-0.5% more than the carton's height to avoid the rush of liquid (here some extra investment is required for materials).
Redesign the tearable slot.

As you also practice along, the spill can be avoided if you had to hold the top portion of the carton without applying more pressure, need to keep it on a surface (such as you can avoid the full force).The edges of the carton are little firm than the center portion.
Comment: Re suggestion number 2 maybe crisp (potato chip) packet designers decided to do the same thing without the benefit. All packets I've seen are about 300% bigger than needed.
Comment: Thanks, @inkmarble, a very good answer. I've thought of your second suggestion myself, which would make it more likely to keep the juice inside the carton while opening.
Comment: True @GeorgeDuckett, but a little more space (not 300% but 3%) would just maybe do the trick?!
Answer: Poor design i'd say. I tend to cut off the corner, with an optional hole the other side to allow air to get in to stop the erratic pouring.
Alternatively, my mum used to have something similar to these (pictured below). That particular one is discontinued, but Amazon lists a few alternatives which look like they do the same job.
Answer: In the UK Tetrapak dominated supermarket shelves for liquid packaging,
but increasingly I see plastic and screw top waxed cartons:
http://youtu.be/2-p8YpR7rJc - No wonder !
They'd work much better if there were a tab with which to break the seal and pull the mouth open.
Comment: You haven't explained why Tetrapak has dominated the market despite being prone to spillages.

Why do Juice cartons fail on opening?


How can I remove latex paint from wall?

Question: I partly re-painted the wall using latex paint (Rust Oleum-Ultra Cover Multi-Purpose Gloss Brush-On Paint) due to some scratches on the wall, but I failed to match the color. I was wondering if it was possible to get rid of the new paint.
Answer: Sure, how much effort would you like to put in to it?
The easiest way is to paint over it.
Then there is manually or machine sanding all of the paint off.
Another option is using a paint stripper and chemically removing the paint.
Both of these last methods are quite labor intensive and make a mess.
I would buy some paint samples. Paint some scrap drywall or pieces of white cardboard. Choose a complementary color or contrasting color. Then paint one entire wall break-to-break. Or just repaint the entire room.
Good luck!
Answer: 1st it sounds like the (Rust Oleum-Ultra Cover Multi-Purpose Gloss Brush-On Paint) is not latex paint.  I have been in the drywall and painting business for many years and agree with the answers above with one exception.
I would either skim coat with drywall mud to get a smooth surface then sand and prime spray painted area then continue to paint entire wall with a color that is close to old color.  Remember that a flat paint also will hide imperfections more than satin or gloss.
Hope this helps...PC
Comment: The [datasheet](http://www.rustoleum.com/~/media/DigitalEncyclopedia/Documents/RustoleumUSA/TDS/English/CBG/Painters%20Touch/PTUC-01_Painters_Touch_Multi-Purpose_Gloss_Brush-On_Paint_TDS.ashx) for this paint says "Resin Type Water-based Acrylic" = latex in American English.

How can I remove latex paint from wall?


Given a linear mapping and a matrix prove that two products are equal.

Question: Let $L : R^n \to R^n$ be a linear mapping with standard matrix $A = [L]$, and let $B = [b_1,...,b_n]$ be an $nxn$ matrix with $rank(B) = n$. Given that $C ={b_1,...,b_n}$ is a basis for $R^n$.
Prove that $B[[A(b_1)]_C,....,[A(b_n)]_C] =AB$.
Answer: Your notation is truly horrendous, but I suppose that for $v\in\Bbb R^n$ the notation $v_C$ means the column formed of the coordinates of $v$ with respect to $C$. Those are obtained by multiplying $v$ to the left by the inverse $B^{-1}$ of the matrix whose columns hold the coordinates (in the standard basis) of the vectors $b_j$ of the basis $C$. Then you are computing
$$
  B[B^{-1}A(b_1)~\ldots~B^{-1}A(b_n)]
 =[A(b_1)~\ldots~A(b_n)]=AB.
$$
But maybe the goal of the exercise was to deduce the fact that the coordinates with respect to $C$ are given by multiplying by $B^{-1}$ in the first place (in which case my explanation is not very helpful)? In that case I would humbly suggest that there are better ways to explain that by such a convoluted exercice.
Comment: +1 for a great answer, and for ''your notation is truly horrendous". :)
Comment: I believe it is the second option and thank you for the helpful response.


What type of hinge: 180 degree, but only 135 degree motion

Question: I have an odd section of wall that I'm putting cabinet doors on.
In case the picture doesn't load, it's 2 framed walls stopping about 18 inches short on both walls before they would touch. So the doors are at a 45° angle.
I'm looking for a couple of hinges, that would allow the door to open pretty wide, about 135° from closed, but the mount needs another 45 to get to the post.
I've attached a quick drawing of what I mean.
I would think a concealed hinge that opens to 180° would work, but then there would be another 45° of travel that the door couldn't make, because it would already be closed. Which would, I suppose, block the soft close option on a hinge. Is there a hinge that fits that?
Comment: You should be able to find near-180 deg hinges.  just mount them on a 45 degree wedge.
Answer: I would take 2"x2" wood, and cut a 45 Dgr in it.
Mount it on the wall.
Now mount the 180 hinge on it,.

It will allow for soft close.


Unusual Segmentation Fault

Question: I was trying to delete alternate nodes in a linklist. I observed a strange behaviour.
void delete_alternate_node_LinkedList(Node *head) {
    Node *prev = head;
    Node *curr = head->next;
    while (prev != NULL and curr != NULL) {
        prev->next = curr->next;
        free(curr);
        prev = prev->next;
        if (prev != NULL) {
            curr = prev->next;
        }
    }
}

This code works fine except the head being nullptr when I use free to delicate or intentionally keep a memory leak but if I change the line free(curr) with delete curr, I get a segmentation fault.
Can anyone explain me the reason?
Here are the boilerplate codes
class Node {
public:
    int data;
    Node * next;
    Node(int data){
        this -> data = data;
        this -> next = NULL;
    }

    ~Node() {
        if(next) {
            delete next;
        }
    }
};
Node* takeinput() {
    int data;
    cin >> data;
    Node *head = NULL, *tail = NULL;
    while(data != -1){
        Node *newNode = new Node(data);
        if(head == NULL) {
            head = newNode;
            tail = newNode;
        }
        else{
            tail -> next = newNode;
            tail = newNode;
        }
        cin >> data;
    }
    return head;
}

void print(Node *head) {
    Node *temp = head;
    while(temp != NULL) {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout << endl;
}

Comment: `free` and `delete` are not interchangeable. You `free` what you `malloc` and `delete` what you `new`. Don't mix them.
Comment: `cout` and `delete` are C++ features that do not exist in C. The C tag is not appropriate for this question.
Comment: If `head` is a `nullptr`, then `Node *curr = head->next;` is a seg fault.
Comment: So basically just change `free(curr)` to `delete curr`.
Comment: on top of not being interchangable with `new` and `delete`, `malloc` does not create objects and `free` does not destruct them properly. Valid uses of those two are really rare in C++
Comment: Your `Node` class does not respect the [rule of 3/5/0](https://en.cppreference.com/w/cpp/language/rule_of_three). I'm not sure if this is the cause of your problem, but it might be. Either way, it's definitely something that needs to be fixed.
Comment: @FrançoisAndrieux Even when I add delete, it gives me error
Comment: @MayukhSarkar Does `delete` cause the crash, or does it simply allow your code to reach a later, different error. If it causes the crash, look into the rule of 3/5/0 mentioned in my previous comment.
Comment: @FrançoisAndrieux Delete works initially. But in later iterations it doesn't and causes exceptions
Comment: @user3386109 Yeah but the input is `1 2 3 4 5 6 -1` I know its an edge case I would handle later
Answer: Your destructor has a problem
Let's assume
A->B->C->D->nullptr
Now when you delete B it invokes destructor (if you use free it won't).
it will delete recursively C (which in turn delete D) and ..... till the end
so in next iteration you are holding on to a dangling pointer (C) and getting the segfault when you are trying to derefence it.
Comment: Okay. The boilerplate code was given by an Online judge and was read-only so I thought it was perfect. Now I see the problem. Thanks.
Comment: wc. you probably don't need to delete the next node. Instead use a function to delete entire list or used shared_ptr<> / unique_ptr<> (depending upon your usage).
Comment: The downside of `unique_ptr` in a linked list is the chain of destruction as the `unique_ptr`s clean up can overflow the stack if the list is long enough.

Unusual Segmentation Fault


Storing and comparing against objects from a database

Question: I am working on an android app that loads in a list of students to display in a list based activity. There are two components to the app. There is a server which responds via xml with the list of current active students and a database on the app end which stores theses students with some details (name,age etc). I would like a way to sync these two data sources. When the app starts, I would like to check against the xml to see if students on the server were added/deleted and update the db accordingly.
I would be parsing the xml list into a student object at login. Is there any way to store/retrieve an entire object into an android supported db so I can do a direct comparison to see what to update/delete? It would end up being something like
if (serverStudent[0].name == dbStudent[0].name)
   //overwrite dbStudent object with serverStudent fields

What is the most efficient/lightweight way to achieve object persistance and then comparison  in Android?
Comment: Can you provide some more details? Do you already have a database? How many records would there be? Do they have an updated timestamp? Why not just store the xml itself?
Answer: Here's a method I have used in the past:
Anytime an object in the database is changed, use a timestamp column to store that time. When the app connects on startup, simply check each timestamp in the app db against the timestamp in the server db for each object. If the timestamps match, do nothing. If the timestamps don't match, retrieve the updated record from the server. Make sure you're using a detail enough timestamp (usually down to milli- or micro- seconds).
The nice thing about timestamps is that if you don't want the server data to override the app data, you could look at which is newer and keep that object if they've both been edited. Just adding some additional thoughts!
Comment: Good answer. Also have on your server a service that lists (and consolidates) all updates since any given timestamp. That way you can connect and immediately get the delta between the two systems.
Comment: True! You could simply store ONE timestamp per user that gets updated anytime a record they've "checked out" is updated. Then you only test 1 timestamp each time and if it doesn't match, simply fetch the records with newer timestamps!
Comment: Timestamps can be troublesome though, if you have to account for time zones.  You could use a GUID instead.
Comment: Anytime you're working with date/time stamps, you need to be able to account for timezones. GUID can work as well since it incorporates timestamps with some unique identifier from the system (I forget exactly what it uses) but may also be able to help you identify which system edited it last (server or app)
Answer: You can do something like this -
public class StudentRecord {
    Vector<StudentData> studentDatas;
    public StudentRecord()
    {
        studentDatas = new Vector<StudentData>();
    }
    public Vector<StudentData> getRecords() {
        return studentDatas;
    }
    public void setRecords(Vector<StudentData> records) {
        this.studentDatas = records;
    }

    public class StudentData
    {
        String name,Rollno;

        public String getRollno() {
            return Rollno;
        }

        public void setRollno(String rollno) {
            Rollno = rollno;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

}

When you get the vector object studentDatas you can do something like this -
for(Object object : record.getRecords())
        {
            data = (StudentData)object;
            data.getRollno();
            data.getName();
        }

Answer: I'm not sure i understood your question correctly.But as far as i understand i would do something like this.

In server side send send Json array which holds json student objects.
In android side create similer Student class and override equals
method as you want.
Then for each student check with equals method whether they are
equals or not and take action accordingly.
If you want to make faster search in students object array then apply
hash map instead of arrays.
Comment: the issue is that right now i would have to reconstruct the student object once i have a query returned from my db in order to compare against the student object i just created from the json data i got back. Doesnt that seem excessive? I am looking for a better solution in the persistance of the student in the db so it doesnt have to be forced into an object once retrieved from the db for the comparison
Answer: Check out these libraries:
http://www.datadroidlib.com/
https://github.com/octo-online/robospice
I believe both offer solutions for your situation.
Or you can roll your own solution... Basically you will want to create a service or asynctask to do the syncing, in your student object you can create a constructor that you can pass an id  to and have it pull the appropriate record from your local db then make a comparison method that will update if newer information is available.
Comment: Link-only answers [are discouraged](http://meta.stackexchange.com/a/8259/166749). Can you expand on this answer at all to make it more helpful?
Comment: @PaulBellora Thank you as I did not know that. I added more information but the op seems to understand what he needs to do, just looking for the best way to do it. These libraries offer full solutions from end to end for this specific task.


How to increase precision with division in mysql

Question: I have a sql query select 1/3, and it returns 0.33333.  Is there any way to increase precision to 20 decimal places?
Thanks
Answer: You can try using decimal precision:
SELECT CAST(1 AS DECIMAL(30, 20)) / 3 AS output FROM dual;

Note here that I first cast 1 to a decimal with 20 places of decimal precision.  Then we divide this by 3, but using the same precision.
Your example is somewhat contrived, because in practice if you required 20 decimal places of precision you would define the relevant columns to be numeric or decimal.  Then you would not need an explicit cast.
Demo


What are good ways to find the limits of this function?

Question: Compute: $\displaystyle\lim_{x\rightarrow 2}\frac{\sqrt{x+1}-\sqrt{ 1-x}}{x}$
Comment: I'm not sure that the problem was to compute the limit when x --> 2...
Comment: sqrt x+1 means $\sqrt{x} + 1$ or $\sqrt{x+1}$? What about sqrt 1 - x? I'm guessing $\sqrt{1-x}$
Comment: $(\sqrt3-i)/2$.
Comment: http://en.wikipedia.org/wiki/L'H%C3%B4pital's_rule
Comment: L'Hopital is not a good way of learning what the limits are but a really good way to check your answer.
Comment: You don't need L'Hopital's rule here, the function is continuous at 2, so you can just substitute $x=2$ and evaluate, as @Berci has done.
Answer: I assume you are interested in $$\lim_{x \to 0} \dfrac{\sqrt{1+x} - \sqrt{1-x}}x$$
Multiply and divide by $\sqrt{1+x} + \sqrt{1-x}$ to get
$$\dfrac{\sqrt{1+x} - \sqrt{1-x}}x \times \dfrac{\sqrt{1+x} + \sqrt{1-x}}{\sqrt{1+x} + \sqrt{1-x}} = \dfrac{(1+x)-(1-x)}{x(\sqrt{1+x} + \sqrt{1-x})} = \dfrac{2x}{x(\sqrt{1+x} + \sqrt{1-x})}\\ = \dfrac2{\sqrt{1+x} + \sqrt{1-x}}$$
Now can you finish it off?
Answer: Just evaluate the function at $x = 2$.


ClassDefNoFound on API 22 x_86 level API

Question: I am facing a strange problem in API level 22 (lollipop) mobiles.
Mobiles using these API levels are working fine

API 24
API 23

But when i run my app on API level 22 mobile, it gives me following error message.
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.squareup.picasso.Picasso"
    on path: DexPathList[[zip file
    "/data/app/com.myapp.app-1/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp.app-1/lib/x86, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

However this is not Picasso related  problem, if i remove Picasso library it starts giving me error messages on other classes.
   Process: com.myapp.app, PID: 16327
   java.lang.NoClassDefFoundError: Failed resolution of: Lcom/myapp/app/VideosListActivity
       at com.myapp.app.MainActivity$8.onClick(MainActivity.java:422)

Gradle FIles (App)
 compileSdkVersion 24
    buildToolsVersion "23.0.3"
    defaultConfig {

        applicationId 'com.myapp.app'
        minSdkVersion 21
        targetSdkVersion 24
        versionCode 26
        versionName "1.0"
        multiDexEnabled true

        ndk {
            abiFilters "armeabi-v7a", "x86", "armeabi", "mips"
        }

    }
    lintOptions {
        abortOnError false
    }
    dexOptions {
        javaMaxHeapSize "4g"
        jumboMode true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    productFlavors {
    }
}
dependencies {
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.google.maps.android:android-maps-utils:0.4'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile project(':common')
    compile project(':commonwidget')
    compile project(':videowidget')
    compile 'com.android.support:multidex:1.0.1'
    compile 'org.apache.commons:commons-lang3:3.4'
    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'com.google.code.gson:gson:2.4'
    compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
    compile 'org.glassfish:javax.annotation:10.0-b28'
    compile 'io.card:android-sdk:5.4.0'
    compile 'it.sephiroth.android.library.targettooltip:target-tooltip-library:1.3.15'
    compile 'com.github.michaelye.easydialog:easydialog:1.4'
    compile 'org.jsoup:jsoup:1.8.3'
    compile 'me.grantland:autofittextview:0.2.+'

repositories {
    flatDir {
        dirs 'libs'
    }
}

Gradle - Project
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        /**/
  /*      classpath 'com.android.tools.build:gradle:1.2.3'*/
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:2.1.0'
        classpath 'com.google.code.gson:gson:2.2.4'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myapp.app">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <application
        android:name=".AnalyticsSampleApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service android:name=".ticketing.services.LogoutService" />

        <activity
            android:name=".MainActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".SplashDefaultActivity" />
        </activity>
        <activity
            android:name=".DirectionsActivity"
            android:label="@string/title_activity_directions"
            android:parentActivityName=".MapsActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".SplashDefaultActivity" />
        </activity>
        <activity
            android:name=".SplashDefaultActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SplashVideoActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar" />

                <activity
            android:name=".VideosListActivity"
            android:configChanges="orientation|keyboardHidden"
            android:label="@string/title_activity_videos_list"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme" />

    <activity
            android:name=".VideoActivity"
            android:configChanges="orientation|screenSize"
            android:label="@string/title_activity_video"
            android:theme="@style/AppTheme" />

Answer: Did you manually re-sync gradle after your changes? Did you also change build-tools version in your build.gradle to match API 22 as well? The errors you're showing I've only seen when gradle hasn't rebuilt or resynced properly. I would also try to manually do it from the command line... (in OS X), ./gradlew clean, ./gradlew assemble
Comment: After changing the gradle files, I click on Sync button and it synced gradle files for me. Its not showing any error message after gradle build. Do i need to do additional steps for APi 22 Support?
Comment: You shouldn't need to. That should be everything. If it's not failing after build, is it deploying and working?


Display CRUD table data even after refreshing the page using ngStorage

Question: I have created this CRUD table, I can see table data being stored in web browser's  local storage in developer tools, even after editing and removing rows, but I don't know how to save and display the same data even after refreshing the page with all latest updates.

Please see the attached code in plunker: https://plnkr.co/edit/fvp2kQzxrnkgLsQ1r4i6?p=preview
Answer: You have 2 issues to fix.
First, you've defined vm.$storage = $localStorage yet you continue to attempt to update $localStorage when you should be updating vm.$storage.
Second, initialize your array like this:
vm.arr = vm.$storage.arr || [];

I have forked your plunk
Comment: Got it, thanks alot for that, i was also having issues in removing the rows but got it fixed now. But now when i am updating the stored data when page is refreshed, i am getting some error , table is not updating in that way, but it gets updated if you add a row first and then update it. Can you please tell me how to fix it ? New updated plunk https://plnkr.co/edit/eoVeVLC7tBCorwy42oJ9?p=preview
Comment: TypeError: Cannot set property 'myid' of undefined
    at Object.vm.edit (controller.js:70), when the data is saved and after refreshing, when i click on update.
Comment: got it fixed https://stackoverflow.com/questions/46863302/type-error-when-i-am-updating-crud-table-after-refreshing-the-page-in-angularjs/46865574#46865574


putting arrays in this format name:url

Question: I am not aware of the term of the array but, I have a list of string urls such as "http://dom/image1.jpg","http://dom/image2.jpg" that I pulled from an api (api returns just the links). The plugin I am using requires the array to be in the format of
{image:"http://dom/image1.jpg"},{image:"http://dom/image1.jpg"}.

How do I go from a list of strings to a list with the name: in front of the url
Link to plugin
http://www.buildinternet.com/project/supersized/docs.html#slides
Answer:  var newArray = array.map(function(item){
      return { image: item }  /* as key-value pair */
 });

Comment: would image be consider a property in this situation? I just would like to know the terminology for this array.
Comment: @user516883: AFAIK, `image` is not a reserved javascript keyword. It is valid usage. You can easily do `array[n].image`. (If that's what you're asking)
Answer: Each element in the array you already have is a string, and you want those strings to be wrapped in objects with an image property.
for(var i = 0; i < arr.length; i++) {
  arr[i] = { image: arr[i] };  // wrap it in an object
}

putting arrays in this format name:url


Finding the support for Transformation of Random Variables

Question: I have two independent random variables $X$ and $Y$ with exponential distribution $\sim E(5)$.
$U=5X-Y$ and $V=4X+2Y$
I need to find the inequalities for the joint density $f(u,v)$. I was able to find the joint density which was $\frac{25}{14}\exp\left(-5\frac{-2(u+6)v}{14}\right)$ but I'm not sure how to proceed to find the support for the function.
Comment: So, to be clear...the joint density is $$f(u,v) = \frac{25}{14} \exp \left(-5 \frac{-2 (u+6) v}{14}\right)$$ Is this Correct? What is the domain of support for $f(u,v)$?
Answer: The joint support of $(X,Y)$ is the first quadrant $[0,\infty) \times [0,\infty)$.  Under the matrix transformation $$\begin{bmatrix}U \\ V\end{bmatrix} = \begin{bmatrix}5 & -1 \\ 4 & 2 \end{bmatrix} \begin{bmatrix} X \\ Y \end{bmatrix},$$ it becomes clear that the joint support of $(U,V)$ must be a linear transformation of this region.  Indeed, we see that when $Y = 0$, then $(U,V) = (5X, 4X)$; and when $X = 0$, then $(U,V) = (-Y, 2Y)$.  Thus the joint support is the region satisfying $$\left( V \ge \frac{4U}{5} \right) \cap \left( V \ge -2U \right),$$ or equivalently, $$V \ge \max\left\{-2U, \frac{4U}{5}\right\}.$$  We could also write this as $$-\frac{V}{2} \le U \le \frac{5V}{4},$$ which perhaps is the simplest of all.
Note it is not sufficient to find the support of the marginal distributions of $U$ and $V$ separately:  the joint support is needed to characterize the distribution, because in the $(U,V)$-plane, the support is not rectangular as it was in the $(X,Y)$-plane.
Comment: Very nice answer.


Using mailto breaks fading page transitions

Question: If you click on a link, it fades the page out and takes you to the new page. This works fine when you're being taken away to another site.
However, this does not work at all with a simple . Why? Because you're not actually going anywhere. As a result, you get left with a blank page and an open mail client. Here is an example:
JSFIDDLE
function fadeAndGo(x) {

        $(x).click(function (e) {
        e.preventDefault();
        var href = this.href;
        $('.wrapper').fadeOut(function(){
            window.location = href;

        });
    });
}

fadeAndGo('a');

Would it be possible, instead of targeting all 'a' tags, target those with an attribute of href? Or choose to ignore those links that begin with mailto:?
Any help would be appreciated.
Comment: I'm no JS expert, but could this be done by giving the HTML anchor a class?
Comment: Unfortunately, this is on WordPress, so I'd like to keep it dynamic rather than change classes with each new anchor tag.
Comment: you'd only have to set the class for the mailto anchor, the rest would remain unaffected.
I cant imagine you use many mailto links on one page..!
Answer: Yes, only with CSS selector. jQuery will take care of the browser compatibility i guess, otherwise it will work on IE9+
fadeAndGo("a:not([href^='mailto:'])");

Comment: Shouldn't it be `a:not([href^='mailto:']) `?
Comment: It's still not right. Try `fadeAndGo("a:not([href^='mailto:'])");
`
Comment: Check out the jquery selector compatibility, i cannot say.
Answer: You can check the href attribute before changing the window.location value:
$('.wrapper').fadeOut(function () {
        if (href.indexOf('mailto') == -1) {
            window.location = href;
        }
}

DEMO
Comment: Again, does not seem to work on the anchor that's not a `mailto`: http://jsfiddle.net/tmyie/n6KGf/4/
Comment: @tmyie Sorry, I posted the wrong link. See the fiddle in my answer now
Comment: Is there a way to have it outside the fadeOut function, so it only fades out if `indexOf?`
Answer: This should work:
fadeAndGo('a[href^="http"]');
JSFiddle here
EDIT: It just occurred to me that this won't work with links containing relative URLs, so I'd advise going with @Germain's answer instead.


Veryifying the Collatz Conjecture for one number without explicit computation

Question: Basically the title. Exhaustive computer searches are going on all the time, but if we seem to find a very large counterexample to the Collatz Conjecture, how will we ever know that it doesn't, in the end, hit $1$? Are there any results, theorems, or algorithms that can help us here?
Comment: An obvious possibility is that it has been found that $n \to \cdots \to n,$ i.e. there is a cycle not including $1$.
Comment: This is part of what makes the problem difficult. Of course, if we find a loop other than 1-4-2-1, then just listing that loop, or even a single number in that loop, is enough to allow anyone else to confirm. However, if the number just gives a diverging sequence, I don't think anyone knows what a proof of such a divergence could possibly be. Modular arithmetic, for instance, is uncharacteristically unhelpful.
Comment: @ChristianBlatter How? If the number just keeps getting larger and never hits a cycle...
Comment: In theory one could hope to prove that the iterates of $n$ never get below $n$.  The least counterexample would certainly have that property.
Comment: Welcome to the Collatz game :)  Might I recommend a book? "The Ultimate Challenge: The 3x+1 Problem", edited by Jeff Lagarias, compiles most known results on this topic.
Comment: Counterexamples come with a proof that they are counterexamples.
Answer: "Are there any results, theorems, or algorithms that can help us here?"
Perhaps the following is interesting if not helpful:
if there really is a nontrivial cycle in the Collatz problem, then $\det M (d) = 0$ for all large $d$, but if there are none then $\det M (d) = (−1)^d$ for all $d$. Here $M(d)$ is Zeilberger's matrix.
References: Chapman
Zeilberger's determinant evaluation problem
Comment: Hmm, I think this is a simple (or even complicated) "blow-up" of the original problem (see Chapman's proof) and thus surely not really *helpful* .
Comment: @GottfriedHelms Yes, I just found it interesting. "Helpful" here, it seems from the comments, is not really available in this context (but "unhelpful" is).
Comment: Dietrich - thanks for your reflection. Actually, my comment might be enough for what should to be said; I've been courious enough to follow your links and to experiment a bit with that matrix - "one nice idea" I must say ... . I'm now deeply involved in another problem so I just want to respond shortly that I don't want to make a big problem. Happy new year to all, btw. - Gottfried
Answer: You're touching upon the notion that the conjecture may be unprovable within certain mathematical systems. This does indeed follow from your observation that one counterexample could ascend indefinitely to infinity.
If a theory weren't strong enough, any proof that some infinitely long sequence exists might itself not be writable in a finite number of steps, making such a proof impossible to complete.


Should I use inetd or xinetd?

Question: I see openbsd-inetd is installed by default but there are quite a few mentions of xinetd in AskUbuntu.
I have a custom service to install. inetd would provide all the features I need.
Should I be using inetd or xinetd to be most compatible with future updates?
Answer: Use xinetd if it does what you want, but personally you should avoid using inet at all. Some information on the service itself would help answer your question.
Comment: Hi Strings, we have an inhouse developed system that facilitates unix to pc communications. Ie send a Unix file to the PC of the domain user who logged in to the Unix server and many other things. When the PC boots, it connects to the Unix server on a specific tcp port and runs a Linux process that takes care of all the communication between Linux and the PC. It maps the Windows user to a Linux user.
Comment: Hi Strings, Er, you seem to be contradicting yourself. In the first post you said use inetd, then in your last post, you said (there is a typo you might like to correct, I think), use xinetd. Openbsd-inetd is inetd, not xinetd. Thanks for your input.
Comment: I did mean xinted, sorry I used the general term, I should have been more specific. I only suggest xinetd vs openbsd-inetd. because you know it will do exactly what you want. imo openbsd-inetd is just the default inet, nothing wrong with using something else.

Should I use inetd or xinetd?


What music player shows "similar bands you might like" feature

Question: In 11.04 I used banshee or rhythmbox because it had a feature that told me, when I was listening to a song what other bands from other similar groups I would enjoy. Most of the time it was correct or at least it helped me find a group I have not heard for a long time.
In 11.10 neither of them have this feature or at least I do not know which one had it and how to activated it again.
What music player has this particular feature in 11.10
Answer: Banshee still has that. You have to make sure that you have enabled the Last.FM-scrobbling plugin in the settings and then check the context pane under view to be shown.
I don't know about Rhythmbox but other than that, Tomahawk player has a similar feature.
Comment: Also rhythmbox has the possibility to enable last-fm plugin
Answer: I found that feature in Songbird (in Ubuntu for the moment works perfectly a sort of portable version- just unpack - I got it here) - a player with a lot of  custom features downloadable from within the player itself. Songbird has an internet browser: search amongst the many add-ons. I think what you need is one called Music Recommendations: it's description says:"Suggests similar artists based on the currently playing song".


Angular 2 Default select option not populating

Question: I am trying to give my select box the selected option on page load by setting it to a variable like this
<select style="border:0;" [(ngModel)]="accountStatuses" >
        option *ngFor="let s of accountStatuses" [ngValue]="s" [selected]="s === user.accountStatus">{{s}}</option>
</select>

The select box has its optioned, but on page load, none are selected.
Here is the relevant bits of typescript.
@Component({
    selector: 'user-detail',
    templateUrl: './user-detail.component.html',
    styleUrls: ['./user-detail.component.css']
})

export class UserDetailComponent implements OnInit {
    user: User;
    userRoles: UserRole[] = [];

    roleAmountStatusMessage = 'Show More..'
    roleAmountStatus = false;
    rolesSice1 = 1;
    rolesSice2 = 10;

    pageRequests: PageRequest[] = [];

    accountStatuses = ['Archived', 'Disabled', 'Enabled', 'Locked'];

    constructor(private userService: UserService, private route: ActivatedRoute, private roleService: RoleService) { }

    ngOnInit(): void {
        let userId = +this.route.snapshot.paramMap.get('id');
        this.userService.getUser(userId).then(user => this.user = user);
        this.userService.getUserLast25PageRequests(userId).then(pageRequest => this.pageRequests = pageRequest);
        this.roleService.getRolesByUserId(userId).then(userRoles => this.userRoles = userRoles);
    }

Comment: Can we see the actual typescript? It sounds like you need to initialize it in an ngOnInit
Comment: I'm having the same problem, I can't find a working plunkr with material beta 12 that's working so I can reproduce the issue.
Comment: @Joris I've added it to the post
Comment: @Lakston check out the answers.
Answer: Look at this example:
accountStatus: AccountStatus;
accountStatuses: AccountStatus[];

<select [(ngModel)]="accountStatus" >
        <option *ngFor="let s of accountStatuses" [ngValue]="s">{{s}}</option>
</select>

Let me know if you need more details
Answer: I think you should introduce a new field like
[(ngModel)]="selectedAccountStatuses"

instead of
[(ngModel)]="accountStatuses"

class MyComponent {
  selectedAccountStatus:string;

   ngOnInit() {
     ...
     this.selectedAccountStatus = this.accountstatuses[0];
   }

[(ngModel)]="selectedAccountStatuses"

and remove
[selected]="s === user.accountStatus"


iOS : how to enable/disable textview's editable property on click of button

Question: I am creating a editable table view where user can enter its values into tableview cells. Table view custom cells contains multiple textview. I have a button like Edit/Done. On click of edit, user should be able to enter values in table view cells containing textview. On Done click, it will disable editable property.
below is my method of Edit/Delete button, but its not functioning as I am wishing to, what will be the possible solution ?
- (IBAction) toggleEdit:(id)sender {
    [self.tableview setEditing:!self.tableview.editing animated:YES];

    static NSString *simpleTableIdentifier = @"ScoreCustomCell";

    ScoreCustomCell *cell = (ScoreCustomCell *)[self.tableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ScoreCustomCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    if (self.tableview.editing) {
        NSString *tempStr=[NSString stringWithFormat:@"Done"];
        [sender setTitle:tempStr  forState:UIControlStateNormal];
        for (int i=0; i<=23; i++) {
            if (cell.scoreText.tag==i) {
                [self.tableview setUserInteractionEnabled:YES];
                [cell setUserInteractionEnabled:YES];
                cell.scoreText.editable=YES;
                [cell.scoreText setUserInteractionEnabled:YES];
                [cell.scoreText becomeFirstResponder];
                [self.tableview reloadInputViews];
            }
        }

    }
    else {
        NSString *tempStr2=[NSString stringWithFormat:@"Edit"];
        [sender setTitle:tempStr2  forState:UIControlStateNormal];
        for (int i=0; i<=23; i++) {
            if (cell.scoreText.tag==i) {
                cell.scoreText.editable=NO;
                [self.tableview reloadInputViews];

            }        }
    }
}

Answer: Update your toggleEdit method like this:
- (IBAction) toggleEdit:(UIButton *)sender {
    [self.tableview setEditing:!self.tableview.editing animated:YES];

    if (self.tableview.editing) {

         NSString *tempStr = [NSString stringWithFormat:@"Done"];
        [sender setTitle:tempStr  forState:UIControlStateNormal];
    }
    else {
        NSString *tempStr2=[NSString stringWithFormat:@"Edit"];
    }

   [sender setTitle:tempStr2  forState:UIControlStateNormal];

   [self.tableView reloadData];
}

Now in cellForRowAtIndexPath method at the end put an if-else
cellForRowAtIndexPath
{
   ...
   ... Your code here ...
   ...

   // before returning cell add this two lines

   [cell.scoreText setEditable:self.tableview.editing];
   [cell.scoreText setUserInteractionEnabled:self.tableview.editing];

   return cell;
}

Hope this helps.
Comment: @Ash Glad that it helped you, can you please upvote the same.
Comment: Vote Up requires 15 reputation ! :( I wish I could :(


check if recyclerview item position has changed while scrolling

Question: Hi I am trying to check whether recycler view current position has changed. and get that position while scrolling. Tried getting it inside onbind but it gets called only once.
Searched for answers and found this. But looking for some workaround to implementing it. Let me know
<code>@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    final News news = episodeList.get(position);
    Log.e(TAG, "onBindViewHolder: " + holder.getAdapterPosition() );
}
</code>
Above here all the positions are logged all together.
Comment: you know how bind view works dear ? please find it and i think it works like it creates view according the screen height , lets say you have 20 items and according to the device height it can only show 6 items , then it binds the view for 6 items , then when you scroll down or up , it will again bind views , According to you requirement i would prefer you to find the center item position  among the current items in list
Comment: The current items are huge so in a screen at a single point their is only one item. but When I try to log the adapter position I am getting all the positions inside it @quicklearner
Comment: Can u post code here
Comment: i told u , that it will change position when you scroll list up or down ,did you try finding the center item and save its position when its completely invisible ?
Answer:
try this :
just use your own layout manager , because my recycler view scrolling horizontally

Save your X-Position as class variable and update each change within the onScrollListener. Ensure you don't reset overallXScroll (f.e. onScreenRotationChange)
<code>private int overallXScroll = 0;
 //...
 mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        overallXScroll = overallXScroll + dx;
        Log.i("check","overall X  = " + overallXScroll);

    }
 });
</code>
Comment: what is first item position here @krishsingh
Comment: **i sort the answer , now you can check**


Execute a program on python server and update results dynamically on the html webpage

Question: I have classical python server.
I made a CGI script. I would like from a click in the client side, execute a script in the server side and screen the result in the same page dynamically in the client side.
I know how to update dynamically a page in the client side but I didn't find a way to do it from the server side.
For instance my initial webpage:
print 'Content-type: text/html'# image/svg+xml'
print '''

My PAGE

    Execute my program

    '''

I would like to execute a script in the server when we click like this kind of execution:
command = "python myscriptinLocal.py -a %s"%(arg)
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()

A result file is generated in the server, and I would like to screen the result in the current page without to generated a new page....
Is it possible? Is there a way to do that with python or with another language?
Answer: You can use any one of python WSGI frameworks to do exactly that. Just sign a free account with Google App Engine and you will be able to do that immediately. Although you may not be able to spawn your own process nothing will stop you from executing your python script and output it as html!
Google app engine pages in Stack:
https://stackoverflow.com/questions/tagged/google-app-engine?sort=votes
Comment: Thank you, I'm gonna search on this way ;) I really don't know this kind of stuff but I'm sure it seems very powerfull! Thank again for your advices :)


Count occurrences between two arrays in javascript

Question: So, lets say I have these two arrays:
const arr1 = ["apple", "orange", "banana", "mango", "cherry"]
const arr2 = ["apple", "mango"]
How to get the number of occurrences in arr1 from arr2. All the strings in both arrays will be unique and there won't be duplicates. Obviously, the result in this concrete case is 2.
What I have tried:

const arr1 = ["apple", "orange", "banana", "mango", "cherry"]

const arr2 = ["apple", "mango"]

let count = 0
arr2.forEach(i =>
  arr1.includes(i) ? count++ : count );
  console.log(count);

The problem is I have to use this in few cases and the count variable is always changing, depending on what you click and you cannot rely on its value.
Thank you in advance!
Comment: Extract to a function that returns the count?
Comment: The problem you have is not visible from the code you have given. Please demonstrate the issue with code.
Comment: @trincot I assume OP uses something like `if (count > 2)` in one place and `if (count < 4)` in another but the counts are of different pairs of arrays.
Comment: `arr2.filter(fruit => arr1.includes(fruit)).length` o.O
Comment: @Andreas I'd extract that to a function, as well, assuming it's used several times as OP suggests their code is.
Comment: @VLAZ Sure, it's just a _"why so complicated?"_
Comment: @Andreas eh, in either case the way the question is worded, it seems like this code is being copy/pasted *including* the variable. Extracting to a function is the first step, then the function can be improved, if needed.
Comment: @VLAZ your assumption is right, thank you! :)
Answer: Check if this is what you are looking for:
const arr1 = ["apple", "orange", "banana", "mango", "cherry"];
const arr2 = ["apple", "mango"];

// count items
const count = arr1.filter(i => arr2.includes(i)).length;

console.log(count) // displays 2


How to properly use appendChild

Question: $(document).ready(function() {
    $("a:last").on("click", function(event) {
        event.preventDefault();
        var url = $("a:last").attr("href");
        var page = url.slice(-2).trim();
        var newDiv = document.createElement("div");
        $(newDiv).addClass("content");
        $(newDiv).addClass(page);
        $(newDiv).load(url);
        document.getElementById("main").appendChild($(newDiv));
    });
});

I want to create a new div and load some content into it, then append it to the "main" div, but I get a TypeError:

Argument 1 of Node.appendChild does not implement interface Node.

I already have a div with id="main", why can't I append my new div to it?
Answer: Basically appendChild() expects a node object as its parameter, but here you are passing a jquery object. You can fix it by passing a node object,
document.getElementById("main").appendChild(newDiv);

And since you are using jquery, you can use its own append() function,
$(document).ready(function() {
    $("a:last").on("click", function(event) {
        event.preventDefault();
        var url = $("a:last").attr("href");
        var page = url.slice(-2).trim();
        var newDiv = $("
");
        newDiv.addClass("content");
        newDiv.addClass(page);
        newDiv.load(url);
        $("#main").append(newDiv);
    });
});

Answer: The issue is because you're mixing up jQuery and plain old JS. The error itself is because you're proving a jQuery object to appendChild() when it's expecting a DOMElement. As you're using jQuery anyway you may as well use that to create your elements. Try this:
$("a:last").on("click", function(e) {
    e.preventDefault();
    var url = $("a:last").attr("href");
    var page = url.slice(-2).trim();
    $('
').addClass('content ' + page).appendTo('#main').load(url);
});

Answer: $(newDiv) is a jquery object, not the node. You need to pass the node in. This will work
$(document).ready(function() {
    $("a:last").on("click", function(event) {
        event.preventDefault();
        var url = $("a:last").attr("href");
        var page = url.slice(-2).trim();
        var newDiv = document.createElement("div");
        $(newDiv).addClass("content");
        $(newDiv).addClass(page);
        $(newDiv).load(url);
        document.getElementById("main").appendChild(newDiv);
    });
});

How to properly use appendChild


Error 310 - when I try to access the Steam market

Question: Whenever I try to access the Steam Community Market, it just shows

Error -310 (unknown)

Googling got me nowhere. Has anyone heard of this error/know how to fix it?
Answer: Steam's errors usually correspond to HTTP status codes. While there are some that may indicate a problem on your end (like a connection failure or expired authentication) this one is a bit special (it's not usually listed with the "standard" HTTP codes) and means "too many redirects". It hints at a server-side problem, for example a programming mistake.
Comment: I don't know why Valve prefixes the code with a minus, but even more annoyingly it's always shown as "unknown".
Answer: I realise this is an old post but just in case someone finds this thread with the same question:
I've had this happen on two different occasions while browsing the Steam Store on my desktop application and both times I was able to get around it by searching for the game with the Steam Store on my web browser and after you click play/buy now click the option "Yes, I have steam installed" and it opens steam and downloads just fine.


How NOT to use an ObjectDataProvider?

Question: I have my first WPF working fine with an ObjectDataProvider in the XAML:
<ObjectDataProvider x:Key="WaitingPatientDS" ObjectType="{x:Type local:clsPatients}">
    <ObjectDataProvider.ConstructorParameters>
        <sys:Boolean>True</sys:Boolean>
    </ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>

However, I don't like using this because if there is a connection error, I can't trap it and the program just barfs out.
So, what I've been trying to do is to instantiate the collection object directly in the codebehind...
public partial class MainWindow : Window
{
  ListBox _activeListBox;
  clsPatients oPatients;

public MainWindow()
{
  oPatients = new clsPatients(true);

...and then reference it in my databinding as so:
<StackPanel x:Name="stkWaitingPatients" Width="300" Margin="0,0,0,-3"
   DataContext="{Binding Mode=OneWay, Source={StaticResource local:oPatients}}">

But, I'm getting "local:oPatients was not found".
So...what am I doing wrong in referencing this and/or how would someone else accomplish this data binding so that I can actually trap for connection errors and divert the main form to a user-friendly error form?
THANKS!
Comment: + 1 - ODS and SQL Params in the markup has always made me feel less than fresh. I have successfully made ReportDataSourses entirely in code, but never got that elusive ODS to work.
Answer: I'd move the data access logic into a separate service, and perhaps into its own assembly entirely to enforce your intended separation of concerns. Then I'd have a view model use said service to retrieve data and expose it for the view. Then the view would simply bind to the view model and wouldn't care whether the data came from a database or whatever.
I would suggest reading up on separation of concerns, service locator/dependency injection, and MVVM.
Comment: Wish I had the time brother, wish I had the time! ;)
Comment: Well, whoever inherits your code will be wishing the same thing ;)
Answer: You're getting that error because oPatients is not a StaticResource. It would have to be defined in the ResourceDictionary the way your ObjectDataProvider was, but as a class member it is not. You could expose it as a public property:
public clsPatients Patients { get; set; }

Then bind to it directly:

<StackPanel x:Name="stkWaitingPatients" Width="300" Margin="0,0,0,-3"
   DataContext="{Binding Patients, ElementName=MainWindowRoot, Mode=OneWay}">

Assuming I haven't made some stupid mistake, that should work. However, it still doesn't solve your problem because you're loading the data in the constructor, which means that any exceptions will cause clsPatients construction to fail, which in turn will cause MainWindow construction to fail, which you cannot properly handle because it's a rats next of a stack trace that's indistinguishable from a legitimate construction failure.
Kent is 100% right: The data should come from an external provider.
You may have resource limitations, but you can still establish good design even if you can't implement a tiered architecture. At bare minimum, establish separation of concerns by loading the data in a separate data provider class then passing the fully-formed data into the window. That allows you to isolate failures where they occur, and keep your code somewhat more loosely coupled.
public class PatientDataProvider
{
    public PatientDataProvider(WhatItNeedsToConnect whatItNeedsToConnect)
    {
        // this doesn't connect because the constructor shouldn't fail because of a connection failure
    }
    public clsPatients GetPatientData(bool yesOrNo)
    {
        // this can fail because of a connection error or some other data loading error
    }
}

and invoke it as:
PatientDataProvider provider = new PatientDataProvider(whatItNeedsToConnect);
clsPatients patients = null;
try {
    patients = provider.GetPatientData(true);
    MainWindow w = new MainWindow { Patients = patients; };
    w.Show();
}
catch (WhateverExceptionGetsThrownByProvider e)
{
    MessageBox.Show("Could not load patients: " + e.Message);
}

Also, if clsPatients is self-refreshing, make sure it implements INotifyPropertyChanged or INotifyCollectionChanged as appropriate in order for the binding targets to update when the data changes.

How NOT to use an ObjectDataProvider?


Rijndael encrypter: Getting empty byte[]. Not encrypting anything

Question: Good evening!
I'm trying to implement an encrypter using Rijndael algorithm and Rijndael class in c#. I tried to follow (not doing exactly the same code) the link bellow, but the problem is given a string to be encrypted I'm not getting any result. I'm no getting any error message too.
https://learn.microsoft.com/pt-br/dotnet/api/system.security.cryptography.rijndael?view=netframework-4.8
CryptDecrypt.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace RijndaelAlgorithm {
    public class CryptDecrypt {
        private Byte[] iv;
        private Byte[] key;

        public CryptDecrypt(String key) {
            iv = new Byte[] {21, 10, 21, 251, 132, 76, 121, 27, 210, 81, 215, 99, 14, 235, 11, 75};
            this.key = Encoding.ASCII.GetBytes(key);
        }

        public String encryptMsg(String originalMsg) {
            byte[] encryptedMsg;

            Rijndael rijAlg = Rijndael.Create();
            rijAlg.Key = formatKey();
            rijAlg.IV = iv;

            MemoryStream msEncrypt = new MemoryStream();
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            StreamWriter swEncrypt = new StreamWriter(csEncrypt);
            swEncrypt.Write(originalMsg);

            encryptedMsg = msEncrypt.ToArray();
            Console.WriteLine("encryptedMsg.Length: " + encryptedMsg.Length);

            return Convert.ToBase64String(encryptedMsg, 0, encryptedMsg.Length);
        }

        private Byte[] formatKey() {
            int len = key.Length;

            String strKey = System.Text.Encoding.UTF8.GetString(key);
            String fillKey = "";
            String strFormatedKey = "";

            Byte[] formatedKeyByte;

            if (len < 16)
                fillKey = new String('X',(16 - len));

            strFormatedKey = String.Concat(strKey, fillKey);
            formatedKeyByte = Encoding.ASCII.GetBytes(strFormatedKey);

            return formatedKeyByte;
        }
    }
}

Menu.cs
using System;

namespace RijndaelAlgorithm {
    public class Menu {
        private CryptDecrypt r;

        public Menu() {
            r = new CryptDecrypt("123654");
        }

        public void showMenu() {
            Console.WriteLine("the encrypted message is: " + r.encryptMsg("isjustatest"));
        }
    }
}

Comment: Your code uses a 128 bit key, not 256. Also, padding with `'X'` is highly unusual and not likely to be done by that online tool. Use a password based key derivation function such as Argon2 or PBKDF2 to turn low entropy keys into proper encryption keys. And do not reuse IVs for any given key.
Comment: Can you create a [mcve], in a separate project or on .net fiddle with only the encryption part of your problem
Comment: I did what I could. The RijndaelAlgorithm class has only two methods and maybe the problem is in formatKey(). Probably not, but I don't know. And Menu class is where I define the key and the message to be encrypted.
Comment: Why did you get rid of the using() constructs? Since they are gone you now have to manually call `swEncrypt.Flush();` and then `csEncrypt.FlushFinalBlock()` after the Write.
Comment: Because I'm newbie in c# and this synthax is very ugly and unusual for me. I added swEncrypt.Flush(); and then csEncrypt.FlushFinalBlock() after the swEncrypt.Write(originalMsg); and now is working fine. Apparently. The thing is I tried encrypt the same message in http://crypt-online.ru/en/crypts/aes/ and I got another thing. I choose 256bit for key size and "123654" for key and I got for Encode: U2FsdGVkX1+IVWR60YK3F6fN7F3a7SKPSpPDvF6ZXlA= and using my code I got GlIhsK3UihG+nlmBZHgHYg==  Why?
Answer: You seem to want to encrypt a message with your .NET application and want to get the same encrypted bytes as a particular online service that you mention in one of your comments.
Parameter
One parameter for an encryption is the initialization vector (IV). It should be random and used only once. So if two apps are correctly implemented (with different random IVs), the encrypted bytes are different.
This service returns a different result every time you press the key, even if you use the same input.
However, if you generally take the different encrypted results and decrypt them with the same key, you will get the original bytes back.
The next problem with testing with this specific service is, that they delivering always the same prefix base64 sequence 'U2FsdGVkX1'. This is not standard AES output (if you decode this base64 sequence you get 'Salted_P'). So it makes sense to use a different online service for tests.
So if two AES-256 encoding implementations are using the same parameters, we will get the same encoded result. We need for it:

Key (32 bytes, not 16 for AES-256)
IV (16 bytes)

Speaking of key length: As others mentioned in the comments, you should not simply add "X" or something similar, but use a standard cryptographic mechanism to derive a good key.
Convenient for tests are methods that convert hex strings to byte arrays and back, e.g. see StringToByteArray and ByteArrayToString methods in this cool answer:
https://stackoverflow.com/a/311179
Let's give it a try. If we take your message 'isjustatest' which has the hex string'69736a7573746174657374374', we need a 32-byte key for AES-256 and 16 bytes IV.
As others mentioned in the comments, you need to flush and close the stream (or better yet, use a 'using' statement).
Taking your code and change the key and iv assignment and output the encrypted message to the console:
rijAlg.Key = StringToByteArray("519C7C3402A943D8AF83746C1548E475319EBDA6A38046059F83B21709BD6A5B"); //32 bytes
rijAlg.IV =  StringToByteArray("0D024CF947CE4C288880D0B34D29BFA5"); // 16 bytes
...
swEncrypt.Write(originalMsg);
swEncrypt.Flush();
swEncrypt.Close();
...
Console.WriteLine("encrypted bytes: '" + ByteArrayToString(encryptedMsg) + "'");

This results in the output of '419536f27da3406625b2d07f43833aab' in the debug console.
So now we can use an online service, e.g. https://cryptii.com/pipes/aes-encryption where we can enter input data, select the encryption algorithm, supply key and IV bytes and then we get the same result as in your program, see screenshot here:

As mentioned above, don't forget to use different random IVs when using it in a real application.


Secure communication between arduino and PHP using RC4 and base64

Question: I'm trying to make a mildly secure communication between Arduino and PHP. I can not use SSL for lack of power on the Arduino. So I wanted to use RC4 to encrypt data from PHP, and receive into the Arduino and decrypt. also encrypt from the Arduino and send to PHP.
The problem is that the encrypted data sent from PHP, do not coincide in the Arduino.
On PHP I get HesshwkfFk8Q in base64 and in the Arduino i get nZcwrlpZEr0V in base64.
different results when they should be equal.
I think I have a wrong Arduino RC4 implementation. I'm using this https://github.com/adamvr/arduino-base64
This is the code:
Arduino
#include <Base64.h>

unsigned char S[256];
char has[512];

#define S_SWAP(a,b) do { int t = S[a]; S[a] = S[b]; S[b] = t; } while(0)

void rc4(char *key, char *data){
     int i,j;

     for (i=0;i<256;i++){
         S[i] = i;
     }

     j = 0;
     for (i=0;i<256;i++){
         j = (j+S[i]+key[i%strlen(key)]) %256;
         S_SWAP(S[i],S[j]);
     }

     i = j = 0;
     for (int k=0;k<strlen(data);k++){
         i = (i+1) %256;
         j = (j+S[i]) %256;
         S_SWAP(S[i],S[j]);
         has[k] = data[k]^S[(S[i]+S[j]) %256];
     }
     has[strlen(data)+1] = '\0';

}

void setup() {
  Serial.begin(9600);
  char key[] = "Hello";
  char sdata[] = "secretMsg";

  rc4(key,sdata);
  Serial.print("Encrypted : ");

  char out[100];
  base64_encode(out,has,strlen(has));
  Serial.println(out);

  char out2[100];
  base64_decode(out2,out,strlen(out));

  rc4(key,out2);
  Serial.print("Decrypted : ");

  Serial.println(has);

}

void loop(){

}

PHP
  <?php
    $key = 'Hello';
    $msg = 'secretMsg';
    $encrypted = rc4_crypt($key, $msg);

    echo 'encrypted b64: ', base64_encode($encrypted) ,'
';
    echo "decrip: " , rc4_decrypt($key,rc4_crypt($key, $msg));
    exit;

    function rc4_crypt($key,$msg) {
          $td = mcrypt_module_open('arcfour', '' , 'stream', '');
    mcrypt_generic_init($td, $key, null);
    $encrypted = mcrypt_generic($td, $msg);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $encrypted;
    }

    function rc4_decrypt($key,$msg) {
    return rc4_crypt($key,$msg);
    }
  ?>

Answer: I had the same problem and I can confirm you that your RC4 function in Arduino is wrong, you can use this instead:
unsigned char S[256];
unsigned int i, j;

void swap(unsigned char *s, unsigned int i, unsigned int j) {
        unsigned char temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }

    /* KSA */
    void rc4_init(unsigned char *key, unsigned int key_length) {
        for (i = 0; i < 256; i++)
            S[i] = i;

        for (i = j = 0; i < 256; i++) {
            j = (j + key[i % key_length] + S[i]) & 255;
            swap(S, i, j);
        }

        i = j = 0;
    }

    /* PRGA */
    unsigned char rc4_output() {
        i = (i + 1) & 255;
        j = (j + S[i]) & 255;

        swap(S, i, j);

        return S[(S[i] + S[j]) & 255];
    }

Comment: Thanks for share, check my comment with my last working implementation
Answer: This is the current implementation that i'm using
#define SWAP(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
class RC4
{
public:

    RC4 ()
    {
        memset(sbox,0,256);
        memset(key,0,256);
    }
    virtual ~RC4 ()
    {
        memset(sbox,0,256);
        memset(key,0,256);
    }

    char *Encrypt(char *pszText,const char *pszKey)
    {
        i=0, j=0,n = 0;
        ilen = (int)strlen(pszKey);

        for (m = 0;  m < 256; m++)
        {
            *(key + m)= *(pszKey + (m % ilen));
            *(sbox + m) = m;
        }
        for (m=0; m < 256; m++)
        {
            n = (n + *(sbox+m) + *(key + m)) &0xff;
            SWAP(*(sbox + m),*(sbox + n));
        }

        ilen = (int)strlen(pszText);
        for (m = 0; m < ilen; m++)
        {
            i = (i + 1) &0xff;
            j = (j + *(sbox + i)) &0xff;
            SWAP(*(sbox+i),*(sbox + j));

            k = *(sbox + ((*(sbox + i) + *(sbox + j)) &0xff ));
            if(k == *(pszText + m))
                k = 0;
            *(pszText + m) ^=  k;
        }

        return pszText;
    }

    char *Decrypt(char *pszText,const char *pszKey)
    {
        return Encrypt(pszText,pszKey) ;
    }

private:
    unsigned char sbox[256];
    unsigned char key[256],k;
    int  m, n, i, j, ilen;
};
;

Answer: After a lot of trials without success I ended up with the following three codes:

Arduino code implemented RC4 (adapted from this C code) and encoding the encrypted result in Base64
PHP code that decodes base64 and decrypts RC4
HTML to test the PHP (and eventually it will be the index of ESP32 Webserver). ATTENTION! sending Base64 in the Url can be dangerous becasue the characters '+' '/' '=' can create problems, so make sure you read this post Base64 in url and the charachters that can be problematic are replaced by '.' '_' '-'

At time of writing I am using Arduino core for ESP32 version 2.0.0 consider that if you are not using this version of Base64.h there could be incompatibility (more details here)
Arduino Code
#include <stdio.h>
#include <string.h>
#include "base64.h"

typedef unsigned long ULONG;

void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len)
{
    int i =0, j = 0;
    char k[256] = {0};
    unsigned char tmp = 0;
    for (i=0;i<256;i++) {
        s[i] = i;
        k[i] = key[i%Len];
    }
    for (i=0; i<256; i++) {
        j=(j+s[i]+k[i])%256;
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }
 }

void rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long Len)
{
    int i = 0, j = 0, t = 0;
    unsigned long k = 0;
    unsigned char tmp;
    for(k=0;k<Len;k++) {
        i=(i+1)%256;
        j=(j+s[i])%256;
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
        t=(s[i]+s[j])%256;
        Data[k] ^= s[t];
     }
}

int main()
{
    unsigned char s[256] = {0}; //S-box
    char key[256] = "Hello";
    char pData[512] = "secretMsg";
    ULONG len = strlen(pData);
    printf("key : %s\n", key);
    printf("raw : %s\n", pData);

    rc4_init(s,(unsigned char *)key,strlen(key));
    rc4_crypt(s,(unsigned char *)pData,len);
    printf("encrypt  : %s\n", pData);

    base64 b;

    String encoded = b.encode((unsigned char *)pData, strlen(pData));

    Serial.println(encoded);

    rc4_init(s,(unsigned char *)key, strlen(key));
    rc4_crypt(s,(unsigned char *)pData,len);
    printf("decrypt  : %s\n",pData);

    return 0;
}

void setup(){
  Serial.begin(115200);
  main();
}

void loop(){
}

PHP CODE
<?php

function rc4_crypt($key,$msg) {
          $td = mcrypt_module_open('arcfour', '' , 'stream', '');
    mcrypt_generic_init($td, $key, null);
    $encrypted = mcrypt_generic($td, $msg);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $encrypted;
    }

    function rc4_decrypt($key,$msg) {
    return rc4_crypt($key,$msg);
    }

if(isset($_POST['base'])) {
    $key = 'Hello';

    $msg_revealed = $_POST['base'];
    rc4_decrypt($key, base64_decode($msg_revealed))  //decode form base64 and decrypt

    $msg = 'secretMsg';     //for testing
    $encrypted = rc4_crypt($key, $msg);

    echo 'encrypted b64: ', base64_encode($encrypted) ,'
';
    echo "decrip: " , rc4_decrypt($key,rc4_crypt($key, $msg));
    exit;
}

?>

HTML CODE FOR TESTING and eventually the code that will be hosted on ESP32 webserver (more info here)

      <title>test Base64</title>
      <meta http-equiv='content-type' content='text/html;charset=utf-8' />
      <meta name='generator' content='Geany 1.36' />

      <form action='https://www.yourwebsite.com/base64.php' method='post' id='downloadForm'>
        <input hidden name='base' value='PASS_THE_URL_BASE64_ENCRYPTED_STRING_HERE'>
        </form>

<button type='button' class='btn btn-danger' onclick='sendBaseForm()'>TEST</button>


Are there nonograms of odd dimensions with a strong property

Question: This question is a follow on from the related question here.
A nonogram (or griddler), for this purpose, is an $m\times n$ blank rectangular grid with clues for each row and column.
A solution involves filling each square in the grid with a symbol $0$ or $1$ matching the clues.
A clue consists of a sequence of integers - for a row of length $m$, the integers might be $a,b,c,d$ with $a+b+c+d+3\le m$ (the number $3$ is one less than the number of clue integers). The clue means that there may be some zeros to the left, but that the leftmost block of ones contains $a$ ones, then there is at least one zero before the next block of exactly $b$ ones (etc). There is a clue for each row and column. The integers in the clues refer to all the ones in the relevant row or column. See the linked question for more detail.
In an answer to the linked problem, I observed that where $m$ and $n$ are even, there are two checkerboard patterns possible, and each generates the same clues. It is possible to put an (even x even) checkerboard in the corner of an array and fill the rest with zeros to get an indeterminate set of clues. If either dimension is $1$ the whole thing is determined by the clues.
The checkerboard pattern has the strong property that none of the values can be determined from the original clues. Is there any (odd x odd) or (odd x even) grid which has this same strong property. (filling a corner with a checkerboard leaves some completely determined rows and/or columns)?
Answer: $$\pmatrix{
1&0&0\\0&1&0\\0&0&1}$$
and
$$\pmatrix{
0&0&1\\0&1&0\\1&0&0}$$
have the same row and column descriptions.  I'm not sure if this meets your criteria or not, because I don't perfectly understand what is meant by "none of the values can be determined."  Any $3\times3$ permutation matrix has one $1$ in each row and column, and so has the same description.  It seems to me that given this description, you can't deduce the value in any cell, but I'm not sure that's what you mean.
Comment: Yes - I realised last night that any transposition matrix would have clues which were a single $1$ for every row and column. So that makes the question rather easy, and your example is the simplest. The twin checkerboard patterns in the even case also have the property that if any one cell is given, the whole pattern is known, so I was thinking a bit about that.


Is it possible to constrain a generic type defined in a jsDoc @template declaration?

Question: We'd like to define mixin classes in regular .js files using jsDoc comments instead of .ts files.
An important aspect of mixin classes is constraining the generic type parameter to a class constructor using extends. E.g., the above page has the following TypeScript:
type Constructor<T> = new(...args: any[]) => T;
function Tagged<T extends Constructor<{}>>(Base: T) { ... }

TypeScript's jsDoc support allows for a @template T declaration, but we don't see any way to constrain T to, for example, be a class constructor. Is there some way to do that?
We'd be willing to create/use .d.ts files to support this, as long as the mixin declaration itself can exist in a .js file, and that checkJs will appropriately type-check the workings of that .js file.
Comment: https://github.com/Microsoft/TypeScript/issues/1178
Comment: https://github.com/Microsoft/TypeScript/issues/24283
Answer: As of TypeScript 2.9 it seems constraining template parameters is now possible using TypeScript (see issue 24600). The above TypeScript declaration would therefor become:
/**
 * @template T
 * @typedef {new(...args: any[]) => T} Constructor
 **/

/**
 * @template {Constructor<{}>} T
 * @param {T} Base
 */
function Tagged(Base) { … }


TensorFlow Classification Using Dataset

Question: I need to utilize TensorFlow for a project to classify items based on their attributes to a certain class (either 1, 2, or 3).
Only problem is almost every TF tutorial or example I find online is about image recognition or text classification.  I can't find anything about classification based on numbers.  I guess what I'm asking for is where to get started.  If anyone knows of a relevant example, or if I'm just thinking about this completely wrong.
We are given the 13 attributes for each item, and need to use the TF neural network to classify each item correctly (or mark the margin of error).  But nothing online is showing me even how to start with this kind of dataset.
Example of dataset: (first value is class, other values are attributes)
2, 11.84, 2.89, 2.23, 18,   112, 1.72, 1.32, 0.43, 0.95, 2.65, 0.96, 2.52, 500
3, 13.69, 3.26, 2.54, 20,   107, 1.83, 0.56, 0.5,  0.8,  5.88, 0.96, 1.82, 680
3, 13.84, 4.12, 2.38, 19.5, 89,  1.8,  0.83, 0.48, 1.56, 9.01, 0.57, 1.64, 480
2, 11.56, 2.05, 3.23, 28.5, 119, 3.18, 5.08, 0.47, 1.87, 6,    0.93, 3.69, 465
1, 14.06, 1.63, 2.28, 16,   126, 3,    3.17, 0.24, 2.1,  5.65, 1.09, 3.71, 780

Comment: In non-convnets (like in the basic mnist example of TF) the image is actually just a list of numbers, so you can use that as a starting point.
Answer: Suppose you have the data in a file, data.txt. You can use Numpy to read this:
import numpy as np
xy = np.loadtxt('data.txt', unpack=True, dtype='float32')
x_data = xy[1:]
y_data = xy[0];

More information: http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.loadtxt.html
Perhaps, you may need 'np.transpose' depends on the shape of your weights and operations.
x_data = np.transpose(xy[1:])

Then, use 'placeholders' and 'feed_dict' to train/test your model:
X = tf.placeholder("float", ...
Y = tf.placeholder("float", ...
....
with tf.Session() as sess:
....
       sess.run(optimizer, feed_dict={X:x_data, Y:y_data})

Answer: for this kind problem TensorFlow have an in depth tutorial here
or in toward data science here
if your looking for videos to start i think sentdex's tutorials on the titanic data-set
is what your looking for although he is using k means to do the classification
(actually I think his entire deep learning/machine learning playlist is great to start with)
you can find it here
otherwise if your looking for basic how to start
first prepossessing:
try first separating the data into class labels and inputs (pandas lib should be able to help you with this)
make your class labels into a one-hot array
than normalize the data:
it looks like your different data attributes have wildly different ranges, make sure to get them all in the same range between 0 and 1
build your model:
a simple fully connected net should do the trick
remember to make the output layer the same size as the number of classes you have
use an argmax function on the output of the finale layer to decide which class the model thinks is the proper classification

TensorFlow Classification Using Dataset


How can I mount a composite rail kit on a ramp shallower than the brackets accommodate?

Question: I recently purchase stair railing kits to install on a handicap ramp for my mother-in-law's home.
The ramp angle is approx. 11 degrees. The install instructions for the kit, indicate they are usable for angles 26-36. What options are there for 'correcting' the 26-36deg brackets for use with 11deg? Or is there a better option not involving bracket modification or use of brackets at all?

I thought perhaps trying to cut 11deg channels for the rails in the posts, but cannot find an convenient/easy way to do so. Another idea is had would be to sand the mounting plate side of the bracket to reduce the post-to-bracket attachment angle from 90 to 75? I'm just fishing for ideas/suggestions. This cannot be an unusual issue for users of these kits.
Comment: What are you mounting them to?
Answer: For that shallow of a slope I'd be inclined to look at level railing kits and their associated hardware instead. That would be a much closer starting point. I'd then mill some 11° wedges from white vinyl to place behind the brackets, tilting them into position.
If that's not a good solution, create some 20° wedges (31° - 11°). Pre-drill them so that longer mounting screws pass through smoothly at the bracket mounting hole locations.
Solid vinyl board stock is readily available at home improvement stores. Try to find pieces that allow you to leave the factory milled finish on exposed faces. Cut faces will show a rough, porous surface.
Ideally the wedges will be roughly 1/2" wider and taller than the brackets (for a 1/4" reveal all around), and smaller than the posts (to avoid flush joints, which are tricky and can be unsightly).
Comment: The first suggestion won't work because the spindles would not be vertical. The other suggestions I like, but I don't think there is sufficient room for 1/4" reveal all the way around. I will see if I can find the blocks you suggest. The mounting is to 4x4 PT posts. Thanks.
Comment: Maybe, but there may be enough play in the spindle cavities for a little tilt. Those assemblies aren't solid. And if there isn't room for 1/4", go with 1/8". I seriously doubt you wouldn't have at least that much space.
Comment: I looked further into your suggestion. Unfortunately, the vinyl blocks are ridiculously expensive--$19 each. So, I will instead use PT  2x4s to make the wedges. On the plus side, the reveal will not be an issue.
Comment: I don't think we're talking about the same thing. I'd have expected that you'd buy a single board for roughly that price and cut all your wedges from it.
Comment: The only vinyl material available near me is 1.5x0.75x8ft for $8. That is cheaper than the block 12.5x8 3/8 x 1 7/8 ($18), but I don't want to piece several together to make one block.  I wish I could find what you describe.


How do I use this seemingly simple loop in CodeIgniter's view?

Question: In the view, right before the footer, I want to load three JavaScript files.  So, the controller sets three variables. For example, $js_1 = "bootstrap.js", $js_2 = '' and $js_3 = "tinymce.js", which may or may not be empty. The logic is, it should echo only if the variable is not empty. I also want to use the ternary if operator.
This was the best I could try.
for ($i = 1; $i <= 3; $i++)
{
    echo (!empty ('$js_' . $i)) ? get_jscript('$js_' . $i) : NULL;
}

The function get_jscript() simply returns the HTML script src.
function get_jscript($js)
{
    return ' ';
}

Please note that I intend to ask this question to primarily learn the correct PHP syntax and not just load JS in the view.
Comment: Possible duplicate of [Codeigniter - how to include a dynamic javascript file in a view](http://stackoverflow.com/questions/17952185/codeigniter-how-to-include-a-dynamic-javascript-file-in-a-view)
Answer: if you can create a array like this->
$javascript = array('js_1' => "bootstrap.js", 'js_2' => '', 'js_3' = "tinymce.js");

then in your view you have to just call a method
loop_javascript($javascript);

it's better to create a function in codeigniter helper and call that helper in controller's function (check how to use helpers in codeingiter) https://ellislab.com/codeigniter/user-guide/general/helpers.html->
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('loop_javascript'))
{
    function loop_javascript($jscript_array)
    {
        foreach($jscript_array as $key =>$value){
            if($value != ''){
                echo '';
            }
        }
    }
}

Comment: Thanks. I'm gonna try doing it that way.
Answer: This has some great info on how to use variable variables.
for ($i = 1; $i <= 3; $i++)
{
    echo (!empty (${'js_'.$i})) ? get_jscript(${'js_'.$i}) : NULL;
}

Answer: for ($i = 1; $i <= 3; $i++)
{
    if(!empty($js.'_'.$i)){ echo get_jscript($js.'_'.$i); echo "
";}
}

function get_jscript($js)
{
    return ' ';
}

Comment: While this answer is probably correct and useful, it is preferred if you [include some explanation along with it](http://meta.stackexchange.com/q/114762/159034) to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. Thanks!
Comment: Dear @VivekGhimire i'm concatenating the value of  `$i` with `$js` => `$js.'_'.$i`, so it give us the variables `$js_1`,`$js_2`,`$js_3`.. and you can use `\n\r` insted of ``
Comment: No, mate. That doesn't work because looping that way would make $js a variable which does not exist. And clearly, since I want to load the JavaScript files, I'm doing it in the head or foot; which means no line breaks.
Comment: Dear @Hatchet, Thank you so much for the appreciation, i'll take care of these things in future and try to explain as much i can ...
Comment: @ManjeetBarnala, Thanks. I'll look upon them.


Remove interior paint from carpet

Question: I recently wanted to repaint an interior wall. I took many precautions to cover the carpet using tarps, tape, and newspaper. Despite all of that, I still managed to get paint onto the carpets and didn't notice until it had already dried.
I've been googling and all I can see are guides to remove the art-types of  paints from carpets (acrylic, latex, and water-based), which I assume is probably ill fated for me because I used a paint + primer that I got from walmart.
Is there any way to remove this paint without damaging the carpet any further?
Comment: Your paint you got from Walmart was almost certainly latex based (but check the can) so use some of those tips you found but take seriously the advice from Ben in the answer below.
Answer: Carpets and paints can be made from a variety of materials. Water might clean it up. Paint thinners might dissolve the carpet (depending on the carpet). You could try isopropyl alcohol without much risk. But I would start by testing some carpet fibers (cut a few fibers off with some scissors) in a dish of paint thinner before testing thinner on the carpet. And still, even if the fibers look okay, use caution applying thinner to carpet. Apply thinner to a rag instead, and wipe the paint off with the rag.
If thinner dissoves the carpet, then the last resort is to give the carpet a trim. Hopefully the paint is not too deep and you can carefully cut out just the paint.
Comment: It may be worth contacting a pro, I spilt modelling paint and a professional got it out. Further to this I have seen some carpet repair companies that can thread in patches of spare or similar carpet or cut out a patch from somewhere like a robe or closet to swap with a stained/damaged section. Looks like it was never there.

Remove interior paint from carpet


Deck Help with correct size lumber and spacing of supports

Question: I'm building five platforms that are 32'x16.5'. These platforms are for large Safari wall tents.
I'm using something called Tuff Blocksᵀᴹ as deck supports (instead of cement blocks) and they have a cradle for 2x joists and single-ply beams about 2 1/2" off the ground, so for a ground level deck no need for posts.
All lumber will be pressure treated Southern yellow pine (ground contact rated).
We will be as low to the ground as allowable using a drop beam design. By doing a drop beam I significantly lower the Tuff Blocks required from ~70 to ~20, saving ton of money and time leveling out each block.
The problem I'm having is that with any deck I've ever built, I've used multiple ply lumber to create beams but these Tuff Blocks only hold one board single-ply.
The joists will be 2x8s set at 16" on center down the 32' run of the deck, supported by a single-ply 2x10 beam. Maximum span of joists including cantilever will be 8'.
My plan is to have a beam every 8' or less (2 @ 8', 2 @ 7') down the 32' run with a total of 5 beams made of single ply 2x10 and those beams will run across the deck a total of 16.5' (1 board) with Tuff Blocks supporting the beam every 5' maximum. I'd like to cantilever those beams 9" on each end.
Can I use a single ply 2x10 of Southern yellow pine ground contact?  I think my spans are fine but I'm not sure and I want to make sure this thing doesn't have bounce - there's not going to be a lot of weight on it, only two or three people max in the tent at any time. I will also have a shower and a toilet built on the deck.
Can't find any good charts for single-ply deck beams. Again, the beams will be 2.5" off the ground.
Comment: Don't know tuff blocks, but the cradle is maybe 1.5 inches deep?  If so if you want extra stiffness, a 2x10 with a 2x8 should work.  You want to prevent the beam from flopping over mainly.  A 2x10 with blocks/angles should be enough.  A low deck means about the worst that happens is drinks get spilled.
Comment: Adding the drawing of your deck framing would help this question immensely.
Answer: A single number 2 grade or better Southern Pine 2x10 beam is good for a 4'-3" span if the joists are all 8 ft long and come from both sides of the beam. The beams at the ends that are only loaded from one side are good for a 6'-0" span. See IRC R507.5. Note that the table is for beams that are loaded from only one side. For a beam loaded from both sides, you have to add the joist span contributions from both sides. 8 ft joists on one side and 8 ft joists on the other side, for example, implies that you would look up the beam corresponding to 8 ft + 8 ft = 16 ft joists in that table.
Your 2x8 joists are unnecessarily deep. Based on 8' length and 16" spacing, the table of IRC R507.6 indicates that 2x6 joists are adequate.
The literature for that Tuff Block product says that they're designed for 1700 pounds. Taking dead load at 10 psf and live load at 40 psf, that implies a supportable area for each block of
1700#/(10 psf + 40 psf) = 34 ft².
This is basically a 6ft by 6ft square of deck. Your deck then needs a minimum of (32 ft)(16.5 ft)/(34 ft²/support) = 15.5 supports, so your 20 supports per deck sound reasonable. Beware of supporting a rigid beam on more than two supports, though. Often a low support will pick up zero load. Galileo wrote about this.
Drop Beam Problems:
An honest reading of the IRC's deck section doesn't cover drop beam decks unless they're braced against toppling by a ledger anchored to another structure, where that structure provides the deck's lateral restraint. Just like joists get blocking at their bearing points, each of your foundation support positions should probably have similar bracing. The code doesn't prescribe such bracing, though, so free standing drop beam decks seem non-conformant to me. If you really want the drop beam deck's height (because of piles of snow, for instance), then you should hire a geotechnical engineer. Instead of the blocking at each foundation position, I think that the cheapest and easiest detail would be four 4x4s set in concrete and sticking up 12" to brace the top of the drop beams against horizontal movement.
And if you work with an geotechnical engineer, ask him for a cheap alternative to these Tuff Block supports. With a compacted base of crushed rock which you should probably be doing anyway, I suspect that a chunk of pressure treated 4x6 laying on its side could replace these supports for less than half the cost. You might actually break even with an engineer, (10 USD/block)(5 deck)(23 block/deck) = 1150 USD.
Joist Bearing Problems:
Your 32' deck length with 8' joists worries me a little. Each joist requires 1-1/2" bearing when sitting on wood. This implies that 4 spans of 8'-0" length lumber will not add up to your 32'-0". At most they would add up to 32'-0" - 3(1.5") = 31'-7.5". Be sure to get that 1-1/2" of bearing.
Block Layout:
The beam span lengths or the weight at each block will prescribe block layouts. First I'll prescribe a layout based on span lengths, and then I'll check that layout against the 34 ft² maximum tributary area that was computed earlier.
The end beams have 6'-0" maximum span lengths, so 2 spans over 3 supports implies (16.5' - 2(6'))/2 = 2.25' long cantilevers on both ends. Footnote g from the table of IRC R507.5 rejects these cantilevers that are longer than 25% the span length of adjacent beams. Increasing the number of supports to 4 provides a conformant layout, with spans of 16.5'/3 = 5.5' length working with no cantilever. The tributary area of a non-corner support is (5.5')(8'/2) = 22 ft² which is less than the 34 ft² maximum.
The interior beams have 4'-3" maximum span lengths, so 3 spans over 4 supports implies (16.5' - 3(4.25'))/2 = 1.875' long cantilevers on both ends. Footnote g from the table of IRC R507.5 rejects these cantilevers that are longer than 25% the span length of adjacent beam. Increasing the number of supports to 5 provides a conformant layout, with spans of 16.5'/4 = 4.125' length. Again, no cantilever. The tributary area at a non edge support is (4.125')(8') = 33 ft² which is less than the 34 ft² maximum.
I count 23 total supports per deck.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/149508/discussion-on-answer-by-popham-deck-help-with-correct-size-lumber-and-spacing-of); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.


how to make a site mobile responsive when data is being pulled from another server

Question: I have created this website for a real estate client but am having a lot of trouble making the idx feed that is being pulled in responsive.
I am using a responsive theme (u-design) and it is working on mobile sites but the idx feeds that are located on the site are not.  I know that I will have to edit some css files and such...
That is fine with me but I just don't know how to do it.  I've spent a few days trying to compare files with other sites to see if I could figure it out but I just can't.  It is all very overwhelming to me.
Comment: No one wants to reverse-engineer an external site. Please read the FAQ on how to properly ask questions on StackOverflow.
Comment: Please read: http://meta.stackexchange.com/questions/125997/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it
Comment: As overwhelming as such things can be, you are best off finding a thorough reference manual and spending a day absorbing...
Comment: yes, i now realize that i didn't ask my question correctly and i apologize...
in all honesty, after trying to find a similar problem, i didn't even know how to ask the question i needed answered.  but Ennui has been very helpful.
Answer: It may not be possible if the IDX feed is just code served from another server, which in my experience it usually is (via an iframe).
If you don't have any way to access or change that server-side code you won't be able to do much, and if it's in an iframe the difference in source protocol between the frame and your website will prevent you from using client-side responsive techniques to make the IDX output responsive.  If the IDX feed is piped in via iframe and its content isn't already responsive there isn't much you can do without having access to the code that generates the IDX feed itself.
Comment: it's not an iframe. i've had to make a subdomain that only the idx uses and there is a "global wrapper" (page curling) that makes the results look like the rest of the site.  i have access to edit the css for the idx results but like i said.... it's all just overwhelming, especially when i'm not 100% sure what i am supposed to be changing.  as diodeus mentioned above, "No one wants to reverse-engineer an external site" and i totally understand.  i was just hoping there might be an easy answer :(
Comment: In that case it should be possible (make your wrapper code responsive on your end, and apply responsive CSS to the IDX content on their end).  There is no "easy" solution though, you have to go in and modify all of the CSS to make it responsive.  For a hacky kind of situation like this where you don't have control over the markup I would say the easiest way to go about it is to just write a bunch of hacky CSS media queries until it looks decent on all screen widths.
Comment: Look up @media css queries on google. simplest way to implement them is just using progressively smaller `@media only screen and (max-width: 1024px) { //code }` queries to define CSS presets for different screen widths.  Often in situations like this a combination of static pixel widths and percentages is easier than the trouble of trying to force disorganized markup into being a fully fluid responsive site.  Sadly there is no way around having to do the grunt work here - just take a day and read up on media queries, it might seem intimidating but it's very doable.
Comment: thank you SO much for taking the time to respond!  since the wrapper code is already responsive (i'm assuming it is already responsive since everything that shows up on the page that isn't related with idx  (header, footers, text) still responds to mobile) i will have to add the media queries to code on the idx website, correct?
Comment: Yeah - probably the easiest way to do it is save a static HTML version of the page WITH the IDX code rendered on it, then write a custom stylesheet with media queries that target the non-responsive elements of the code output by the IDX provider.  That way you can test offline without having to upload your CSS to the IDX software every time you want to see it (media queries tend to be one of those things you switch between the editor and browser A LOT to tweak little values).  If this helps please upvote/mark this question as the answer (the check box)!