Q:

How to iterate and encode list text instead of list?

I have been trying to encode the list price['value'], getting the error AttributeError: 'list' object has no attribute 'encode'.  After realising the problem, I've tried a number of different ways to encode the text before it's added to the list, but none have worked.
How do I use .encode('utf-8') correctly in this situation in order to get non-unicode data in the results for price['value'], by encoding the text and not the list?
import mechanize
from lxml import html
import csv
import io
from time import sleep

def save_products (products, writer):

    for product in products:

        writer.writerow([ product["title"][0].encode('utf-8') ])
        for price in product['prices']:
            writer.writerow([ price["value"] ])

f_out = open('pcdResult.csv', 'wb')
writer = csv.writer(f_out)

links = ["http://purechemsdirect.com/ourprices.html/" ]

br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

for link in links:

    print(link)
    r = br.open(link)

    content = r.read()

    products = []
    tree = html.fromstring(content)
    product_nodes = tree.xpath('//div[@class="col-md-6 col-lg-6 col-sm-12"]')

    for product_node in product_nodes:

        product = {}
        try:
            product['title'] = product_node.xpath('.//p/strong/text()')

        except:
            product['title'] = ""

        price_nodes = product_node.xpath('.//ul')

        product['prices'] = []
        for price_node in price_nodes:

            price = {}
            try:
                price['value'] = price_node.xpath('.//li/text()')

            except:
                price['value'] = ""

            product['prices'].append(price)
        products.append(product)
    save_products(products, writer)

f_out.close()

A:

Maybe try a list comprehension since price['value'] is a list. I'm assuming that the values inside price['value'] are strings, not other lists. If there are more lists inside, then this answer will not work.
def save_products (products, writer):

for product in products:

    writer.writerow([ product["title"][0].encode('utf-8') ])
    for price in product['prices']:
        writer.writerow([x.encode('utf-8') for x in price['value']])
...


Q:

How to create a fake class from scratch with PHPUnit?

I currently need to test a method that checks a class for the existance of a supplied method with PHPUnit.
Currently I simply create an empty class inside my unit test and it works fine. I am guessing there is probably a better solution though. This is the code that I am currently running:
class ControllerMiddleWareTest extends TestCase
{
    /**
     * Check to see if a faulty method name leads to a MethodNotFoundException.
     */
    public function testShouldMethodNotFoundException()
    {
        $this->expectException(MethodNotFoundException::class);

        $parameterBag = new Bag(['lang' => 'NL']);

        // This class name(and method) should never exist.
        new ControllerMiddleware('AwesomeController', 'init', $parameterBag);
    }
}

// Mock class so we get a MethodNotFoundException.
class AwesomeController{}

I have found plenty of examples where an existing class is being mocked but not where a class is created like this. How would I go about doing this properly?

A:

Found the solution:
$this->getMockBuilder('AwesomeController')->getMock();

If anybody else knows a better way or has any suggestions, I would be happy to hear it.


Q:

Find and Replace a section of a string with wildcard type search

I want to be able to read a file, and replace all instances of:
M9S1800.2 with S1800  (I want to get rid of the M9 and the .2).
The problem I am having is that the 4 digit number after the "S" can be different every time, as well as the number after the decimal.
For example,
It can be:  M9S3200.1   or M9S5400.1   or M9S5400.2
Can someone please show me how to do this with C#?
I know how to find and replace by using this code:
StreamReader reader = new StreamReader(fDialog.FileName.ToString());
string content = reader.ReadToEnd();
reader.Close();

content = Regex.Replace(content, "M2", "M3");

but with the M9S3200.1, I want to do a wildcard type replace.  For example it would be like replace M9S*.1 with S*   so M9S3200.1 would just become S3200.

A:

content = Regex.Replace(content, @"M9(S\d{4})\.\d", "$1");


Q:

RxJava Android sequence print data

I'm learning RxJava in Android.
I have:
Observable<Country> getCountries(){} // returns Countries
Observable<City> getCapital(int countryId){} // returns capital by country id

I want:
Print all country names returned by getCountries(). Then print capital name of each country from getCapital() method, except country with id=1. This all should be in one chain.
For example:
private Observable<Country> getCountries(){
    return Observable.just(
            new Country(0, "Luxemburg"),
            new Country(1, "Netherlands"),
            new Country(2, "Norway"),
            new Country(3, "India"),
            new Country(4, "Italy")
    );
}
private Observable<City> getCapital(int countryId){
    City city;
    switch (countryId){
        case 0: city = new City("Luxembrug");
            break;
        case 1: city = new City("Amsterdam");
            break;
        case 2: city = new City("Oslo");
            break;
        case 3: city = new City("Delhi");
            break;
        case 4: city = new City("Rome");
            break;
        default:
            city = new City("");
            break;
    }
    return Observable.just(city);
}

getCountries()
      .doOnNext(country -> Log.d("TAG", "Country: id="+country.getId()+" name="+country.getName()))
      .filter(country -> country.getId()!=1)
      .flatMap(country -> getCapital(country.getId()))
      .subscribe(city -> Log.d("TAG", "City: "+city.getName()));

What I want to get:
D: Country: id=0 name=Luxemburg
D: Country: id=1 name=Netherlands
D: Country: id=2 name=Norway
D: Country: id=3 name=India
D: Country: id=4 name=Italy
D: City: Amsterdam
D: City: Oslo
D: City: Delhi
D: City: Rome

What I get:
D: Country: id=0 name=Luxemburg
D: Country: id=1 name=Netherlands
D: City: Amsterdam
D: Country: id=2 name=Norway
D: City: Oslo
D: Country: id=3 name=India
D: City: Delhi
D: Country: id=4 name=Italy
D: City: Rome

How can I achieve this?
I should at first get all countries, print it and after then get capitals for this countries. But I don't understand how can I do this in one chain..
Thanks for any tips!

A:

Assuming you can't change the getCountries() and getCapital(int countryId) methods you can achieve it like this:
RxJava 1x:
    getCountries()
            .toList()
            .doOnNext(countries -> {
                for (Country country : countries) {
                    Log.d("TAG", "Country: id=" + country.getId() + " name=" + country.getName());
                }
            })
            .flatMap(Observable::from)
            .filter(country -> country.getId() != 1)
            .flatMap(new Func1<Country, Observable<City>>() {
                @Override public Observable<City> call(Country country) {
                    return getCapital(country.getId());
                }
            })
            .subscribe(city -> Log.d("TAG", "City: " + city.getName()));

RxJava 2x:
    getCountries()
            .toList()
            .doOnSuccess(countries -> {
                for (Country country : countries) {
                    Log.d("TAG", "Country: id=" + country.getId() + " name=" + country.getName());
                }
            })
            .toObservable()
            .flatMap(Observable::fromIterable)
            .filter(country -> country.getId() != 1)
            .flatMap(new Function<Country, ObservableSource<City>>() {
                @Override
                public ObservableSource<City> apply(@NonNull Country country) throws Exception {
                    return getCapital(country.getId());
                }
            })
            .subscribe(city -> Log.d("TAG", "City: " + city.getName()));


Q:

VC++ Mutex Issue

So I'm just learning about c++ mutexes and I'm following, for the most part, the examples on MSDN. Why am I getting timeouts? I have the mutex timeout set at 2000ms and the "fake" process set at 250ms using Sleep(). You can see it processes some fine, then starts blowing up.... I know if I up the mutex timeout to something like 60000ms, it'll be fine, but why would I want it that high for only a 250ms process? Also, why is it jumping from threadid #1 to threadid #25??
Thanks!
Eric
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686927(v=vs.85).aspx
int createMutex(char* mutexName)
{

#define THREADCOUNT 25

    HANDLE aThread[THREADCOUNT];
    DWORD ThreadID;
    int i;

    int ID[THREADCOUNT];

    // Create a mutex with no initial owner

    ghMutex = CreateMutex(
        NULL,              // default security attributes
        FALSE,             // initially not owned
        (LPCWSTR)mutexName);             // unnamed mutex

    if (ghMutex == NULL)
    {
        return 1;
    }

    // Create worker threads
    for( i=0; i < THREADCOUNT; i++ )
    {
        ID[i] = i +1;
        aThread[i] = CreateThread(
            NULL,       // default security attributes
            0,          // default stack size
            (LPTHREAD_START_ROUTINE) WriteToDatabase,
            &ID[i],       // no thread function arguments
            0,          // default creation flags
            &ThreadID); // receive thread identifier

        if( aThread[i] == NULL )
        {
            return 1;
        }
    }

    // Wait for all threads to terminate
    WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

    // Close thread and mutex handles
    for( i=0; i < THREADCOUNT; i++ ) CloseHandle(aThread[i]);

    CloseHandle(ghMutex);

    return 0;

}

DWORD WINAPI WriteToDatabase(int *ID){

    int threadID = *ID;

    char buffer[256];
    int MUTEX_TIMEOUT = 2000;
    int FAKE_PROCESS_TIME_DELAY = 250;

    DWORD dwWaitResult;

    // Request ownership of mutex.
    dwWaitResult = WaitForSingleObject(
        ghMutex,    // handle to mutex
        MUTEX_TIMEOUT);     // time-out interval

    sprintf(buffer, "NEW THREAD STARTED: #%d\n", threadID);
    printf(buffer);

    if(dwWaitResult == WAIT_OBJECT_0){

        // The thread got ownership of the mutex
        sprintf(buffer, "DB WRITE STATED: #%d\n", threadID);
        printf(buffer);

        Sleep(FAKE_PROCESS_TIME_DELAY); //simulate a long running process (db process?) which creates a WAIT_TIMEOUT

        sprintf(buffer, "DB WRITE COMPLETED: #%d\n", threadID);
        printf(buffer);

        dwCount++;
        ReleaseMutex(ghMutex);

        return TRUE;
    }else{
        switch(dwWaitResult){
                case WAIT_ABANDONED:
                    sprintf(buffer, "MUTEX ERROR [%s] #%d\n", "WAIT_ABANDONED", threadID);
                    break;
                case WAIT_TIMEOUT:
                    sprintf(buffer, "MUTEX ERROR [%s] #%d\n", "WAIT_TIMEOUT", threadID);
                    break;
                default:
                    sprintf(buffer, "MUTEX ERROR [%s] #%d\n", "UNKNOWN", threadID);
        }

        printf(buffer);
        MutexERRORs++;

        //ReleaseMutex(ghMutex);
        return FALSE;
    }

    return TRUE;
}

A:

You're creating 25 threads at practically the same time, if each takes the mutex for ~250ms then with each thread running back-to-back the total time for all threads to process is going to be 250ms * 25 = 6250ms. With this in mind, some of your threads are sure to time-out acquiring the mutex because you're only waiting 2000ms. Indeed, it looks like after 8 threads have processed, the rest time-out (which should come as no surprise since 250ms * 8 = 2000ms).
As far as thread #25 acquiring the mutex after thread #1, I don't believe there's any guaranteed ordering with regards waiting vs. acquiring the mutex. Run it a number of times and you'll likely get a different order on each run.


Q:

How do you get SharePoint "My Links" back after a profile has been deleted and restored?

We're running SharePoint 2007 SP1 and profiles are imported from Active Directory (a full import runs daily).  We had a problem where many of the users were disabled unintentionally in Active Directory and this caused their profiles to be removed from SharePoint.  We re-enabled their Active Directory accounts and ran a full import which restored their SharePoint profiles.  However, all of their My Links are missing.  Is there a method or best practice for restoring them?

A:

I posted this because I couldn't find an answer to my problem anywhere.  This post by Joel Oleson that describes a similar problem to mine gave me a hint as to where to go looking for the missing data.  And This post by Corey Roth showed me how to programatically add the links to a users My Links.
First things first - you need to restore a backup of the database that contains the My Links data.  You don't want to restore over your working database, you want to restore it to another location.  The links stored in the SSP Database.  (You can find out the name of the database by going into Central Admin --> Shared Services Admin then open the menu for the SSP and click on Edit Properties - the SSP Database is listed on the properties page.)
Once the database has been restored you want to retrieve the Link information:

the domain account name of the user who owns the link,
the url of the link
the name of the link

This query will get you that information:
SELECT UPF.NTName, UL.Url, UL.Title
FROM UserLinks UL INNER JOIN UserProfile_full UPF ON UL.recordID = UPF.recordID
INNER JOIN UserPrivacyPolicy UPP ON UL.PolicyId = UPP.id
ORDER BY NTName

(I should note that I did not take into account what group or what privacy level the links were set to, you could probably find that information by looking at the information in the UserPrivacyPolicy table)
I copied the results into Excel & saved it as a .csv file (comma separated list) - just because my production server did not have access to the location where I restored my database.  I ordered the columns with Title last because the Title could contain commas and that would mess up how I'm reading in the data.  (I checked and the other two fields do not contain commas - you should check yours before making this assumption.)
I then wrote a little console app to import the data.  It takes two arguments:

the path where the file containing all of the links is located (ie c:\temp\links.csv)
the url of the SSP from with the My Links have gone missing (ie https://portal.mydomain.com)

These are the references used:

Microsoft.Office.Server (C:\Program Files\Common Files\Microsoft    Shared\Web Server    Extensions\12\ISAPI\Microsoft.Office.Server.dll)
Microsoft.SharePoint (C:\Program Files\Common Files\Microsoft    Shared\Web Server    Extensions\12\ISAPI\Microsoft.SharePoint.dll)
System
System.Data
System.Web
System.Xml

And this is the code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Web;

namespace UserLinks
{
    class Program
    {
        static void Main(string[] args)
        {
            string _accountName = "", _linkTitle = "", _url = "", _tmp = "", _path = "", _SPSsite = "";

            // Check arguments
            if (args.Length != 2)
            {
                ShowUsage();
                return;
            }

            _path = args[0];
            _SPSsite = args[1];

            using (SPSite _site = new SPSite(_SPSsite))
            {
                ServerContext _context = ServerContext.GetContext(_site);
                UserProfileManager _userProfileManger = new UserProfileManager(_context);

                /* Expecting a comma seperated list with 3 columns:
                 * AccountName in the format Domain\Account name - I am assuming there are no commas in this field
                 * URL - I am assuming there are no commas in this field
                 * Link Title - link title is last because there may be commas in the title
                */
                TextReader _reader = new StreamReader(_path, System.Text.Encoding.Default);
                while (_reader.Peek() != -1)
                {
                    _tmp = _reader.ReadLine();
                    _accountName = _tmp.Substring(0, _tmp.IndexOf(','));
                    _tmp = _tmp.Replace(_accountName + ",", "");
                    _url = _tmp.Substring(0, _tmp.IndexOf(','));
                    _linkTitle = _tmp.Replace(_url + ",", "");

                    try
                    {
                        UserProfile _currentUser = _userProfileManger.GetUserProfile(_accountName);
                        QuickLinkManager _quickLinkManager = _currentUser.QuickLinks;
                        _quickLinkManager.Create(_linkTitle, _url, QuickLinkGroupType.General, null, Privacy.Private);  //I am assuming that all links have no group assigned to them and they are all private links
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(_accountName);
                        Console.WriteLine(ex);
                    }

                }
                _reader.Close();

            }
        }

        private static void ShowUsage()
        {
            Console.WriteLine("Usage");
            Console.WriteLine("UserLinks [FilePath] [SharePoint URL]");
        }

    }
}

So problem solved & as a side benefit, this program can be used to force links to show up in a user's My Links list.


Q:

Does "have you not scolded by any" make any sense?

While chatting with a friend I used the phrase "have you not scolded by any". But it doesn't sound correct. Does it make any sense?

A:

It is "have you scolded any" if you are asking your friend if s/he scolded somebody, or "have you been scolded by any[body]" if you are asking your friend if somebody scolded her/him.
In the latter case, by any is probably not necessary, except when you are saying, for example, "by any of your relatives."


Q:

If a line parallel to $y=-7x+3$ touches the parabola $2x^2-3x+2$ in the point $(x_0,y_0)$, what is the value of $4x_0+y_0$?

I tried solving this but I've no idea how to find the point where a line of the form $y=-7x+n$ intersects a given parabola.
Hints are welcome. Don't know calculus (don't even know if it's applicable here, but either way).

A:

Hint: the line $y=ax+b$ meets the parabola $y=cx^2+dx+e$ when $ax+b=cx^2+dx+e$ - can you see why?
Second hint: the tangent to a parabola meets it at just one point as you will see from a simple sketch


Q:

Adding infiinity to set of even numbers?

I've defined even numbers via the following format:
Inductive even : nat -> Prop :=
| ev0: even 0
| evSS: forall n, even n -> even S (S n) .

I want to add infinity to the list, so something like (even inf) as a Proposition. How can I do this?

A:

The definition of nat in Coq does not have an infinite value. Thus, the first step is to add such an element. Here is one possible definition:
Inductive nat_inf :=
| Fin : nat -> nat_inf
| Inf.

You can now define evenness as follows:
Inductive even : nat_inf -> Prop :=
| ev0   : even (Fin 0)
| evSS  : forall n, even (Fin n) -> even (Fin (S (S n)))
| evInf : even Inf.


Q:

считать значения переменных в словарь из строки вида: "key1=value1 key2=value2 key3=value3"

Вводится строка виде "a=1 b=2 c=3". Необходимо считать значение переменных а,b,c в эти переменных. Проблема в том, что эти значения могут быть вперемешку(Не a,b,c, а b,a,c). Желательно, сохранить вообще всё это в словарь, но сойдёт и в переменные

A:

Вот записывает в словарь с ключами 'a', 'b' и 'c' и соответствующими им значениями:
d = {i.split('=')[0]: int(i.split('=')[1]) for i in input().split(' ')}
print(d)

Или вот так:
d = {}
for i in input().split(' '):
    spl = i.split('=')
    d[spl[0]] = int(spl[1])
print(d)


Q:

Sum up all values from a child node and pass the sum value to another child node

I'm having a problem passing the values of child "like" to child "post" (node "postLikes"). Here's my Json tree :

Here's my listener for the button like event :
mDatabaseRefLike.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        UserLike userLike = new UserLike();
        if(mProcessLike){

            if(dataSnapshot.child(mPostKey).hasChild(mUserId)){
                mDatabaseRefLike.child(mPostKey).child(mUserId).removeValue();
                mProcessLike = false;

            }else {
                mDatabaseRefLike.child(mPostKey).child(mUserId).setValue(1);
                userLike.setUserLikes(1);
                mProcessLike = false;

                for (DataSnapshot snap: dataSnapshot.getChildren()) {
                    UserLike getLikes= snap.getValue(UserLike.class);
                    int gLikes = getLikes.getUserLikes();

                    gLikes += gLikes;

                    mDatabaseRefPost.child(mPostKey).child("postLikes").setValue(gLikes);
                }
            }
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

I already spent days to solve this problem, and it seems I couldn't find a solution.

A:

It should be like this: (I've included comment so that it can be understood easier)
mDatabaseRefLike.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // sorry I remove userLike object because I don't quite understand what is that for

        // get count data first before it's changed
        int likeCounter = (int) dataSnapshot.getChildrenCount();

        // here we add/remove value in "like/postId/userId"
        // and update likeCounter value
        if(dataSnapshot.child(mPostKey).hasChild(mUserId)) {
            mDatabaseRefLike.child(mPostKey).child(mUserId).removeValue();
            likeCounter--;

        } else {
            mDatabaseRefLike.child(mPostKey).child(mUserId).setValue(true);
            likeCounter++;
        }

        // then we update value in "post/postId/postLikes"
        mDatabaseRefPost.child(mPostKey).child("postLikes").setValue(likeCounter);
    }
    ...
});

Hope this helps.

Note:
Sorry it takes me long to understand your code. First I think your code just make simple thing more complicated. But when I tried to solve the problem, it actually is a good practice. Great job :)


Q:

Using git rev-parse with --parseopt to access named arguments in a shell script

When using the --parseopt option with git rev-parse, it outputs a string that can be passed to eval, e.g.
set -- --foo --bar=arg 'test' --

After running this command via eval, it sets $1 to "--foo", $2 to "--bar=arg", and $3 to "test". My question is, does the set command do any magic besides setting positional arguments that would allow my script to access options by name? Or do I have to manually loop through the arguments and check the names myself?

A:

There's no magic, but you can change what is evaled to something else, so you can access by name.  For example:
$ eval `git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'
$ echo $bar
arg
$ [[ ${foo+t} ]] && echo y
y
$ if [[ ${baz+t} ]]; then echo y; else echo n; fi
n

The sed removes the leading -- and for lines without an =, adds one to the end.  When the shell evals a line like foo= it sets a variable named foo to an empty string.  You can test that foo is set with [[ ${foo+t} ]] (t is arbitrary, I choose t as a mnemonic for true). You could also set the variable to some sentinel value in the sed, and then use a simple [[ $foo ]] test.
Depending on the variety of arguments you need to support, you may need to tweak the sed.   Using set -xv will show you everything that's happening so you can make changes:
$ set -xv
$ eval `git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'`
eval `git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'`
git rev-parse --foo --bar=arg | sed -r 's/--//g; /^[^=]+$/s/$/=/'
++ sed -r 's/--//g; /^[^=]+$/s/$/=/'
++ git rev-parse --foo --bar=arg
+ eval foo= bar=arg
foo= bar=arg
++ foo=
++ bar=arg


Q:

Stretch marks during weight training

I am 15 and my height is 5 ft. 7. I started working out about two months ago. I only did tricep push ups, bicep curls, and skull crushers because I was warned that workouts will stunt my growth. I just bulked right away without cutting. When I reached two weeks of work outs, I had stretch marks on my shoulders and biceps. I first thought that it was a scar of honor but as time passed it grew larger and deeper. Right now, it is very visible when I wear tank tops or sleeveless shirts. I want to cure this, but if it is hard to do so, I want to know how to prevent it.
Now I want to ask about the second part of this story. So, my father said that I am growing up and building mass at the same time, and by now my fragile skin cannot take it. He recommends me to workout when I am about 17, when I would already have strong skins that can endure such circumstances. Is this true? or do I just have to live with it. Lastly, this is not that important, but what would people think when they notice my stretch marks? Would they freak out or give me a disgusting look?
People who have already gone through this process, I would be grateful if you help me out.

A:

I am 35 years old and started lifting weights when I was 13 years old. I also have stretch marks where my pecks (pectoral muscle) chest connects with the shoulder. Stretch marks are due to the elasticity of your skin. Skin can stretch a certain amount, but it's ability to stretch is highly affected by what you consume (eat). Sugar intake will make your skin very inflexible and not able to stretch. I recommend eating 14 to 28 grams or less of sugar a day if you want to have the most skin elasticity(stretchability). This will be the case if you are 13, 17 or 35 etc.
What people think of your stretch marks is irrelevant. If someone is judging you by your appearance then they have missed a great deal and are clueless. All bodies fade to dust and there is always someone stronger than you. I recommend working out to gain strength to use for the greater good of all humankind. Pick up someone who has a broken leg, lift a log off of a child, carry a heavy object for someone... etc. I started working out to defend myself from bullies at school and over the years I have grown quite a bit mentally and I realize that things here can be very confusing and only you personally will be able to figure this life out with contemplation and experience. One thing that is hard to learn is that a positive attitude has far more weight on attraction than just the physical body. A great attitude with a big smile is key, muscles won't get you there alone.
Others are correct lifting is a lifelong process and two months is nothing (I know you worked hard and I do not de-value any of your hard work). I highly suggest you workout every other day for the rest of your life... only skip when necessary or on rare occasion. It is this sort of consistent workout which will serve you well. Your body will acquire the ability to heal very quickly compared to non-lifters because of the constant micro-tearing and healing of your muscle tissue. This ability to heal is not isolated to just your muscles... your whole body can heal faster.
I think drinking the aloe is a great idea... also I would drink at least a quart of water 30 minutes before your workout to help with lubricating your joints and helping with flexibility.
I would concentrate on bench press and squat for maximum benefit for your time. They work out a large grouping of muscles and give much more benefit than isolated muscle exercises. Remember form and consistency is more important than weight. Form first weight second.
I wish you the best brother.


Q:

Set a returned pointer NULL doesn't work?

I'm currently facing a Problem where I can't set a returned pointer NULL.
Here's a simplified version of my code:
const Item* Stack::removeItem() {
    return pointer_to_item;
}

Now I'm trying to delete this Item and set it to NULL
bool Slots::removeItem(const Item & item) {

    Item const *temp = stack[index]->removeItem(item);
    delete temp;
    temp = NULL;

    return true;
}

This doesn't set the returned pointer to NULL. The next time the item is accessed from the stack, variables are not set (like a memeber variable "id" in Item).
If I set it to NULL like this, it works just fine:
const Item* Stack::removeItem() {
    pointer_to_item = NULL;
    return pointer_to_item;
}

Thank you for your explanations!

A:

If I understand correctly, what you basically want is something like this:
const Item* Stack::removeItem() {
    Item *temp = pointer_to_item;
    pointer_to_item = NULL;
    return temp;
}


Q:

How to configure kube-proxy to serve from local node only

I need to configure kube-proxy to server from the pods running on the current node only , and avoid for the connections to bounce around different nodes.

A:

Found a solution in docs:
As of Kubernetes 1.5, packets sent to Services with Type=NodePort are source NAT’d by default. You can test this by creating a NodePort Service:
$ kubectl expose deployment source-ip-app --name=nodeport --port=80 --target-port=8080 --type=NodePort
service/nodeport exposed

$ NODEPORT=$(kubectl get -o jsonpath="{.spec.ports[0].nodePort}" services nodeport)
$ NODES=$(kubectl get nodes -o jsonpath='{ $.items[*].status.addresses[?(@.type=="ExternalIP")].address }')

If you’re running on a cloudprovider, you may need to open up a firewall-rule for the nodes:nodeport reported above. Now you can try reaching the Service from outside the cluster through the node port allocated above.
$ for node in $NODES; do curl -s $node:$NODEPORT | grep -i client_address; done
client_address=10.180.1.1
client_address=10.240.0.5
client_address=10.240.0.3

Note that these are not the correct client IPs, they’re cluster internal IPs. This is what happens:
Client sends packet to node2:nodePort
node2 replaces the source IP address (SNAT) in the packet with its own IP address
node2 replaces the destination IP on the packet with the pod IP
packet is routed to node 1, and then to the endpoint
the pod’s reply is routed back to node2
the pod’s reply is sent back to the client
Visually:
          client
             \ ^
              \ \
               v \
   node 1 <--- node 2
    | ^   SNAT
    | |   --->
    v |
 endpoint

To avoid this, Kubernetes has a feature to preserve the client source IP (check here for feature availability). Setting service.spec.externalTrafficPolicy to the value Local will only proxy requests to local endpoints, never forwarding traffic to other nodes and thereby preserving the original source IP address. If there are no local endpoints, packets sent to the node are dropped, so you can rely on the correct source-ip in any packet processing rules you might apply a packet that make it through to the endpoint.
Set the service.spec.externalTrafficPolicy field as follows:
$ kubectl patch svc nodeport -p '{"spec":{"externalTrafficPolicy":"Local"}}'
service/nodeport patched

Now, re-run the test:
$ for node in $NODES; do curl --connect-timeout 1 -s $node:$NODEPORT | grep -i client_address; done
client_address=104.132.1.79

Note that you only got one reply, with the right client IP, from the one node on which the endpoint pod is running.
This is what happens:
client sends packet to node2:nodePort, which doesn’t have any endpoints
packet is dropped
client sends packet to node1:nodePort, which does have endpoints
node1 routes packet to endpoint with the correct source IP
Visually:
        client
       ^ /   \
      / /     \
     / v       X
   node 1     node 2
    ^ |
    | |
    | v
 endpoint


Q:

Complex filtering in Ansible/Jinja2

I am pretty new to Jinja2, and I'm wondering how to achieve this.
Say I have the following vars:
---
servers:
  192.168.0.1:
    names:
      - foo.example.com
      - foo
    exports:
      data:
        foo1: /disks/foo1
        foo2: /disks/foo2
  192.168.0.2:
    ...

I want to create a symlink /data/foo1 to /disks/foo1 and /data/foo2 to /disks/foo2, but only on foo server; on other servers, make symlinks to their respective exports. So I thought file status=link with_items=... would be the correct thing to do. In Python, I can get the array I need using the following logic:
[
    { 'mount': mount, 'export': export }
    for ip, server in servers.iteritems()
    if ansible_hostname in server['names']
    and 'exports' in server
    and 'data' in server['exports']
    for mount, export in server['exports']['data'].iteritems()'
]

I don't know how to do this in Jinja2. I wanted to do something like
{{ servers | select('ansible_hostname in self.names') | ... }}

but that doesn't work. Would I need to create a plugin for this logic? Or is my approach all wrong and I should rethink the structure of my servers data?

A:

Answer from my comment:
Usually you want to use inventory_hostname variable – it is what you use as host name in inventory.
servers[ansible_hostname] will access servers' key with name of ansible_hostname's value.
Just for curiosity, you can check out this (complex filter chain) and this (runtime object construction).


Q:

Translate content in fields in bibliography entries (biblatex)

I have in the @thesis entries in my .bib file the names of institutions and types written in the local language of the thesis. I need to translate these to English. As an example, I need to translate institution names like

Universitetet i Oslo
Universitetet i Bergen
Høgskolen i Agder

to

University of Oslo
University of Bergen
Agder University College

and translate type names like

Hovedoppgave
Hovedfagsavhandling
Masteroppgave

to

Main subject thesis
Main subject thesis
MA thesis

Based on similar conversions I've done (Change US postal codes (CA) to AP stylebook abbreviations (Calif.) in bibliography (biblatex)), I have a vague idea what to do, but I don't know how to accurately implement it:
\DeclareSourcemap{
  \maps[datatype = bibtex]{
    \map{
      \step[fieldsource = institution,
          match = , % <- strings like "Universitetet i Oslo", "Universitetet i Bergen"
          replace = ] % <- strings like "University of Oslo", "University of Bergen"
    }
    \map{
      \step[fieldsource = type,
          match = , % <- strings like "Hovedoppgave", "Masteroppgave"
          replace = ] % <- strings like "Main subject thesis", "MA thesis"
    }
  }
}

EDIT
There seems to be a problem doing this when the string I need to replace contains non-ascii characters like æøå:
\documentclass{article}
\usepackage[style = authoryear-comp]{biblatex}
\usepackage{fontspec,filecontents}
\begin{filecontents}{\jobname.bib}
@THESIS{aasen2004,
    AUTHOR = "Anita Aasen",
    INSTITUTION = "Universitetet i Oslo",
    TITLE = "Språklig nivellering i Oslo-regionen",
    TYPE = "Hovedfagsoppgave i nordisk språk og litteratur",
    YEAR = "2004",
    SUBTITLE = "Ungdommers valg av språklige varianter i Follo"}
\end{filecontents}
\DeclareSourcemap{
  \maps[datatype = bibtex]{
    \map{
       \step[fieldsource = type,
          match = {Hovedfagsoppgave i nordisk språk og litteratur},
          replace = {Main subject thesis}]
    }
  }
}
\addbibresource{\jobname.bib}
\begin{document}
\nocite{*}
\printbibliography
\end{document}

A:

Here is a solution using \regexps
\DeclareSourcemap{
  \maps[datatype = bibtex]{
    \map{
      \step[fieldsource = institution,
          match = \regexp{Universitetet(\s)i},
          replace = \regexp{University$1of}]
      \step[fieldsource = institution,
        match = \regexp{Høgskolen(\s)i(\s)(.*)},
        replace = \regexp{$3$1University$2College}
      ]
      }
    \map{
      \step[fieldsource = type,
          match = {Hovedoppgave},
          replace = {Main subject thesis} ]
      \step[fieldsource = type,
          match = {Hovedfagsavhandling}
          replace = {Main subject thesis}]
      \step[fieldsource = type,
          match = {Masteroppgave},
          replace = {MA Thesis}]
    }
  }
}


Q:

SQL percentage syntax

May I ask why I should use CodeA instead of CodeB for calculating the percentage? The result are totally different.
Thank you so much for your help!

CodeA:
select name, round(sum(amount_paid) /
  (select sum(amount_paid) from order_items) * 100.0, 2) as pct
from order_items
group by 1
order by 2 desc;

CodeB:
select name, round((amount_paid /
  sum(amount_paid)) * 100.0, 2) as pct
from order_items
group by 1
order by 2 desc;

A:

CodeB is totally wrong because it uses wrong GROUP BY statement (amount_paid column without aggregate function).
Strict databases will trowing error if you try to use this query.
CodeA uses subselect (select sum(amount_paid) from order_items) which calculates total sum(amount_paid) from table and then uses it for calculating percentage for each row.


Q:

Magento table rates custom options

In Tablerate.php I want to change the calculation.
So for some Products with custom options like width, height the shipping cost must change.
I tried with this method to find out if one product in cart has width or height greater than 60cm (example).
But currently I have no Idea how to get custom option values...
this code working well.
foreach ($request->getAllItems() as $item) {

        echo 'Name: '.$item->getName().
            '
 SKU:'.$item->getSku().
            '
 ProductID: '.$item->getProductId().
            '
 Price: '.$item->getPrice().'
';   }

A:

this worked
foreach ($request->getAllItems() as $item) {
    $selectedOpt = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
    $counted =  count($selectedOpt['options']);
    for ($i = 0; $i < $counted; $i++) {
        echo '
'. var_dump($selectedOpt['options'][$i]['option_value']);
    }
    echo '
';
}


Q:

Multiline lambda comparator

I am starting with the lambda expressions in Java and there is something that I consider bizarre and I am sure that I am doing something wrong or it has a workaround.
To define a comparator, I can do:
 col.setComparator((CustomCell o1, CustomCell o2) ->
            ((Comparable) o1.getValue()).compareTo(o2.getValue())
        );

Which is great, however, if I just add two "{". I get a compilation error:
 col.setComparator((CustomCell o1, CustomCell o2) -> {
            ((Comparable) o1.getValue()).compareTo(o2.getValue());
        });

The error is not related to the "{", but to setComparator:
The method setComparator(Comparator<CustomCell>) in the type
TableColumnBase<CustomParentCell,CustomCell> is not applicable for the arguments
((CustomCell o1, CustomCell o2) -> {})

I have tried using the multiline statements before for actionevents and it does work:
 setOnAction(event -> {
        // do something
 });

Is it because it only has one argument?

A:

The method you are implementing with setOnAction is
public void handleEvent(ActionEvent event) ;

It has a return type of void: i.e. it doesn't return anything:
The method you are implementing with setComparator is
public int compare(CustomCell cell1, CustomCell cell2) ;

which returns a value. To use the longer form, you must have an explicit return statement for methods that return a value:
col.setComparator((CustomCell o1, CustomCell o2) -> {
        return ((Comparable) o1.getValue()).compareTo(o2.getValue());
    });


Q:

When using Cache.Add, is an exception thrown if the key exists already or does it fail silently?

I have read everywhere that the Add method fails if it already exists but does it throw an exception or does it fail silently?
I am writing a multithreaded web application where it should not exist already and it will cause problems if I overwrite the cache, so I can't use the Insert method.
Would this be something I could do:
try
{
    HttpContext.Current.Cache.Add("notifications", notifications, null,
      System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(8),
      System.Web.Caching.CacheItemPriority.High, null);
}
catch
{
    //do whatever if notifications already exist
}

Thanks for any answers :)

A:

System.Web.Caching.Cache is designed to be thread-safe in a multithreaded web application, and multiple threads may be in contention to add the same key to the cache.  So it depends on how you want to handle such race conditions.

In many cases, you will be inserting immutable data into the cache and won't care which thread 'wins' the race.  So you can use Add or Insert.
If you want "first one wins", use the Add method, if you want "last one wins (and overwrites)" use the Insert method.
There is no point in checking for existence before inserting/adding.  Another thread may insert the item after your check and before you attempt to add/insert.
Neither Add nor Insert with throw an exception if the key already exists.  It wouldn't make sense to do so as the Cache is designed for thread-safe insertion without locking.  Add will fail silently, and Insert wil overwrite.
Incidentally, when reading from the Cache, don't check for existence then read:
if (Cache["MyKey"] == null)
{
    // ... handle missing value
}
else
{
    // ... a race condition means the item may have been removed here
    // before you get a chance to read it

    MyType value = (MyType) Cache["MyKey"];
}

Instead, read the value from the cache and check for null:
MyType value = Cache["MyKey"] as MyType; // for reference types
if (value == null)
{
    // ... handle missing value
}


Q:

How to set some weights in a layer to a particulr number?

I would like to ask if  it is possible to set some weights in a layer to particular number or zero of pretrained model.
For example, I want to download Lecun model and set some weights in the last layer to number e.x 4 and calculate the accuracy.
How can I do that?

A:

You are after "net surgery". In python you can load the net and get direct access to the stored weights. Then you can tweak them as you pleased and save the modified net.


Q:

Run rails server command

I'm using ActiveAdmin framework, I followed the  ActiveAdmin's getting started and in the last step rails generate active_admin:resource [MyModelName] I write this: rails generate active_admin:resource User then I tried to see the results in the browser so I run the server rails s and then I get this problem:
 edu@edu-ThinkPad-Edge:~/Desktop/rails_proyects/fulbo$ rails server
 => Booting WEBrick
 => Rails 3.2.13 application starting in development on `http://0.0.0.0:3000`
 => Call with -d to detach
 => Ctrl-C to shutdown server Exiting /home/edu/Desktop/rails_proyects/fulbo/app/admin/users.rb:1:in `<top
 (required)>': uninitialized constant User (NameError)  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin/application.rb:179:in
 `block in load!'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin/application.rb:179:in
 `each'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin/application.rb:179:in
 `load!'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin/application.rb:197:in
 `routes'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin.rb:83:in
 `routes'   from
 /home/edu/Desktop/rails_proyects/fulbo/config/routes.rb:3:in `block in
 <top (required)>'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/actionpack-3.2.13/lib/action_dispatch/routing/route_set.rb:289:in
 `instance_exec'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/actionpack-3.2.13/lib/action_dispatch/routing/route_set.rb:289:in
 `eval_block'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/actionpack-3.2.13/lib/action_dispatch/routing/route_set.rb:267:in
 `draw'     from
 /home/edu/Desktop/rails_proyects/fulbo/config/routes.rb:1:in `<top
 (required)>'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:40:in
 `block in load_paths'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:40:in
 `each'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:40:in
 `load_paths'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application/routes_reloader.rb:16:in
 `reload!'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application.rb:108:in `reload_routes!'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin/reloader.rb:34:in
 `reload!'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activeadmin-0.6.0/lib/active_admin/reloader.rb:61:in
 `block in attach!'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:429:in
 `_run__246534365__prepare__874865436__callbacks'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:405:in
 `__run_callback'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:385:in
 `_run_prepare_callbacks'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/activesupport-3.2.13/lib/active_support/callbacks.rb:81:in
 `run_callbacks'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/actionpack-3.2.13/lib/action_dispatch/middleware/reloader.rb:74:in
 `prepare!'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/actionpack-3.2.13/lib/action_dispatch/middleware/reloader.rb:48:in
 `prepare!'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application/finisher.rb:47:in
 `block in <module:Finisher>'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `instance_exec'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `run'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/initializable.rb:55:in `block in run_initializers'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `each'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `run_initializers'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/application.rb:136:in `initialize!'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/railtie/configurable.rb:30:in
 `method_missing'   from
 /home/edu/Desktop/rails_proyects/fulbo/config/environment.rb:5:in
 `<top (required)>'     from
 /home/edu/Desktop/rails_proyects/fulbo/config.ru:3:in `block in
 <main>'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/builder.rb:51:in
 `instance_eval'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/builder.rb:51:in
 `initialize'   from /home/edu/Desktop/rails_proyects/fulbo/config.ru:in
 `new'  from /home/edu/Desktop/rails_proyects/fulbo/config.ru:in
 `<main>'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/builder.rb:40:in
 `eval'     from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/builder.rb:40:in
 `parse_file'   from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/server.rb:200:in
 `app'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/commands/server.rb:46:in `app'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/server.rb:304:in
 `wrapped_app'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/rack-1.4.5/lib/rack/server.rb:254:in
 `start'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/commands/server.rb:70:in `start'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/commands.rb:55:in
 `block in <top (required)>'    from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/commands.rb:50:in
 `tap'  from
 /home/edu/.rvm/gems/ruby-1.9.3-p392@fulbo/gems/railties-3.2.13/lib/rails/commands.rb:50:in
 `<top (required)>'     from script/rails:6:in `require'    from
 script/rails:6:in `<main>'

someone knows how to fix it or what's wrong.

A:

The problem you are encountering is - ActiveAdmin is trying to generate resource on users, but model for users doesn't exist. Therefore, you will have to create a model User before you generate active_admin resource on User.
Do it as follows:
rm app/admin/users.rb
rails generate model User username: string email: string
bundle exec rake db:migrate
#this should be successful
rails generate active_admin:resource User
rails server

Let me know, if it helps you out. Comment with the errors you encounter.
Good luck


Q:

how to echo variable with name including $ sign?

suppose two variables:
A1=1234
A2=5678
for i in 1 2
do
echo $A$i
done

it prints:
1
2

i want to print:
1234
5678

how to do that?

A:

You need:
for i in 1 2
do
  temp="A$i"
  echo "${!temp}"
done


Q:

ignore duplicated rows in database

I have a csv file wich I have imported in a database in phpmyadmin, I need to write to a file a new csv file but ignoring duplicated emails, for example if my query finds these two rows :
41  Alain   Aiseng  a.as@gmail.com  DL MCI

42  Alain   Aiseng  a.as@gmail.com  LNKD 05 14

BOTH rows should be ignored in my new csv output. What should be the SQL query for this ?

A:

You can generate a query for this (and then save the results to a file).  The query is:
select t.*
from table t
group by name, email
having count(*) = 1;

The columns name and email correspond to whichever columns hold Alain Aiseng and a.as@example.com.
Note that this uses a MySQL feature where column names do not have to be in the group by for an aggregation query.  This is one case where this feature is totally safe to use, because the having clause specifies that only one row matches the condition.

A:

       select * from table
       where email not in
       (select email from table group by email having count(*)>1)a;


Q:

Character buffer being overrun while reading file

I'm trying to read data from a file but I'm getting a STATUS_STACK_BUFFER_OVERRUN error and the app crashes.
I have a struct:
struct BSPEntities
{
    char* ents;
};

And I'm reading the file:
BSPEntities entities
ifstream mapfile;
int size = 54506;
int offset = 5182600;

entities.ents = new char[size];
mapfile.seekg(offset, ios::beg);
mapfile.read((char *)(&entities.ents), size);

"size" and "offset" are values loaded from the file and known to be valid. I have preprocessor directives #pragma pack(1) and #pragma push around the BSPEntities struct.
Thanks.

A:

&entities.ents is a pointer to a pointer to char.  The object pointed to (a pointer to char) is probably only 4 or 8 bytes depending on the architecture you're targeting, but you're trying to write 54,506 bytes to it.  Obviously 54,506 is larger than 8, so you're writing past the end of the pointer, and the behavior is undefined.
That read should just be mapfile.read(entities.ents, size);
Also you don't need to mess around with #pragma pack here, unless there's something more complicated going on that you're not showing.


Q:

Error de consulta a BBDD con PDO: Call to undefined method Conexion::prepare()

Estoy haciendo una consulta sencilla a mi BBDD usando PDO. Mi conexión a PDO la tengo almacenada en una clase llamada Conexion en un archivo llamado Conexion.php al que mando a llamar para instanciar mi clase.
El problema es que, cuando intento traer los datos de mi base de datos me tira este error:
Fatal error: Uncaught Error: Call to undefined method Conexion::prepare() in C:\xampp\htdocs\DAlessaShop.Admin\index.php:9 Stack trace: #0 {main} thrown in C:\xampp\htdocs\DAlessaShop.Admin\index.php on line 9

No entiendo porque me da ese error. Ya revisé mi clase y todo y aún no encuentro el error. Adjunto mi archivo con la clase y la porción donde estoy haciendo la consulta:
Conexion.php:
<?php

    class Conexion
    {
        function __construct() {
            try {
                session_start();

                $this->conexion = new PDO('mysql:host=' . $this->DB_SERVER . ';dbname=' . $this->DB_BBDD, $this->DB_USER, $this->DB_PASSWORD, $this->arrayOptions);

                return $this->conexion;
            } catch (PDOException $e) {

                die("Error de conexión " . $e->getMessage() . " en la línea " . $e->getLine());
            }
        }

    // Variables usadas para establecer conexión y las configuraciones pertinentes
        private $DB_SERVER = "localhost";
        private $DB_BBDD = "dalesashop";
        private $DB_USER = "root";
        private $DB_PASSWORD = "";
        public $conexion;
        private $arrayOptions = array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => FALSE,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
    }

    $conexion = new Conexion();
?>

index.php (donde estoy haciendo la consulta):
<?php

    include_once 'Models/Conexion.php';

    $query = "SELECT * FROM productos";

    try {
        $con_prep = $conexion->prepare($query);
        $con_prep->execute();

        $productos = $con_prep->fetchAll();
    } catch (PDOException $e) {
        die("Error: " . $e->getMessage() . "
on line: " . $e->getLine() . "
on file: " . $e->getFile());
    }
?>

A:

En tu caso, tienes una clase conexion con un unico metodo, el constructor. Cuando inicializas un objeto de esa clase, defines dentro de esta una propiedad publica llamada conexion.
En el index estas llamando al objeto conexion (de tipo conexion) y al metodo de esta clase, llamado prepare. Esto no es correcto, puesto que este ultimo metodo no existe en la definicion de tu clase.
Tienes dos maneras de solucionarlo:

define un metodo prepare en tu clase:
public function prepare($sql) {
$this->conexion->prepare($sql);
}

2.- en tu index.php llama a $conexion->conexion->prepare($sql);


Q:

MS SQL Database Structure about Space occupy

I am making a database in MS SQL.
And have a question about the long term database space occupy and performance issue.
I have a table of user can have different type of meta values.
Table_User
PK UserID

Table_User_Meta
PK UserMetaID int
FK UserID int
FK CreatedBy int
   CreateDate Datetime
   TextValue varchar(500) NULL
   DecimalValue decimal(18,0) NULL

For different usage the user might have different type of Meta Value, so that either the TextValue or DecimalValue will be null.
Since the TextValue can be maximum of 500, is it will occupy too much space when there are millions of rows are coming with only Decimal Value?
I thought about another way to do this.
Table_User
PK UserID

Table_User_Meta_Text
PK UserMetaTextID int
FK UserID int
FK CreatedBy int
   CreateDate Datetime
   MetaDescription varchar(500)

Table_User_Meta_Decimal
PK UserMetaTextID int
FK UserID int
FK CreatedBy int
   CreateDate Datetime
   DecimalValue decimal(18,0)

This way I am using two separate table which there will be no null field.
But this way will force me to read two tables once I need to retrieve data.
My question is which way will be better? For both space usage and performance in a long term condition. Probably there will be at least 100 millions of Users in the Table_User, and each User can have maximum two Meta regardless of Text or Decimal.
Thanks everyone!
Edit:
Explain about the possible duplicate question:
Thank you guys for answer my question and I think my question is not the same as this one SQL Server 2008, how much space does this occupy?
My question is more of which way is a good way to balancing space occupy and read/write performance. Because I never handled a database with large amount of data so I was kind of not sure which way is better for implementation.
The answers below still helps so I will consider more of the I/O performance than the space occupy. Thank you guys.

A:

At first, VARCHAR data type does not store unnecessary spaces,
unless you specify something like this: ABC      DEF. So do not
worry about the space in that case.
At second, if you worry about space, use BIGINT instead of
decimal(18,0) and do not worry about NULLs, which might save you a
lot of space.


Q:

local.settings.json transformation during Azure CI/CD

I have been looking for a way to transform values in local.settings.json of azure functions during the release pipeline. Please note I am not publishing function directly from the visual studio as the release process is automated with azure CI/CD. I could find below link but it didn't mention anything to automate it as the part of CI/CD.
I know how can do the config transformation for appsettings.json in.net core but so far I know local.settings.json will not copy to the release folder and I don't want to create another .json file on top of local.settings.json
https://docs.microsoft.com/en-us/azure/azure-functions/functions-develop-vs#function-app-settings

A:

I have found it in the Azure Release pipeline in the App Settings section as shown below. You can add all app settings key-value pairs using the syntax "-key value". For example, if you want to add an email address in the app settings of Azure function during release then write -Email "emailadress" under the App settings section of the release pipeline


Q:

Android sending HTTP POST request to the server

I'm creating an application that connects to the cakePHP website
I create a default HTTP client and send a HTTP POST request to the server.
The data is coming from the server in json format, and in the client side I take the value from the json array, this is my project structure.
Below I show some code that I used to connect with server
        try{
             HttpClient httpclient = new DefaultHttpClient();
             HttpPost httppost = new HttpPost("http://10.0.2.2/XXXX/logins/login1");

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        response = httpclient.execute(httppost);
        StringBuilder builder = new StringBuilder();
               BufferedReader   reader = new BufferedReader

            (new     InputStreamReader(response.getEntity().getContent(), "UTF-8"));

              for (String line = null; (line = reader.readLine()) != null;)

                    {
                    builder.append(line).append("\n");
                    }

              JSONTokener   tokener = new JSONTokener(builder.toString());
              JSONArray  finalResult = new JSONArray(tokener);
              System.out.println("finalresulttttttt"+finalResult.toString());
              System.out.println("finalresul length"+finalResult.length());
                Object type = new Object();

              if (finalResult.length() == 0 && type.equals("both"))
            {
        System.out.println("null value in the json array");

                }
    else {

           JSONObject   json_data = new JSONObject();

            for (int i = 0; i < finalResult.length(); i++)
               {
                   json_data = finalResult.getJSONObject(i);

                   JSONObject menuObject = json_data.getJSONObject("Userprofile");

                   group_id= menuObject.getString("group_id");
                   id = menuObject.getString("id");
                   name = menuObject.getString("name");
                }
                    }
                        }

                  catch (Exception e) {
               Toast.makeText(FirstMain.this,"exceptionnnnn",Toast.LENGTH_LONG).show();
                 e.printStackTrace();
                    }

My problem is

I need to connect every page with the server, for that I need to write the code every time in my all activity, is there any other way to make a connection to the server and send a request from every activity? The concept of an interface is something like....
Is there any class  that is supplied by the android library for connecting to the server?
Is any need to check all verification such as an SSL certificate such as in the client-side?
Are there any additional requirements needed for connecting to a server from android?
What is the need of implementing services like SOAP REST for interaction with the server

I'm a fresher in this field.. please give me answer for my  doubts..
And please support me...

A:

This will help you:
public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws Exception {

    // Making HTTP request
    try {

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            // new
            HttpParams httpParameters = httpPost.getParams();
            // Set the timeout in milliseconds until a connection is
            // established.
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 10000;
            HttpConnectionParams
                    .setSoTimeout(httpParameters, timeoutSocket);
            // new
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);
            // new
            HttpParams httpParameters = httpGet.getParams();
            // Set the timeout in milliseconds until a connection is
            // established.
            int timeoutConnection = 10000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 10000;
            HttpConnectionParams
                    .setSoTimeout(httpParameters, timeoutSocket);
            // new
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        throw new Exception("Unsupported encoding error.");
    } catch (ClientProtocolException e) {
        throw new Exception("Client protocol error.");
    } catch (SocketTimeoutException e) {
        throw new Exception("Sorry, socket timeout.");
    } catch (ConnectTimeoutException e) {
        throw new Exception("Sorry, connection timeout.");
    } catch (IOException e) {
        throw new Exception("I/O error(May be server down).");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        throw new Exception(e.getMessage());
    }

    // return JSON String
    return jObj;

}
 }

You can use the above class like this:
eg:
public class GetName extends AsyncTask<String, String, String> {
String imei = "abc";
JSONParser jsonParser = new JSONParser();

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

protected String doInBackground(String... args) {
    String name = null;
    String URL = "http://192.168.2.5:8000/mobile/";
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", mUsername));
    params.add(new BasicNameValuePair("password", mPassword));
    JSONObject json;
    try {
        json = jsonParser.makeHttpRequest(URL, "POST", params);
        try {
            int success = json.getInt(Settings.SUCCESS);
            if (success == 1) {
                name = json.getString("name");
            } else {
                name = null;
            }
        } catch (JSONException e) {
            name = null;
        }
    } catch (Exception e1) {
    }
    return name;
}

protected void onPostExecute(String name) {
    Toast.makeText(mcontext, name, Toast.LENGTH_SHORT).show();
 }
 }

How to use it:
Just create new JSONParse class by copying about class code.
Then you can call it any where in your application as shown in second code(Customize the second code).
You need to give manifest permission:
    <uses-permission android:name="android.permission.INTERNET" />

No need to check  SSL certificate.

A:

1 you can write a utility class HTTPPoster and wrap into HTTPAsyncCall. Use that class in each activity and pass parameters
2 URLConnection, but at Android better use AsyncTask especially for Android +4
3 you can set to trust everyone in Android side... not so safe..
4 no, but at android manifest need to add permissions, like Internet
5 there are 2 ways either you do manually or automatically with libraryesmarshaling, unmarshaling. JSON has less overhead.
I hope it helps!


Q:

When xml is changed the swf file doesn't change

I am trying to read values from XML to swf file ,so i have a xml file like this :
<?xml version="1.0" encoding="utf-8"?>
<GALLERY>

<IMAGE TITLE="ssasa">image1.jpg</IMAGE>
<IMAGE TITLE="oooo">image2.jpg</IMAGE>
<IMAGE TITLE="shop">image3.jpg</IMAGE>
</GALLERY>

In my AS3 flash file i have this code :
import flash.system.SecurityDomain;
import flash.system.Security;

var xml:XML;
var xmlList:XMLList;
var xmlLoader:URLLoader = new URLLoader();
Security.loadPolicyFile("http://localhost:15979/crossdomain.xml");
xmlLoader.load(new URLRequest("http://localhost:15979/default.aspx"));
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(event:Event):void
{
xml = XML(event.target.data);
xmlList = xml.children();
trace(xml.IMAGE[1].@TITLE);
txtname.text=xml.IMAGE[1].@TITLE;
}

In my timeline i have this :

As you can see i call my acionscript code in frame 22,but my problem is when i changed the data in xml file the swf file ,it doesn't apply to swf file and the swf file shows the old text on the screen ,but after closing the file it works fine and the new text appears.
I think it is because the iis  cachs the data .!!!
best regards

A:

I finally add this value to my request :
var request:URLRequest = new URLRequest("http://localhost:15979/default.aspx");
var variables:URLVariables = new URLVariables();
variables.nocache = new Date().getTime();
// set up other URLVariables here
request.data = variables;


Q:

using xpath in java to go through this list?

i have an xml file that contains lots of different nodes. some in particularly are nested like this:
 <emailAddresses>
            <emailAddress>
                <value>sambj1981@gmail.com</value>
                <typeSource>WORK</typeSource>
                <typeUser></typeUser>
                <primary>false</primary>
            </emailAddress>
            <emailAddress>
                <value>sambj@hotmail.co.uk</value>
                <typeSource>HOME</typeSource>
                <typeUser></typeUser>
                <primary>true</primary>
            </emailAddress>
        </emailAddresses>

From the above node, what i want to do is go through each  and get the values inside it(value, typeSource, typeUser etc) and put them in a POJO.
i tried to see if i can use this xpath expression "//emailAddress" but it doesnt return me the tags inside inside it. maybe i am doing it wrong. i am pretty new to using xpath.
i could do something like this:
//emailAddress/value | //emailAddress/typeSource | ..  but doing that will list all elements values together if im not mistaken leaving me to work out when i have finished reading from a specific emailAddress tag and going to the next emailAddress tag.
well to sum up my needs i basically want this to be returned similar to how you would return results from a bog standard sql query that returns results in a row. i.e. if your sql query produces 10 emailAddress, it will return each emailAddress in a row and i can simply iterate over "each emailAddress" and get the appropriate value based on the colunm name or index.

A:

No,

//emailAddress

doesn't return the tags inside, that is correct. What it does return is a NodeList/NodeSet. To actually get the values you can do something like this:
String emailpath = "//emailAddress";
String emailvalue = ".//value";

XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
Document document;
public XpathStuff(String file) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = docFactory.newDocumentBuilder();

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    document = builder.parse(bis);

    NodeList nodeList = getNodeList(document, emailpath);
    for(int i = 0; i < nodeList.getLength(); i++){
        System.out.println(getValue(nodeList.item(i), emailvalue));
    }
    bis.close();
}

public NodeList getNodeList(Document doc, String expr) {
    try {
        XPathExpression pathExpr = xpath.compile(expr);
        return (NodeList) pathExpr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return null;
}

//extracts the String value for the given expression
private String getValue(Node n, String expr) {
    try {
        XPathExpression pathExpr = xpath.compile(expr);
        return (String) pathExpr.evaluate(n,
                XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return null;
}

Maybe I should point out that when iterating over the Nodelist, in .//values the first dot means the current context. Without the dot you would get the first node all the time.


Q:

KML from PostGIS Geometry into Openlayers

im getting the KML value from my postgis database.. st_askml()
And the output is like this:
"<Polygon><outerBoundaryIs><LinearRing><coordinates>-99.999999990686774,48.499999959021807 -99.999999990686774,47.999999988824129 -99.500000020489097,47.999999988824129 -99.500000020489097,48.499999959021807 -99.999999990686774,48.499999959021807</coordinates></LinearRing></outerBoundaryIs></Polygon>"
Now i need to display them on a Openlayers Map i got.
Layer:
var KML_Layer = new OpenLayers.Layer.Vector('KML');
Formatting code:
function GetFeaturesFromKMLString (strKML) {
var format = new OpenLayers.Format.KML({
        'internalProjection': options.projections.source, //EPSG:3785/900913
        'externalProjection': options.projections.display //EPSG:4326
    });

return format.read(strKML);
};

Adding the feature to the layer:
KML_Layer.addFeatures(value.st_askml);
Debuggin info:
value.st_askml = The output format i pasted earlier in topic.
After running it trough the GetFeaturesFromKMLString() its set to [] (No value here)
How can i get this to display correctly on the map?

A:

ST_AsKML() function doesnt return you valid kml file for openlayers or google earth. the result you have seen being formed from raw coordinates for kml file. you can achive this with following code which @BradHards has mentioned.
put your output between <Placemark>your output</Placemark>. you can try it whether works or not with google earth. i have tested it and has worked.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
  <Style id="0">
  </Style>
    <Placemark>
     <Polygon>
      <outerBoundaryIs>
       <LinearRing>
        <coordinates>
        -99.999999990686774,48.499999959021807
        -99.999999990686774,47.999999988824129
        -99.500000020489097,47.999999988824129
        -99.500000020489097,48.499999959021807
        -99.999999990686774,48.499999959021807
        </coordinates>
       </LinearRing>
      </outerBoundaryIs>
     </Polygon>
    </Placemark>
</Document>
</kml>

i hope it helps you...


Q:

How to ping internal application url through Linux?

I want to ping internal application URL like http://test.com:8080/ , but it through error as unknown host , because there is DNS server or no standard setting for this server.
Thats means i have internal application which means application running in within network(only our network can access this application). if ping this url , it throws unknown host.
Please advise is there any way to ping internal application ?

A:

You ping hosts, not applications. ping relies on the ICMP protocol, which is completely outside of TCP, so it has no concept of ports (ports are a TCP thing). What you need to do is make sure that your test.com resolves to the correct IP address (the simplest way to do it would be to put the address statically into /etc/hosts).
For example, if you're test.com is at 10.0.0.1, your /etc/hosts on your local machine should contain a line with 10.0.0.1  test.com or you should ping 10.0.0.1 directly (ping 10.0.0.1).
Additionally, on the server, make sure that incoming ICMP requests aren't ignored (echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all) (usually by default, they aren't).


Q:

How to rig a bone that moves the entire object?

So what i'd like to do is use that bone to move the entire rig. Right now it is not parented with any other bone, i've just created it.

A:

Enter Edit Mode of the armature and parent every bone that doesn't have a parent yet to your main bone with offset.


Q:

quick random row selection in Postgres

I have a table in postgres that contains couple of millions  of rows. I have checked on the internet and I found the following
SELECT myid FROM mytable ORDER BY RANDOM() LIMIT 1;

It works, but it's really slow... is there another way to make that query, or a direct way to select a random row without reading all the table? By the way 'myid' is an integer but it can be an empty field.

A:

You might want to experiment with OFFSET, as in
SELECT myid FROM mytable OFFSET floor(random()*N) LIMIT 1;
The N is the number of rows in mytable. You may need to first do a SELECT COUNT(*) to figure out the value of N.
Update (by Antony Hatchkins)
You must use floor here:
SELECT myid FROM mytable OFFSET floor(random()*N) LIMIT 1;

Consider a table of 2 rows; random()*N generates 0 <= x < 2 and for example SELECT myid FROM mytable OFFSET 1.7 LIMIT 1; returns 0 rows because of implicit rounding to nearest int.

A:

PostgreSQL 9.5 introduced a new approach for much faster sample selection: TABLESAMPLE
The syntax is
SELECT * FROM my_table TABLESAMPLE BERNOULLI(percentage);
SELECT * FROM my_table TABLESAMPLE SYSTEM(percentage);

This is not the optimal solution if you want only one row selected, because you need to know the COUNT of the table to calculate the exact percentage.
To avoid a slow COUNT and use fast TABLESAMPLE for tables from 1 row to billions of rows, you can do:
 SELECT * FROM my_table TABLESAMPLE SYSTEM(0.000001) LIMIT 1;
 -- if you got no result:
 SELECT * FROM my_table TABLESAMPLE SYSTEM(0.00001) LIMIT 1;
 -- if you got no result:
 SELECT * FROM my_table TABLESAMPLE SYSTEM(0.0001) LIMIT 1;
 -- if you got no result:
 SELECT * FROM my_table TABLESAMPLE SYSTEM(0.001) LIMIT 1;
 ...

This might not look so elegant, but probably is faster than any of the other answers.
To decide whether you want to use BERNULLI oder SYSTEM, read about the difference at http://blog.2ndquadrant.com/tablesample-in-postgresql-9-5-2/

A:

I tried this with a subquery and it worked fine. Offset, at least in Postgresql v8.4.4 works fine.
select * from mytable offset random() * (select count(*) from mytable) limit 1 ;


Q:

c++ how to get a pointer to the current object in another class?

And again a bad-formulted question, but I don't know how to shortly explain this situation:
I have two classes. Let's name them A and B. A has a lot of member variables and methods. B is a struct which has a shared_pointer to an object of type A. Now A has a method that returns an instance of B (with a pointer to the current instance of A).
My problem is, that A is the subclass of C. C has the same method as described above as pure virtual. The code would look like this:
class C {
public:
  virtual B mymethod() const =0;
  virtual int getMyvar() const =0;
};

class A : public C {
public:
  B mymethod() const override;
  int getMyvar() const override;   //outputs myvar
private:
  int myvar;
};

struct B {
  std::shared_ptr<C> pointer;
};

B A::mymethod() const {
  B instance;
  instance.pointer = std::make_shared<A>(*this);   //is this wrong?
  return instance;
}

My compiler (gcc 4.8.2) creates the executables for the following code, but at runtime I get "Segmentation fault (core dumped)":
void AnotherClass::something() const {
  A object;
  B instance = object.mymethod();
  std::cout << instance.pointer->getMyvar();   //dumps the core womehow?
}

I read about the std::enable_shared_from_this but I could not figure out how it works or if it helps me.
Why do I get the error message and how can I fix this?

A:

From what I have read in the manual, you do:
class A : public C, std::enable_shared_from_this<A> {
public:
  B mymethod() override; // Notice the lack of const
private:
  int myvar;
};

and then:
B A::mymethod() {
  B instance;
  instance.pointer = shared_from_this();   // this should be right
  return instance;
}

Like this, all the instances of a std::shared_ptr to the same A object will share the same reference counter, and it will be destroyed only when it must be.
EDIT:
Also, notice that your object A must be managed by some other std::shared_ptr before you can call A::mymethod(). I.e. you must create A objects like this:
std::shared_ptr<A> a_obj(new A);

then you can call A::mymethod():
B b_obj = a_obj->mymethod();

EDIT2:
Method A::mymethod() (and consequently, C::mymethod()) can't be const to be able to call the non-const method shared_from_this().


Q:

S3 client reading the configuration file

Is there any free S3 client that supports reading AWS profiles from the configuration file (.aws/credentials)?
I tried Cyberduck and winSCP but they unfortunately don't have this kind of support.

A:

From help/en/howto/s3 – Cyberduck:

Connecting using credentials in ~/.aws/credentials
Download the S3 (Credentials from AWS Security Token Service) profile for preconfigured settings.

I downloaded the linked file and it worked fine.


Q:

Problem using AddMoleculeColumnToFrame on Google Colab

I’d been using AddMoleculeColumnToFrame on Google Colab with no problem. After not using it for about 1 month I just discovered that it stopped working, i.e. the images are not showing up in the data frame (see below).
Any ideas? The most likely explanation is that something changed on Google Colab. But could it also be that a new version of Pandas is causing the problem?
Here’s the link to the notebook and a screenshot.
https://colab.research.google.com/drive/1nQPmdEbYQgVsFr7c44yRd3wpXPEsJar3

A:

Seems like this is a problem with all pandas versions above 0.25.0, So I guess for now the easiest fix is to downgrade pandas. Or you can use this method which seemed to work for me:
from IPython.display import HTML
HTML(df.to_html())

https://colab.research.google.com/drive/1eP8VZdr61DIoYXRz3PfwmVeG71GRzsRG
I am not quite sure why but this also seems to work:
def display_mol(x):
    if isinstance(x, Mol):
        return x
    return x

df.style.format(display_mol)

Screenshot:


Q:

Java char/int conversion confusion

Given this code in Java:
    FileOutputStream os = new FileOutputStream("/tmp/test.dat");
    os.write(0x14);
    os.write(0xfe);
    os.write(0xae);

    os.write(String.valueOf((char) 0x14).getBytes("UTF-8"));
    os.write(String.valueOf((char) 0xfe).getBytes("UTF-8"));
    os.write(String.valueOf((char) 0xae).getBytes("UTF-8"));

    os.write("\u0014".getBytes("UTF-8"));
    os.write("\u00fe".getBytes("UTF-8"));
    os.write("\u00ae".getBytes("UTF-8"));

    os.close();

Can somebody explain to me why the first 3 bytes in test.dat are
14 fe ae

while the output from the last 6 os.write()'s are
14 c3 be c2

Basically, I want to literally output the bytes 14 fe ae.  I was storing these values as a String constant, and writing the value of these constants to a UTF-8 file, but 14 c3 be c2 was output instead. There's obviously a gap in my understanding in how these byte sequences are converted in Java.
Thanks!

A:

It gives:
0x 14 fe ae 14 c3 be c2 ae 14 c3 be c2 ae

The first three bytes are obvious.  They're just being outputted literally.  For the next three, you should remember that char in Java represents a UTF-16 code unit, not a byte.  So you're first creating the Unicode code units U+0014, U+00FE, U+00AE, then converting each to UTF-8.  U+0014 is 0x14 in UTF-8 (since it's also ASCII), but U+00FE is 0xC3 0xBE and U+00AE is 0xC2 0xAE.
You're creating the same characters again in the next three lines.
The bottom line is that if you want to store literal bytes, just use a byte array.


Q:

Loading bar over status bar?

I've seen several apps do this, and i've been wondering how it's done. If you look at the Wunderkit app, when it loads something, there's a blue animated bar that slides down to cover the status bar until it finishes loading. How is this done?

A:

you can subclass UIWindow.
And set it windowLevel = UIWindowLevelStatusBar;
code:
@interface CHLoadingWindow : UIWindow

@implementation CHLoadingWindow
- (id)init
{
  self = [super init];
  if (self) {
    self.windowLevel = UIWindowLevelStatusBar;
    // then draw your UI
  }
  return self;
}
@end

use it:
CHLoadingWindow *loading = [[CHLoadingWindow alloc] init];
[loading makeKeyAndVisible];

discover it:
[loading release];
loading = nil;

[[[[UIApplication sharedApplication] windows] objectAtIndex:0] makeKeyWindow];


Q:

Since there are no toilets on smaller aircraft, how do you deal with the inevitable?

How do you handle business on a small plane on long flights? For example a cross country in a C-172.

A:

The other answers are good, but don't touch on one key method...
Prevention.
Small aircraft like a Cessna 172 have a limited cruise time, about 4 hours maximum. They are small enough that they get relatively uncomfortable after 2-3 hours, and if flying in turbulence or challenging conditions, flights can be relatively short.
The best way I've found to avoid the problem is to make sure to use the facilities as close to departure time as possible and to limit my intake of fluids in the hour or so leading up to a flight.
The other option you have is to land and use the "facilities". Many unmanned airports that have terminals (like KMNM) have a keypad access and facilities inside. Airports are pretty common and you usually aren't more than 30 minutes away from an airport with a bathroom.
Just as a personal account of this, I was doing night training at my local field (Class C) and it was late (10:00 PM or so). One gentleman came on the radio and asked the tower if the FBO was open so he could use the facilities. The controller responded that the FBO was closed but he could taxi him to a quiet corner of the airfield for a few minutes. The pilot gladly took him up on the offer.

A:

I have had success with these things. They are basically a little baggy that has the same stuff they put in a diaper.
You can always wear adult diapers (and I have heard of it being done)
Some small planes can be fitted with a pilot relief tube. This is effectively a tube connected to a small venturi outside the plane. The venturi creates a low pressure system that causes there to be some suction on the tube. The tube terminates in the cockpit near the seat and the pilot is able to relieve them self. The fluid is drawn through the tube, atomized in the venturi and dispersed.
There are some more elaborate bottle like scenarios.
But of course, a good old bottle will suffice, it did for Lindbergh,

[Said to King George V upon his landing]
  So Lindbergh explained that in his airplane his chair was made of
  wicker and there was a hole in it. And there was a funnel below that
  hole. And his waste, whenever nature called, would go down through
  there into sort of an aluminum can. And so he explained that and said
  that rather than show up with it in Le Bourget, the airport that he
  landed in, that he just dropped it over France.

Some of the larger aircraft like the TBM, Caravan and similar turbo props can be fitted with a seat that hides a little toilet underneath.
As a bit of a counter to Rons points, a lot of smaller planes (Mooney comes to mind) have "extended range tank" upgrades that can greatly extend the range of light aircraft. Provided your back, ears, and stamina can handle it some people are flying 5-8 hour legs in GA planes. This has led to a lot of "interesting" scenarios and solutions by pilots.

A:

As mentioned prevention is generally best. Part of my job involves aerial survey work in a P.68, with flights regularly going over 5 hours. My personal record is a 7.5 hour flight. This is my method to keep bodily functions at bay:
The day before a long flight drink plenty of water to stay as hydrated as possible. On the day of the flight get your fluids in early in the day and avoid tea and coffee for at least 2 hours beforehand, and avoid dehydrating foods such as bacon rolls for breakfast. Relieve yourself as close as possible to your departure time.
In flight only take small sips of water to stave off thirst. At the end of a long flight I usually end up with roughly 1/2 to 2/3 of a bottle of water left.
As a last resort there are various devices to be used as mentioned that come in varieties for both genders, and there is always that water bottle...


Q:

Does Ext 3.2 have button icons?

http://dev.sencha.com/deploy/dev/examples/button/buttons.html
I saw this and was wondering if I have access to these kind of icons for my itemCl config option.

A:

Yes. Those specific images are in the ext_base_dir/examples/button/images directory.


Q:

Compare two lists of field names, and remove unique fields

I have 5 shapefiles in which certain fields need removing. I have a csv file with the correct shapefile name and which fields that need deleting.
I am trying to do a simple comparison of fields, and want to remove the ones not listed in the CSV.
However the print statement at the end does not tell me which fields are being deleted. This should theoretically tell me before i go ahead and delete the fields.
shapefiles = arcpy.ListFeatureClasses()

scursor = arcpy.da.SearchCursor(csv, ["FMEextracts", "NewField"])

for fc in shapefiles:
    newfieldlist = []
    oldfieldlist = []
    fields = arcpy.ListFields(fc)
    for field in fields:
        oldfieldlist.append(field.name)
        print "old fields", fc, oldfieldlist
        for srow in scursor:
            if fc == srow[0]:
                newfieldlist.append(srow[1])
                print "new fields", fc, newfieldlist

                if field.name not in newfieldlist:
                    if not field.required:
                        print "deleting", field.name,"from", fc
                        #arcpy.DeleteField_management(fc, field.name)

FMEextracts     NewField
NGC_CABLE.shp   ACTION_DTT
NGC_CABLE.shp   CABLE_ROUT
NGC_CABLE.shp   CABLE_SET
NGC_CABLE.shp   CABLE_TY00
NGC_CABLE.shp   CABLE_TYPE
NGC_CABLE.shp   COMMENTS
NGC_CABLE.shp   FID
NGC_CABLE.shp   GDO_GID
NGC_CABLE.shp   OPERATING_
NGC_CABLE.shp   OWNED
NGC_CABLE.shp   Shape
NGC_CABLE.shp   STATUS
NGC_CABLE.shp   TUNNEL
NGC_CABLE.shp   YEAR_OF_IN
NGC_GAS_PIPE_FEEDER.shp FID
NGC_GAS_PIPE_FEEDER.shp ABANDONED
NGC_GAS_PIPE_FEEDER.shp BPD
NGC_GAS_PIPE_FEEDER.shp DIAMETER
NGC_GAS_PIPE_FEEDER.shp GDO_GID

A:

I think it is possible to write less code for this task. Building lists and jumping back and forward will keep you in debugging forever.
My .csv file contents:
FMEextracts;NewField
NGC_CABLE.shp;ACTION_DTT
NGC_CABLE.shp;CABLE_ROUT
NGC_CABLE.shp;CABLE_SET
NGC_CABLE.shp;CABLE_TY00
NGC_CABLE.shp;CABLE_TYPE
NGC_CABLE.shp;COMMENTS
NGC_CABLE.shp;FID
NGC_CABLE.shp;GDO_GID
NGC_CABLE.shp;OPERATING_
NGC_CABLE.shp;OWNED
NGC_CABLE.shp;Shape
NGC_CABLE.shp;STATUS
NGC_CABLE.shp;TUNNEL
NGC_CABLE.shp;YEAR_OF_IN
NGC_GAS_PIPE_FEEDER.shp;FID
NGC_GAS_PIPE_FEEDER.shp;ABANDONED
NGC_GAS_PIPE_FEEDER.shp;BPD
NGC_GAS_PIPE_FEEDER.shp;DIAMETER
NGC_GAS_PIPE_FEEDER.shp;GDO_GID

ArcGIS 10.4+ solution (comes with pandas); you can also install pandas on your own:
import pandas as pd
import arcpy
arcpy.env.workspace = r'C:\GIS\Datasets\data_SHAPE'

shps = arcpy.ListFeatureClasses()#['NGC_CABLE.shp', 'NGC_GAS_PIPE_FEEDER.shp']
df = pd.read_csv(r"C:\GIS\Temp\ReferenceFields.csv", sep=';')

for shp in shps:
    print "Shapefile {}".format(shp).center(50, '-')

    fields_to_keep = list(df[df['FMEextracts'] == shp]['NewField'].values)

    for field in arcpy.ListFields(shp):
        if field.name not in fields_to_keep and not field.required:
            print "deleting the field  - ", field.name
    print

ArcGIS 10.x solution using the built-in Python csv module:
import csv
import arcpy
arcpy.env.workspace = r'C:\GIS\Datasets\data_SHAPE'
shps = arcpy.ListFeatureClasses()#['NGC_CABLE.shp', 'NGC_GAS_PIPE_FEEDER.shp']

f = open(r"C:\GIS\Temp\ReferenceFields.csv")
reader = csv.DictReader(f, delimiter=';')
data = [row for row in reader]

for shp in shps:
    print "Shapefile {}".format(shp).center(50, '-')

    fields_to_keep = [row['NewField'] for row in data if row['FMEextracts'] == shp]

    for field in arcpy.ListFields(shp):
        if field.name not in fields_to_keep and not field.required:
            print "deleting the field  - ", field.name
    print


Q:

The type of an expression must be an array type, but it is resolved to Object

I expected this to compile, but I kept getting the error "The type of an expression must be an array type, but it is resolved to Object". Is there a simple workaround for this?
public class NodeTest {
    public static void main(String[] args) {

    Object[] arr = new Object[5]; // each element of object will be an array of integers.
    for(int i = 0; i < 5; i++){
        int[][] a = new int[2*(i+1)][2*(i+1)];
        arr[i] = a;
    }
    arr[0][0][0] = 0; //error here
}

}

A:

arr is Object[] so arr[0] will return an Object
But since you know that arr contains int[][] as instance of Object you will have to cast them to be so.
( ( int[][] ) arr[0] )[0][0] = 0;

A:

You want to declare arr as int[][][] rather than Object[]. While arrays are of type Object so the assignment in the loop is legal, you're then losing that type information so the compiler doesn't know the elements of arr are int[][] in the bottom line.
int[][][] arr = new int[5][][];
for(int i = 0; i < arr.length; i++) { //good practice not to hardcode 5
    arr[i] = new int[2*(i+1)][2*(i+1)];
}
arr[0][0][0] = 0; //compiles


Q:

A sequence of order statistics from an iid sequence

Given a sequence of iid random variables $X_i$ (without loss of generality from $U(0,1)$), an integer $k \ge 1$ and some $p \in (0,1)$, construct the sequence of random vectors $Z^{(j)}$, $j=0,1,...$ in the following way. Let
$$Z^{(0)}=(X_{(1)},...,X_{(k)}),$$
where $X_{(l)}$ is the $l$-order statistic of sample $\{X_1,...,X_k\}$. Introduce notations
\begin{align}
Z^{(j)}&=(Z_{j,1},...,Z_{j,k}),\\
m_j&=\min(Z_{j-1,1},...,Z_{j-1,k},X_{k+j}),\\
M_j&=\max(Z_{j-1,1},...,Z_{j-1,k},X_{k+j})
\end{align}
Then
$$Z^{(j)}=(Y_{(1)},...,Y_{(k)})$$
where $Y_{(l)}$ is the $l$-order statistic of the following set which is

The set $\{Z_{j-1,1},...,Z_{j-1,k},X_{k+j}\}\backslash m_j$ with probability $p$
The set $\{Z_{j-1,1},...,Z_{j-1,k},X_{k+j}\}\backslash M_j$ with probability $1-p$

The decision between cases 1. and 2. is made independently from the $X_i$ (and hence from the $Z^{(i)}$).
The $Z^{(j)}$ are supported on the $k$-dimensional simplex $S_k = \{(x_1, \dots, x_k) \in \mathbb{R}^k \, | \, 0 \le x_1 \le x_2 \le \dots \le x_k \le 1 \}$.
It appears that the $Z^{(j)}$ converge in distribution. Is this known? Is anything known about the limiting distribution?
For the case $k=1$, the answer is the following. Denote the cdf of $Z^{(j)}$ by $F_j$.
The cdf of $\min(X_{n+1},Z^{(n)})$ (for $U(0,1)$ case) is
$$x+F_n(x)−xF_n(x)$$
and the cdf of $\max(X_{n+1},Z^{(n)})$ is
$$xF_n(x)$$.
Hence
\begin{align}
F_{n+1}(x)&=p(x+F_n(x)−xF_n(x))+(1−p)xF_n(x)\\
&=px+(p(1-x)+(1-p)x)F_n(x)
\end{align}
Since $p(1-x)+(1-p)x\in(0,1)$ we have that
$$\lim F_{n}(x)=\frac{px}{1-p(1-x)-(1-p)x}$$
I am looking for general results (case $k>1$) either for the limiting distribution of the whole vector $Z^{(j)}$ or of some of its components (marginal distributions).

A:

I've asked this question in mathoverflow. It has one answer, which I do not find time to check, so I am giving the link as an answer here.


Q:

requireJS and LESS

I'm using the client-side javascript version of LESS to compile out less code, and would like to continue using this even on the final live site (I know... bad form, but it gives me the ability to allow users to customize a few less variables and have that "theme" their whole app on the fly, seeing as it's a webapp that once loaded never refreshes, I'm thinking the additional second of load time to compile the less is acceptable).
I'm also using requireJS.
The question is:
A) How do I get requireJS to load less code?
B) Does less dispatch any events when compilation is complete? and
C) Is there a way to trigger less to re-compile on command?
Thanks.

A:

I have used the text loader plugin for RequireJS to load the .less file as text, then create a new less.Parser instance to parse the text, then add the style text myself:
(new less.Parser()).parse(lessText, function (err, css) {
  if (err) {
    if (typeof console !== 'undefined' && console.error) {
      console.error(err);
    }
  } else {
    var style = document.createElement('style');
    style.type = 'text/css';
    style.textContent = css.toCSS();
  }
});

You could take a similar approach, but give the style node an ID and remove that ID and then add back another reparsed LESS text when you want on demand.
A caveat: the text plugin can only load text files on demand when the text file is on the same domain as the web page. If you use the RequireJS optimizer, you can inline the text into a built, optimized JS file.

A:

@jrburke: I've put together a quick requirejs plugin based on your code:
define({

    version: '0.1',

    load: function(name, req, onLoad, config) {

        req(['text!' + name, 'base/less'], function(lessText) {

            var styleElem;

            (new less.Parser()).parse(lessText, function (err, css) {
                if (err) {
                    if (typeof console !== 'undefined' && console.error) {
                        console.error(err);
                    }
                } else {
                    styleElem = document.createElement('style');
                    styleElem.type = 'text/css';

                    if (styleElem.styleSheet)
                        styleElem.styleSheet.cssText = css.toCSS();
                    else
                        styleElem.appendChild( document.createTextNode( css.toCSS() ) );

                    document.getElementsByTagName("head")[0].appendChild( styleElem );
                }

                onLoad(styleElem);
            });

        });
    }

});

"base/less" points to the less source. You could also load this ahead of time, and assume the global less object exists. Ideally, I'd like to pull the less Parser object into this plugin itself so it doesn't create a global at all.
Using this I can do stuff like:
require(['less!global.less'], function(elem) {

});

At which point, global.less has been parsed and added to the page and gives back elem pointing to the style element in case I need to remove or modify it for some reason.
Does anyone have any input or know a better way of doing this?
Cheers

A:

I was having trouble with @nicholas plugin with imports. I fixed it by adding the path of the file to the search path, and set filename for better error messages:
// http://stackoverflow.com/questions/5889901/requirejs-and-less
// enables require(['share/less!whatever.less'], function(elem) {});
define({
    version: '0.1',
    load: function(name, req, onLoad, config) {
        req(['share/text!' + name, 'share/less-1.3.0'], function(lessText) {
            var styleElem;
            var parser = new(less.Parser)({
                filename: name,
                paths: [name.split('/').slice(0,-1).join('/') + '/'],
            });
            parser.parse(lessText, function (err, css) {
                if (err) {
                    if (typeof console !== 'undefined' && console.error) {
                        console.error(err);
                    }
                } else {
                    styleElem = document.createElement('style');
                    styleElem.type = 'text/css';

                    if (styleElem.styleSheet)
                        styleElem.styleSheet.cssText = css.toCSS();
                    else
                        styleElem.appendChild( document.createTextNode( css.toCSS() ) );

                    document.getElementsByTagName("head")[0].appendChild( styleElem );
                }
                onLoad(styleElem);
            });
        });
    }
});


Q:

Simple Ajax Post to PHP echo

I have the following code on product.php .. can't seem to echo post variable from ajax post. Alert displays fine. Please help
JQUERY
    document.getElementById("LBTest").onchange = function(){
      var lbtest = $('#LBTest :selected').val();
      $.ajax({
      type: "POST",
      url: "product.php",
      data: {test: lbtest},
      success: function()
      {
          alert("Successful");
      }
      });
}

PHP
if(isset($_POST['test'])){
    $data = $_POST['test'];
    echo $data;
}

A:

You need to do something with the data you receive from the ajax call. For example, to put the result into a <div> called resultDiv:
success: function(data)
{
  $('#resultDiv').html(data);
  alert("Successful");
}