text:
Q: Is it possible to publish items with multiple conditional fields from a collection? Consider this case, I have a party object, this party object has a few info fields about the party, location, time, guests, etc..
It also has a few fields that set privacy to some of the info fields, like showLocation, showGuests, etc..
These will hide this info from users not invited.
How can I only send to the client the fields where the "show" field is true?
When I publish a single item I can use something like this: (merge is not a real function)
Meteor.publish("party", function (_id) {
    var party = Parties.findOne({_id: _id});

    var fields = merge(
        {name: 1, title: 1, creatorUserId: 1},
        (party.showLocationAndDate ? {location: 1, date: 1} : null),
        (party.showGuests ? {guests: 1} : null)
    );

    return Parties.find({_id: _id}, {fields: fields});
});

When I publish multiple items but with a single condition I can use something like this:
Meteor.publish("parties", function () {
    var fieldsWithLocation = {
        name: 1,
        title: 1,
        creatorUserId: 1,
        location: 1
    };
    var fieldsWithoutLocation = {
        name: 1,
        title: 1,
        creatorUserId: 1
    };

    //return multiple cursors
    return [
        Parties.find({showLocation: true}, {fields: fieldsWithLocation}),
        Parties.find({showLocation: false}, {fields: fieldsWithoutLocation})
        ];
});

But how can I do this elegantly with a few conditional fields when publishing multiple items?

A: 1) based on Michel Floyds "subscribe to them all!" solution, return multiple cursors from a publish like this:
return [
    Identities.find(query, options),
    Identities.find(merge(query, {showLocation: true}), {fields: {location: 1}}),
    Identities.find(merge(query, {showGuests: true}), {fields: {guests: 1}}),
];

2) Add a third field called "publicX" and fill/empty that field whenever the item with "showX" is edited/created, then include
this field in the field specifier instead of the true "X" field.
This solution is the only one that works if you also want to sort or filter by these fields, that way you can use publicX instead of "X" in queries and field specifiers.
3) use an observation yourself and control the results more tightly:
Meteor.publish("activeParties", function () {
    var self = this;
    var query = {active: true};

    //Observe the collection query for acivity
    var handle = Parties.find(query).observeChanges({
        //Runs one time first on all matching documents and sends them to the client
        //also runs each time a document is added
        added: function (id, fields) {
            if(!fields.showLocation) { //User choose to hide field
                delete fields.location; //Remove field from document
            }
            //etc.. add as many more conditional fields here as wanted

            self.added("Parties", id, fields ); //Sends the new document to the client
        },
        //Runs each time a matching document was updated, getting the id and only the changed fields
        changed: function (id, fields) {
            if("showLocation" in fields) { //check if showLocation was updated
                if(!fields.showLocation) {
                    fields.location = undefined; //marks field for deletion on client
                }
                else {
                    //Needed because "fields" only contains the changed fields, so we need to pull the actual value from the DB
                    //You should probably test here that the doc still exist first
                    fields.location = Parties.findOne({_id: id}, {location: 1}).location;
                }
            }
            //etc.. add as many more conditional fields here as wanted

            self.changed("Parties", id, fields ); //Sends the changes to the client
        },
        //Runs each time a document is removed
        removed: function (id) {
            self.removed("Parties", id );
        },
    });
    self.ready(); //Tell the client that all the data was published

    //Runs when the client unsubscribes from this publish
    self.onStop(function () {
        //Stops observing the collection
        //important because otherwise it would continue observing even after unsubscribing
        handle.stop();
    });
});

This solution may be "low level" but it's very flexible and can be adapted to different needs, even complex conditions involving many fields and it's all on the server side so no private data is sent to the client.

A: Three options:

*

*Define a transform function when you create your collection

*Use cursor.map() on the server to run a callback on every document and include/exclude fields based on your requirements. The resulting object is an array instead of a cursor but the client will happily use that.

*Use cursor.fetch() on the server side and then process the resulting array with a forEach()

A: Upon further reflection, your original idea was on the right track but here's a slightly different (and possibly more meteoric) way to think of the problem.
Create a publication for each set and subscribe to them all!
Meteor.publish('partiesWithLocations',function(){
  ... unique logic for this publication
  return Parties.find({showLocation: true}, {fields: fieldsWithLocation});
});

Meteor.publish('partiesWithoutLocations',function(){
  ... unique logic for this publication
  return Parties.find({showLocation: false}, {fields: fieldsWithoutLocation});
});

The nice thing is that even if your logic results in overlapping publications you'll still get the right set of data back in the client.


text:
Q: select2 change ajax url Im working with knockout.js and select2 plugin.
Im trying to change the select2 ajax url based on a value of an observable.
for example if based on some selection i do ajax call to 1 url or another.
Here is a sample code:
<input type="hidden" data-bind="combobox: { optionsText: 'Name', optionsValue: 'ID', optionsCaption: 'Избери...', sourceUrl: partnerUrl }, value: ApplyToSubject" id="ApplyToSubject" name="ApplyToSubject">

This is how the sourceUrl: partnerUrl is retrieved:
self.partnerUrl = ko.computed(function () {
        var value = "";
        if (something)
        {
            value = apiUrls.customer;
        }
        else if (something else)
        {
            value = apiUrls.vendor;
        }
        else if(or another thing)
        {
            value = apiUrls.employee;
        }
        return value;
    });

I work with custom binding.
Here is the code for it:
// documentation http://ivaynberg.github.io/select2/
ko.bindingHandlers.combobox = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor();
        var optionsText = ko.utils.unwrapObservable(obj.optionsText);
        var optionsValue = ko.utils.unwrapObservable(obj.optionsValue);
        var sourceUrl = ko.utils.unwrapObservable(obj.sourceUrl);
        var selectedID = ko.utils.unwrapObservable(allBindings.value);
        var model = obj.model;
        var unwrapped = ko.utils.unwrapObservable(obj.model);

        $(element).select2({
            minimumInputLength: 3,
            formatResult: function formatResult(result) {
                return result.text;
            },
            data: function (model) {
                return { id: unwrapped[optionsValue](), text: unwrapped[optionsText](), data: unwrapped }
            },
            initSelection: function (element, callback) {
                if (unwrapped && selectedID !== "") {
                    callback({ id: unwrapped[optionsValue](), text: unwrapped[optionsText](), data: unwrapped });
                }
            },
            ajax: {
                quietMillis: 500,
                url: subdirUrl + sourceUrl,
                dataType: 'json',
                data: function (search, page) {
                    return {
                        page: page,
                        search: search
                    };
                },
                results: function (data) {
                    var result = [];
                    $.each(data.list, function (key, value) {
                        result.push({ id: value[optionsValue], text: value[optionsText], data: value });
                    });
                    var more = data.paging.currentPage < data.paging.pageCount;
                    return { results: result, more: more };
                }
            }
        });
        $(element).on('select2-selected', function (eventData) {
            if (eventData.choice) {
                // item selected
                var selectedItem = eventData.choice.data;
                var selectedId = eventData.choice.id;
                model(selectedItem);
            }
            else {
                model(undefined);
            }
        });

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor();
        var selectedID = ko.utils.unwrapObservable(allBindings.value);
        $(element).val(selectedID).trigger('change');
    }
};

It works for url's that dont change, but for urls that need to update, i cant make it work.
(it seems like its keeping the first url that was passed (sourceUrl).

A: I've finally managed to solve this one.
From what i could read from the select2 documentation,
you should pass string or function to ajax url parameter.
So this is what i've done
I've written a function that returns value of the observable (which is the url):
self.returnUrl = function () {
    return self.dynamicUrl();
};

And then i pass that function to my custom binding options:
<input data-bind="combobox: { ... sourceUrl: $data.returnUrl }, value: ApplyToSubject" type="hidden" >

Then the custom binding works the same as in the code in the question, with a small change:
...
ajax: {
     url: sourceUrl <- this is the returnUrl function
...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Objective-C memory management (alloc and autorelease) When you allocate and initialize and object, and then want to return that object, how are you supposed to return it?
I have the following code:
NSXMLDocument* fmdoc = [[NSXMLDocument alloc] initWithContentsOfURL:trackInfoUrl
    options:NSXMLDocumentTidyXML error:&err];
return [fmdoc autorelease];

Is this correct?

A: That is correct. Since you are initializing the object, it is your responsibility to release or autorelease it.
As the retain count on creation is 1 and you want it to not be deleted before the calling method has a chance to use the object, autorelease is the correct message to send.
If you had sent it release, the memory would have been reclaimed immediately. By sending it autorelease the memory will not be reclaimed until the default autorelease pool is drained, which won't happen until after the calling method has had a chance to retain the object if it needs to.


text:
Q: How to get the current cache size for a System.Runtime.Caching.MemoryCache instance? I was trying to find a way to know what percentage of my System.Runtime.Caching.MemoryCache is used. I know how I can configure the limits of the memory cache by using the CacheMemoryLimitMegabytes and PhysicalMemoryLimitPercentage, but my question is how in any moment of my program running I can check what percentage of the defined memory limit is used?
I looked the MS documentation https://learn.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache?view=dotnet-plat-ext-6.0, but couldn't find what I was looking for. There are again two properties that get me the limit in bytes and the % of physical memory that can be used, but nothing for the current state.

A: I couldn't find any good answer anywhere, seems it's not possible with the means of MemoryCache itself, i.e. no exposed api or whatsoever.
However, I found another stackoverflow ticket with some answers which sounds sufficient for further work and investigation.


text:
Q: Text classification with sequences containing two languages? I'm currently trying to make a text classification model which receives a text sequence containing more than one (two in my case) language. I've tried using multilingual language models (e.g., multilingual BERT) which works but the performance isn't as high as I'd like.
I'm curious if there are any other approaches that could be used in order to handle this issue. The problem is that using a typical LM pre-trained on English data results in many [UNK] tokens when encoding the input.
Any tips or pointers are appreciated. Thanks.


text:
Q: Changing only orthographic size and only changing Pixel to units for low resolution sprites I'm wondering, if this is a good practice?
For now highest resolution I will support is 1920x1080 and I will change everything according to this.
Aspect ratios are not problem, I will create extra content.
For lower resolutions I will load sprites dynamically and set appropriate value for Pixel to units's property to fit my highest resolution.
if for 1920x1080 sprites there are 100 Pixels to units, for 480x270 there will be 25 Pixels to units.
This will allow me to have constant units across all resolutions.
The reason I'm thinking this is not good, is because when I manually tried to set the orthgraphicSize to fit other resolutions I got some numbers like these:
Resolution         Orthographic Size
320x240      =>    7.2
800x480      =>    5.763
1280x800     =>    6.002
1920x1080    =>    5.4019

If this is alright, anyone have function to convert these resolutions to orthographicSize or suggest me some method to create this function?

A: I recommend just scaling your items.


text:
Q: Are these monadic expressions equivalent I come across some short piece of monadic code and I have a question not related to the actual subject of the example
ap :: (Monad m) => m (a -> b) -> m a -> m b
ap mf mx = do
        f <- mf
        x <- mx
        return (f x)

staying purely symbolic without knowing at all the context or what the code "does", is the above equivalent to
ap :: (Monad m) => m (a -> b) -> m a -> m b
ap mf mx = do
        x <- mx
        f <- mf
        return (f x)

When I had first seen the example code I had wondered if there was a reason wether the author of this code has chosen the order f <- mf, x <-mx over x <- mx, f <- mf consciously because the order does make a difference or entirely arbitrarily.
Best regards
Günther

A: A simple example where they aren't the same (in that they have different side effects):
mf :: IO (Int -> Int)
mf = do
    putStr "Hello, "
    return (+1)

mx :: IO Int
mx = do
    putStr "world"
    return 1

ap1 = Control.Monad.ap
ap2 mf mx = do
    x <- mx
    f <- mf
    return (f x)

And to test it out
> void $ ap1 mf mx
Hello, world
> void $ ap2 mf mx
worldHello,

These are obviously quite different results even though the actual result of the computation is the same in both cases, i.e. 2.

A: No, they are not equivalent. Desugared, they are
mf >>= (\f -> mx >>= (\x -> return (f x)))
mx >>= (\x -> mf >>= (\f -> return (f x)))

So the bind operation is applied to mf first, mx second in the first definition and the other way around in the second. Bind is not commutative, or at least it does not need to be (it's not required by the monad laws). A counterexample that doesn't involve IO is mf = [(+1), (+2)], mx = [1, 5].

A: As others have pointed out, IO is a simple counterexample. The list monad is not commutative, also.
Prelude> do f<-[succ,pred] ; x<-[10,20] ; return (f x)
[11,21,9,19]
Prelude> do x<-[10,20] ; f<-[succ,pred] ; return (f x)
[11,9,21,19]

Let's build a little list of commutative monads.
Commutative:

*

*Identity

*Reader / (->) a

*Maybe

*Cont (I guess?)

*[] (if you disregard order)

*Random (at least morally)

*UniqueSupply (at least morally)

Non commutative:

*

*Writer

*State

*IO / ST

*STM

*[] (if order matters)

*Either

*Random (formally)

*UniqueSupply (formally)

A: This question actually has answers at two levels:

*

*Are the two expressions equivalent from the point of view of the monad laws.

*Are the two expressions equivalent from the point of view of a specific monad.

The thing to understand is this: any type that instantiates Monad is required to obey the monad laws, which demand that certain expressions be equivalent (e.g., (a >> b) >> c == a >> (b >> c)).  But the monad laws do not forbid individual monads from having additional equivalences.
The monad laws in and of themselves do not require your two functions to be equivalent; therefore:

*

*There are some specific monads where your two functions are equivalent, and others where they are not.

*If you're writing code that's supposed to work for any arbitrary monad, you may not assume the equivalence.

On the other hand, several monads do make your functions equivalent; for example, Maybe and Reader do.  A monad that obeys that equivalence is called a commutative monad—one where the order of effects does not matter.


text:
Q: Issue in building IONIC 3 Application Every time I try to build the ionic app using the ionic cloud server it always fails , like in this image :

here's my system info
global packages:

@ionic/cli-utils : 1.5.0
Cordova CLI      : 7.0.1
Ionic CLI        : 3.5.0

local packages:
@ionic/app-scripts              : 2.0.2
@ionic/cli-plugin-cordova       : 1.4.1
@ionic/cli-plugin-ionic-angular : 1.3.2
Cordova Platforms               : android 6.2.3 ios 4.4.0
Ionic Framework                 : ionic-angular 3.5.3

System:
Node       : v6.10.0
OS         : Windows 7
Xcode      : not installed
ios-deploy : not installed
ios-sim    : not installed
npm        : 5.0.3

after trying more and more , it push this error :

I tried to build android locally - it also push this error :
I want to build it anyway - locally or on the cloud - anyway !!


text:
Q: Can't resolve the reference 'CoreLocation.CLAuthorizationStatus CoreLocation.CLLocationManager::get_AuthorizationStatus() XAMARIN I am trying to release my application so I can distribute, however when I try to build my application I get this error message.
Can't resolve the reference 'CoreLocation.CLAuthorizationStatus CoreLocation.CLLocationManager::get_AuthorizationStatus()', referenced from the method 'System.Void Xamarin.Essentials.Permissions/LocationWhenInUse/ManagerDelegate::DidChangeAuthorization(CoreLocation.CLLocationManager)' in 'Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065'. (MT2101)
Everything works fine when I am in debug mode. I can test on my phone and the emulator but when I think I am good to release I get hit with the error above. I read in the docs, looks like this happens when someone is trying to request access to the location information. However the only thing I can think I am requesting is the current UTC time and dateTime.Now for local time which I don't think has anything to do with the location of the device/user.
That is the only major thing I have changed from my last release, that and I updated some nugget packages. I had issues when I tried to release last time and someone on here was able to help me figure it out, it was a nugget package creating a conflict with another one. I want to think it is my Xamarin.Essentials nugget but I'm not sure. Has anyone else seen this? I saw some people requested help from Xamarin forums but the solution they explained I did not find helpful.
they said to do the following.

Updatring
pool: vmImage: 'macOS-latest'

and removing

- script: sudo $AGENT_HOMEDIRECTORY/scripts/select-xamarin-sdk.sh 6_8_0

A: I found the same issue in this thread:
And this should be fixed in #1606
The solution is using the latest Xamarin.Essentials/1.6.1-preview1.
If you can' switch to the preview, then you will have to install the latest version of Xamarin.iOS on the agents.


text:
Q: How do you save an object to a fooSettings.settings file in Visual Studio? Can you save an object to a settings.settings file in Visual Studio?  If so how?  I think you can make your object serializable and it should persist, but I'm not sure if I'm doing it right i.e. when I try to get the object back it is always null.
Here is the code:
    [Serializable()]
    [XmlRoot(ElementName = "LayerTCA", IsNullable = false, Namespace = "http://somesite.com")]
    public class LayerTCA
    {
        //This is a COM object so I don't want to serialize this.
        IFeatureClass featureClass;

        string fullName;
        string basicName;

        public LayerTCA()
        {

        }

        public LayerTCA(IFeatureClass featureClass)
        {
            FeatureClass = featureClass;
        }

        public IFeatureClass FeatureClass
        {
            get { return featureClass; }
            set
            {
                featureClass = value;
                fullName = featureClass.AliasName;
                basicName = StringHelper.StringAfterLastFullStop(fullName);
            }
        }

        [XmlAttribute(AttributeName = "BasicName")]
        public string BasicName
        {
            get { return basicName; }
            set { basicName = value; }
        }

        [XmlAttribute(AttributeName = "FullName")]
        public string FullName
        {
            get { return fullName; }
            set { fullName = value; }
        }

        public override string ToString()
        {
            return FullName;
        }

    }

A: I'd use a member variable that is an IFeatureClassName.  The constructor would accept an IFeatureclass, then cast the featureclass to IDataset and set the member variable to  IDataset.FullName.  This will be an IName.  All IName objects are persistable via IPersistStream.  While not directly serializable to xml, an IPersistStream object can be written to a byte[] (via MemoryBlobStream).  Can't remember if byte[] can be exposed via XmlAttribute, probably should use base64.  Might also have an Open method would simply call IName.Open on the contained member featureclassname variable, returning an IFeatureclass.
Update: Here's some code that might help converting a featureclassname to and from a string.
public static void TestIt(IFeatureClass fc)
{
    string guidplusbase64Name = GetFullName((IDataset)fc);
    Debug.Print(guidplusbase64Name);
    IFeatureClass fc2 = OpenDataset(guidplusbase64Name) as IFeatureClass;
    Debug.Print(fc2.AliasName);
}

public static string GetFullName(IDataset ds)
{
    IPersistStream ps = ds.FullName as IPersistStream;
    Guid g;
    ps.GetClassID(out g);
    IMemoryBlobStream mbs = new MemoryBlobStreamClass();
    ps.Save(mbs,0);
    object bytes;
    ((IMemoryBlobStreamVariant)mbs).ExportToVariant(out bytes);
    return String.Format("{0};{1}",g,Convert.ToBase64String((byte[])bytes));
}

public static IDataset OpenDataset(string guidplusbase64Name)
{
    int idx = guidplusbase64Name.IndexOf(";");
    string base64Name = guidplusbase64Name.Substring(idx+1);
    string guidString = guidplusbase64Name.Substring(0, idx);

    byte[] bytes = Convert.FromBase64String(base64Name);
    IMemoryBlobStream mbs = new MemoryBlobStreamClass();
    ((IMemoryBlobStreamVariant)mbs).ImportFromVariant(bytes);
    Type t = Type.GetTypeFromCLSID(new Guid(guidString));
    IName n = Activator.CreateInstance(t) as IName;
    ((IPersistStream)n).Load(mbs);
    IDataset ds = n.Open() as IDataset;
    return ds;
}

(updated to work with any IDataset, not just featureclasses)
(update2: concatenating the clsid allows it to work with any dataset, previous version was hardwired for featureclassname)
Don't ask me why ESRI hasn't gotten around to implementing IName.NameString.

The NameString property is reserved
  for future use. When implemented, it
  will return a string representation of
  the locational component of the name
  object that may be persisted by
  applications.


text:
Q: how pass data on prepareForSegue function differently? swift 5 Hi everyOne actually I want to add Data of the cell in tableView that when I click on it , data should pass on showOfferController(another view controller) but I dont why my data is nil when passed on showOfferController:
this is my prepareForSegue function :
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "cellToShow" {

               let prePag = segue.destination as! ShowOfferController
            //print("title : \(title)")
            if WelcomeJson.CodingKeys.title.rawValue == titleItem {
                prePag.celanderItem = WelcomeJson.CodingKeys.dateOfExpire.rawValue
                prePag.itemImage[0] = imageString
                prePag.itemAddress = WelcomeJson.CodingKeys.address.rawValue
                prePag.itemOffer = WelcomeJson.CodingKeys.offer.rawValue
                prePag.itemDefine = WelcomeJson.CodingKeys.about.rawValue
           }

       }
   }

And also this is my DidSelectRow TableView function :
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    performSegue(withIdentifier: "cellToShow", sender: nil)

}

this is my ShowOfferController on main.storyBoard and also my viewController or VC1 that tabelViewCell point to ShowOfferController:

And here my ShowOfferController.swift code :
class ShowOfferController: UIViewController, UIScrollViewDelegate {

@IBOutlet weak var offerScroll: UIScrollView!

@IBOutlet weak var offerPageController: UIPageControl!

@IBOutlet weak var getLabel: UILabel!

@IBOutlet weak var percentLbl: UILabel!
@IBOutlet weak var calendar: UILabel!
@IBOutlet weak var address: UILabel!
let locations = NSTextAttachment()
let calendars = NSTextAttachment()
let precents = NSTextAttachment()
var itemAddress : String = ""
var itemOffer : String = ""
var celanderItem : String = ""
var itemImage : [String] = []
var itemDefine : String = ""

var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)

override func viewDidLoad() {
    super.viewDidLoad()
   print("item of images is : \(itemImage)")
    // Do any additional setup after loading the view.

    offerPageController.numberOfPages = itemImage.count

    setupImages()
    offerScroll.delegate = self
    getLabel.text = itemDefine
    locations.image = UIImage(systemName: "location.fill")
    let locationVaAdress = NSMutableAttributedString(string: ". ")
    locationVaAdress.append(NSAttributedString(attachment: locations))
    locationVaAdress.append(NSAttributedString(string: "   \(itemAddress)"))
    address.attributedText = locationVaAdress
    calendars.image = UIImage(systemName: "calendar")
    let calendarss = NSMutableAttributedString(string: ". ")
    calendarss.append(NSAttributedString(attachment: calendars))
    calendarss.append(NSAttributedString(string: "   \(celanderItem)"))
    calendar.attributedText = calendarss
    precents.image = UIImage(systemName: "percent")
    let percentAndDarsad = NSMutableAttributedString(string: ". ")
    percentAndDarsad.append(NSAttributedString(attachment: precents))
    percentAndDarsad.append(NSAttributedString(string: "   \(itemOffer)"))
    percentLbl.attributedText = percentAndDarsad

}

func setupImages() {

    for index in 0..<itemImage.count {
        // 1.
        frame.origin.x = offerScroll.frame.size.width * CGFloat(index)
        frame.size = offerScroll.frame.size

            let correctScope = itemImage[index].addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
            let unoptionalScope = correctScope!
            let imgUrl = URL(string: "http://5.63.13.16:8080/\(unoptionalScope)")!
            if let data = try? Data(contentsOf: imgUrl) {
                let imgOffer = UIImageView(frame: frame)
                imgOffer.image = UIImage(data: data)
                self.offerScroll.addSubview(imgOffer)
            }

        offerScroll.contentSize = CGSize(width: (offerScroll.frame.size.width * CGFloat(itemImage.count)), height: offerScroll.frame.size.height)
           offerScroll.delegate = self
    }

}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = offerScroll.contentOffset.x / offerScroll.frame.size.width
    offerPageController.currentPage = Int(pageNumber)
}

so what's your idea ?

A: You should make (drag) the segue from on top of the table view controller in the storyboard instead of from the row


text:
Q: How do I install Ubuntu in VMware? I am using Windows 8 and want to install Ubuntu in virtual environment.
How do I install Ubuntu in VMware?

A: To install Ubuntu in VMware:

*

*Download VMware from here and Ubuntu from here.

*They have some different version of Workstations. Pick one of each which fits for your computer.

*Double click on the VMware software application and run it.

*Click Next to install.

*Keep pressing Next until you see finishand then click finish.

*After that, double click on the Icon which is named VMware Workstation is located on the desktop. Clicking on File --> New --> Virtual Machine…  then choose Typical --> Next.

*If you have software in DVD which contained software that you want to create, choose Install disc. Otherwise, Choosing the Installer Disc image file (ISO) software application with extension ISO.

*Keep pressing "Next" to continue.

*Setting maximum disk size (GB) as 8 and choose the option "Store virtual disk as a single file", then hit "Next"

*Enter username and password in Ubuntu.

*Keep pressing "Next" until you see finish then hit Finish

*It will automatically reboot , next, it will run an Ubuntu application as well (the one input "Ubuntu.ISO" above step).

*The installing screen will appear and run as the picture.

*After finish running the installation, restart now

Source


text:
Q: How to write tests for deep links in Android? I would like to write tests for Android app with deep link cases using UI testing framework (Espresso) - launch app using only ACTION_VIEW intent and check all views on opened screen.
But looks like Espresso (even espresso-intents) doesn't have this functionality, and require to define Activity class.
I tried this way, but it doesn't work properly, because launched app twice - standard launch using AppLauncherActivity (required by Espresso) and launch via deep link.
@RunWith(AndroidJUnit4.class)
public class DeeplinkAppLauncherTest {

    @Rule
    public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<>(AppLauncherActivity.class);

    @Test
    public void testDeeplinkAfterScollDownAndBackUp() {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("myapp://search/777"));
        activityRule.launchActivity(intent);

        onView(withId(R.id.search_panel)).check(matches(isDisplayed()));
    }

}

I would like to launch testing app using only deep link without standard launch.
Do you know, how to do it?

A: I found one option - just added deep link opening parameters for existed intent and use standard activity launch:
@Rule
public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<AppLauncherActivity>(AppLauncherActivity.class){
    @Override protected Intent getActivityIntent() {
        Intent intent = super.getActivityIntent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("myapp://search/777"));
        return intent;
    }
};

A: @Rule
public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<>(AppLauncherActivity.class, false, false);

There are multiple constructors for creating an ActivityTestRule. The third one is launchActivity. Set it to false as shown above because you manually start that activity afterwards with activityRule.launchActivity(intent). This should prevent it from starting twice

A: Accepted answer is helpful, but nowadays the ActivityTestRule class has been deprecated.
We can use ActivityScenario instead.
Here is a Kotlin example:
class MyDeepLinkTest {

    private lateinit var scenario: ActivityScenario<LoadingActivity>

    @Before
    fun setUp() {
        Intents.init()
    }

    @After
    fun tearDown() {
        Intents.release()
        scenario.close()
    }

    @Test
    fun myTest() {
        val intent = Intent(ApplicationProvider.getApplicationContext(), LoadingActivity::class.java)
            .putExtra("example_extra1", "Value 1")
            .putExtra("example_extra2", 777)

        scenario = ActivityScenario.launch(intent)

        // Test code goes here (e.g. intent causes to start MainActivity)
        intended(hasComponent(MainActivity::class.java.name))
    }

}

I also found this blog post with additional examples.


text:
Q: How to solve " AttributeError: 'PathCollection' object has no property 'pred' " error? I am working on k-means clustering analysis and trying to plot the clusters. However the code I have encounters the error:

AttributeError: 'PathCollection' object has no property 'pred'

My code:
#scale features
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
scaled_df = scaler.fit_transform(df)

# fitting multiple k-means algorithms and storing the values in an empty list

SSE = []
for cluster in range(1,40):
    kmeans = KMeans(n_jobs = -1, n_clusters = cluster, init='k-means++')
    kmeans.fit(scaled_df)
    SSE.append(kmeans.inertia_)

# converting the results into a dataframe and plotting them
frame = pd.DataFrame({'Cluster':range(1,40), 'SSE':SSE})
plt.figure(figsize=(12,6))
plt.plot(frame['Cluster'], frame['SSE'], marker='o')
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')

kmeans = KMeans(n_clusters=16, init ='k-means++', max_iter=300, n_init=10,random_state=0 )
pred = kmeans.fit_predict(scaled_df)

#Plot All K-Means Clusters
#Getting unique labels
u_labels = np.unique(pred)

#plotting the results:
for i in u_labels:
    plt.scatter(scaled_df[pred == i , 0], scaled_df[pred == i , 1], pred = i)
plt.legend()
plt.show()

I have 18 attributes to be clustered and would also appreciate any help in getting the attributes within each cluster. Thanks!
I have tried to plot the first 5 clusters individually:
plt.scatter(scaled_df_uk19[pred==0, 0], scaled_df_uk19[pred==0, 1], s=100, c='red', label ='Cluster 1')
plt.scatter(scaled_df_uk19[pred==1, 0], scaled_df_uk19[pred==1, 1], s=100, c='blue', label ='Cluster 2')
plt.scatter(scaled_df_uk19[pred==2, 0], scaled_df_uk19[pred==2, 1], s=100, c='green', label ='Cluster 3')
plt.scatter(scaled_df_uk19[pred==3, 0], scaled_df_uk19[pred==3, 1], s=100, c='cyan', label ='Cluster 4')
plt.scatter(scaled_df_uk19[pred==4, 0], scaled_df_uk19[pred==4, 1], s=100, c='magenta', label ='Cluster 5')

It results in the following which I suppose is abit odd?

Edit: When I removed the pred=i argument within the scatter function, the plot shows:
It does not look like the usual cluster plots. Can anyone kindly explain why this may happen? Thank you!


text:
Q: Wordpress Plugin Upgrade Hook Function I'm developing new version of my wordpress plugin (http://wordpress.org/extend/plugins/facebook-send-like-button/) .
New options (add_option()) coming with new version. But i can't register this new options automatically.
For example there is fgb_single option in new version.
Where should i put add_option('fgb_single', 'on');  code in my plugin's file?

A: The Options API is using the global $wpdb, make sure you have that declared before using any function like add_option or get_option.Also acording to the WordPress Codex, you will see no changes when you use add_option($option, $value, $deprecated, $autoload) if you already have a value for that option:

Note: add_option uses get_option to determine whether the option already exists, and since get_option returns false as the default value, if you set an option to false in the database (e.g. via update_option($option_name, false)), then a subsequent call to add_option will change the value, because it will seem to add_option that the option does not exist.

You can use the Options API anywhere in your plugin as log as you load $wpdb.Also I'd recommend using update_option instead of add_option as it is able to create new options but won't return false in case an option already exists, it will simply overwrite it.


text:
Q: asp_sessionid cookie default path to be made application specific I have a website in which I had to make the default path which is usually visible as "/" for asp.netSessionId cookie and .ASPXAUTH cookie to application specific for security reasons and after lot of RND i was able to do that but I have a confusion and a problem now described as follows:

*

*The confusion is: In order to make the cookie path application specific I wrote a method say "setcookiepath" to do so and called that method from global file's session_start but that did not work that as the path either used to get reset sometime after certain clicks or more than 1 cookie got generated one with default path and other with app specific path. So I went ahead and called my method 1 by 1 from other events in global.asax file and finally ended up calling from each one, still it worked only sometimes. Then I abandoned session in my Session_Start only the first time when Application is called by using a flag that i set in application_start and reset after session abandons in session_start. This time it worked perfectly fine. Now, i tried removing unneccesary calls from setcookiepath and tested this time it is working with single method call in any of the events and even after removing the logic of abandoning session it is working now.I am confused what is the right approach?

*The problem is: Although now my code is working for the website but there is an Admin module which is called from a sub folder within that website. For this Admin sub module my code is not working i.e. the problem I am facing is. I am able to login to Admin module the first time I hit the url and 2 cookies get generated for ASP.NetSessionId one with default path and the other has application specific path. This works as long as my browser is open, when I close the browser and try to relogin, now my previous session cookies are removed and I keep getting redirected to login page because the user session gets invalidated in between somewhere when I am redirecting from login page to home page for Admin module, this issue is not occuring in main website module. Also, after removing the path reset logic from global.asax.cs file admin module session works fine between login and home page.
Please help.
Code for path set is :
public void setCookieApp()
        {
            if (HttpContext.Current != null)
            {
                /// only apply session cookie persistence to requests requiring session information
                if (HttpContext.Current.Handler is IRequiresSessionState || HttpContext.Current.Handler is IReadOnlySessionState)
                {
                    SessionStateSection sessionState = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
                    string cookieName = sessionState != null && !string.IsNullOrEmpty(sessionState.CookieName) ? sessionState.CookieName : "ASP.NET_SessionId";
                    string cookieName1 = sessionState != null && !string.IsNullOrEmpty(sessionState.CookieName) ? sessionState.CookieName : ".ASPXAUTH";
                    //System.TimeSpan timeout = sessionState != null ? sessionState.Timeout : TimeSpan.FromMinutes(20);
                    /// Ensure ASP.NET Session Cookies are accessible throughout the subdomains.
                    if (HttpContext.Current.Request.Cookies[cookieName] != null)
                    {
                        //Response.Cookies[cookieName].Value = Session.SessionID;
                        HttpContext.Current.Response.Cookies[cookieName].Path = HttpContext.Current.Request.ApplicationPath;
                        //Response.Cookies[cookieName].Expires = DateTime.Now.Add(timeout);
                    }
                    if (HttpContext.Current.Request.Cookies[cookieName1] != null)
                    {
                        //Response.Cookies[cookieName].Value = Session.SessionID;
                        HttpContext.Current.Response.Cookies[cookieName1].Path = HttpContext.Current.Request.ApplicationPath;
                        //Response.Cookies[cookieName].Expires = DateTime.Now.Add(timeout);
                    }
                }

                foreach (string k in HttpContext.Current.Request.Cookies.AllKeys)
                {
                    if (k.ToString().Contains("ASP.NET_SessionId"))
                    {
                        HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Path = HttpContext.Current.Request.ApplicationPath;
                    }
                    else if (k.ToString().Contains(".ASPXAUTH"))
                    {
                        HttpContext.Current.Response.Cookies[".ASPXAUTH"].Path = HttpContext.Current.Request.ApplicationPath;
                    }
                }
            }
        }


text:
Q: Why does windbg title stack with childebp and args to child I know this may sound nit-picky, but I want to know if there is a reason for these semantics.
Child to me means those are the things it will pass to the function it is about to call, however if you break on function name, then a given record will already exist and will not change.  That record shows what that function received from its parent.
Lets say that I break on wmain and step in a few lines.
windbg will report:
 # ChildEBP RetAddr  Args to Child
00 005dfeb8 009e138b 00000001 00ac9bc0 00acfac8 ASMTests!wmain+0x19

Now those values wont change.
When I enter the next function DoBuf0, they don't change so they are not actually the args to the child, They are the args received from the parent.
Eg:
My wmain passes "buf0" as second argument to DoBuf0
 # ChildEBP RetAddr  Args to Child
00 005dfe0c 009e1131 005dfe34 009e218c 005dfe74 ASMTests!DoBuf0
01 005dfeb8 009e138b 00000001 00ac9bc0 00acfac8 ASMTests!wmain+0x91

0:000:x86> da 009e218c
009e218c  "buf0"

They are the args the parent (wmain) passed to the child (DoBuf0), But they are NOT displayed on the Parents line, they are displayed on the childs.  Wouldn't it make more sense to just call them Args from parent?  In the case above args to Child implicates that DoBuf0 will be passing them to ITs child.
Thanks

A:
Child to me means those are the things it will pass to the function it
  is about to call

How could the window show things that have not happened yet? Do you expect some sort of speculative execution simulation? A "child" is something that has been called, and the call has left evidence data on the stack.
Quote from the WinDbg help

Raw args displays the first three parameters that are passed to the
  function. On an x86-based processor, this display includes the first
  three parameters that are passed to the function ("Args to Child").
Addrs displays various frame-related addresses. On an x86-based
  processor, this display includes the base pointer for the stack frame
  ("ChildEBP") and the return address ("RetAddr").


text:
Q: What is the fastest growing total computable function you can describe in a few lines? What is the fastest growing total computable function you can describe in a few lines?
Well, not necessarily the fastest - I just would like to know how far an ingenious mathematician can go using only a few lines, and what systematic approaches exist for this purpose.
How farther you can go if we the restriction of computability is lifted?

A: After having written quite a few programs related to large numbers and recursion over on ppcg.SE, I came up with this really interesting notation which I now call Simply's Ordinal Array Program (SOAP), and I'll explain a tweaked version that's nicer on the eyes than what my actual program does.
Before we begin, we have 2 different types of things we'll deal with.

*

*Integers : $\dots,-2,-1,0,1,2,\dots$

*Ordered sets : $\{1,2,3\}$ or $\{x,y\}$ or $\{-2\}$
Next, we have our ordinal array function:
$$\small f(a,n,b,q)=\begin{cases}q,&a\text{ is a negative integer}\\a-1,&a\text{ is a non-negative integer}\\x,&a=\{x,y,z\},\text{ where $y$ or $z$ are zero}\\\{\{x,y,f(z,n,b,q)\},f(y,n,b,q),x\},&a=\{x,y,z\},\text{ but $y$ and $z$ aren't zero}\\n,&a=\{x,y\},\text{ where $x=0$}\\\{\{f(x,n,x,n),0\},n,n\},&a=\{x,y\},\text{ where $x\ne0$ and $y=0$}\\\{t,n,\{f(y,n,b,t)\}\},&a=\{x,y\},\text{ where $x,y\ne0$ and }t=\{f(x,n,x,n),y\}\\1,&a=\{x\},n=0\\\{f(b,n-1,b,n-1),x\},&a=\{x\}\end{cases}$$
And finally we have our much much simpler ordinal counting function:
$$g(a,n)=\begin{cases}n,&a=0\\g(f(a,n,a,n),n+1),&a\ne0\end{cases}$$
Perhaps a bit of a stretch of what you might call a few lines, but this notation has been well crafted to give you some very very very big numbers, and is strong enough to rival even Deedlit's answer. In fact, $g(\{\{-1,3,1\}\},3n)$ grows approximately as fast as the largest number you can write in Deedlit's $f$ notation using at most $n$ symbols.
Some basic analysis:
If $a$ is an integer, then $g(a,n)=g(a-1,n+1)=\dots=n+a$.
If $a=\{0,0\}$, then $g(a,n)=g(n,n+1)=2n+1$.
If $a=\{\{0,0\},0,k\}$, then $g(a,n)=g(\{0,0\},n+1)=2n+3$.
If $a=\{\{0,0\},1,k\}$, then $g(a,n)=g(\{\{0,0\},1,k-1\},n+2)=\dots=g(\{0,0\},n+2k+1)=2n+4k+3$.
If $a=\{\{0,0\},2,k\}$, then $g(a,n)\approx n\times2^k$.
Okay, not very fast growing so far, but suddenly,
If $a=\{\{0,0\},3,k\}$, then $g(a,n)\approx n\uparrow^kn\approx A(n,n)$, in terms of Knuth's up-arrow notation and the Ackermann function. This is much faster than before.
If $a=\{\{0,0\},3,\{\{0,0\},0,0\}\}$, then $g(a,n)\approx g_n$, with $g_{64}$ being the famous Graham's number.
If $a=\{\{0,0\},4,k\}$, then $g(a,n)\approx f_{\omega^k}(n)$ in the fast growing hierarchy, which is decently fast.
If $a=\{\{0,0\},5,\{0,0\}\}$, then $g(a,n)\approx f_{\varepsilon_0}(2n)$. This is large enough for Peano arithmetic to break down.
If $a=\{\{\{0\},3,\{0,0\}\},2,\{0,0\}\}$, then $g(a,n)\approx TREE(n)$, the famous TREE sequence.
From there, it just keeps going up very rapidly, and
$$g(\{x_n\},n)\approx f_{\psi(\chi(\Omega_{M+1}^{\Omega_{M+1}}))}(n)$$
where
$$x_n=\begin{cases}1,&n=0\\\{x_{n-1},x_{n-1},x_{n-1}\},&n>0\end{cases}$$
which is about as fast as my notation can grow.

A:
How farther you can go if we the restriction of computability is lifted?
$
\def\nn{\mathbb{N}}
$

You can construct extremely fast-growing functions from $\nn$ to $\nn$. Clearly, you can enumerate the computable functions (since there are countably many) and diagonalize against those that halt, giving you a function that grows faster (eventually) than every computable function. So it dwarfs everything in the FGH (fast-growing hierarchy), and you can only begin to appreciate how fast that is when you appreciate how fast the functions in the FGH grow!
But there's much much more we can do, and in only a few lines:

Pick some infinite countable ordinal $α$ and some bijection $i$ from finite strings to $α$. Define a hyper-program as a program that can call an oracle $H$, where $H(k,x)$ is $1$ iff $x$ is a valid hyper-program that when run on empty input only calls $H(j,\bullet)$ for string $j$ such that $i(j) < i(k)$, and halts, and $H(k,x)$ is $0$ otherwise. Identifying finite strings with natural numbers, let $F(n)$ be $1$ plus the sum of the outputs of all the hyper-programs from $0$ to $n$ on input $n$ (excluding those that do not halt).

To understand how fast $F$ grows, we have to look first at the growth rate of the hyper-programs. A hyper-program that does not call $H$ at all are ordinary programs (computably equivalent to Turing machines). We shall say that a hyper-program is at level $β$ iff on all inputs it only calls $H(k,\bullet)$ for $i(k)<β$. Ordinary programs are hence at level $0$. $H(i^{-1}(0),\bullet)$ is the halting oracle, also known as the first Turing jump. The Busy Beaver function $BB$ can be computed using calls to $H(i^{-1}(0),\bullet)$, so it is at level $1$. But programs which can call $BB$ as an oracle also cannot solve their own halting problem, yet $H(i^{-1}(1),\bullet)$ (the second Turing jump) can! So by the same diagonalization as for $BB$, there is a hyper-program that calls only $H(i^{-1}(1),\bullet)$ and computes a function that outgrows every function computed by programs that calls only $BB$.
Can you imagine how fast that is? Every program that you can design using $BB$ that always halts on every input, including iterating $BB$ on the input as many times as given by the output of some computable function in the FGH, will lose hands down to a simple hyper-program at level $2$... In general, there is a hyper-program at level $β$ that grows faster than every total hyper-program at any level lower than $β$. Now can you imagine level $3,4,5,\cdots$?
Note that we have to pick $α,i$ right from the beginning, and the hyper-programs we get will reach all levels below $α$. For example we could have picked $α$ to be the Church-Kleene ordinal $ω_1^{CK}$. If we want to reach higher, simply pick a larger $α$ to start with! But there is no largest countable ordinal, so there is no absolute winner.
Also, for each natural number $n$, if the $n$-th hyper-program halts on input $n$ and outputs $x$ then $F(n) > x$ by construction. Therefore $F$ grows faster than every total hyper-program! But notice that we could have simply started with $α+1$ and in the new hierarchy $F$ would simply be at level $α$. So it all boils down to the length of $α$.
Finally, if one has no qualms with programs over an uncountable alphabet, one can do exactly the same construction but with uncountable $α$.

A: An example which grows faster than any computable function (for obvious reasons): Let BB(n) denote the time it takes for the longest halting Turing machine with n symbols to halt.
edit perhaps "obvious" was an exaggeration: Was BB computable then you could write a program to check whether any input program halts or not by seeing if it stops before BB(length(program)) steps, but this is not computable by Turing's argument so BB is not computable. Also let f be any computable function, then you can see that BB grows faster than f, since there is a program that takes f steps to halt.

A: It is pretty simple to define one:
BIGCOQ(n) = For any valid, well-typed Coq program with a term x:Nat and its length not longer than n, the maximum value of x.
This function is totally computable, and it will growth faster than every other function that could be written in Coq code...

A: Using ordinals, we can construct some pretty massive things. Much in the same manner that Deedlit has answered, we may then construct the following fast growing function based on finitely many $\text{Ord}^m\mapsto\text{Ord}$ functions:
$$C(n)=\begin{cases}\{0,1,2\},&n=0\\=C(n-1)\cup\{f_1(X_1),f_2(X_2),\dots,f_k(X_k):X_i\in C(n-1)^{m_i}\},&n>0\end{cases}$$
where $A^m$ is the set of $m$-tuples who's elements are elements of $A$. One may then define
$$H(\alpha,n)=\begin{cases}n,&\alpha=0\\H(\max(C(n)\cap\alpha),2^n),&\alpha\ne0\end{cases}$$
which produces an infinite hierarchy of fast growing functions satisfying some nice properties, like:
$$\alpha<\beta\implies H(\alpha,n)\le H(\beta,n)\\n<k\implies H(\alpha,n)<H(\alpha,k)$$
If the provided functions are computable, then you have yourself some very fast growing computable functions. Even something as simple as $f_1(\alpha,\beta)=\alpha+\beta$ and $f_2(\alpha)=\omega^\alpha$ will produce a function who's growth rate is comparable to the Goodstein sequence.
Using this ordinal collapsing function, we get the following:
$H(0,n)=n$
$H(1,n)=2^n$
$H(2,n)=2^{2^n}$
$H(3,n)=2^{2^{2^n}}$
$H(\omega,n)\approx2\uparrow\uparrow n$
$H(\omega^2,n)\approx2\uparrow\uparrow\uparrow n$
$H(\omega^k,n)\approx2\uparrow^{k+1}n$
$H(\omega^\omega,n)\approx Ack(n,n)$, the Ackermann function.
$H(\omega^{\omega+1},n)\approx g_n$, where $g_{64}$ is Graham's number.
$H(\psi_0^0(0),n)\approx\mathcal {G}(n)$, the length of the Goodstein sequence starting at $n$.
$H(\psi_0^0(\omega^{\omega^{\Psi(0)+1}+1}),n)\approx{\rm tree}(n),~H(\psi_0^0(\omega^{\omega^{\Psi(0)+1}}+,n)\gtrsim{\rm TREE}(n)$, the tree and weak tree function.
$H(\psi_0^0(\psi_{\Psi(\omega)}^0(0)),n)\approx{\rm scg}(n)$, the subcubic graph numbers.

A: Most fast-growing functions are constructed by a recursive scheme analogous to the
well-known Ackermann function - namely one repeatedly iterates
a function and then diagonalizes. Thus iterating addition
yields multiplication, which iterated yields exponentiation,
which iterated yields tetration, etc. Diagonalizing the resulting
sequence of functions yields a faster-growing Ackermann function
- which itself may be successively iterated, diagonalized, etc. Paul du Bois-Reymond discovered such diagonalization on growth rates of functions ("orders of infinity") in 1875, long before Cantor's better-known rediscovery (1891), employed to show $|2^S| > |S|$.
Proof-theorists use analogous recursive schemes to construct
notation systems for ordinals - which they employ to measure
the strength of logical systems. Functions and numbers notated by such means
(whether finite or infinite) tremendously dwarf those that
occur in most all other branches of mathematics. Thus I highly recommend that you consult the literature on ordinal notation systems.
Below are some expository references on related topics (from an old sci.math post).
[Ruc] Rucker, Rudy. Infinity and The Mind, 1995, 342 pp. Princeton U. Pr.
[Spe] Spencer, Joel.  Large numbers and unprovable theorems,
 Amer. Math. Monthly, Dec 1983, 669-675.
[Smo] Smorynski, Craig  (all three papers are reprinted in [HFR])
 Some rapidly growing functions, Math. Intelligencer, 2 1980, 149-154.
 The Varieties of Arboreal Experience, Math. Intelligencer, 4 1982, 182-188.
 "Big" News from Archimedes to Friedman,  Notices Amer. Math. Soc. 30 1983, 251-256.
[Kol] Kolata, Gina.  Does Godel's theorem matter to mathematics?
 Science 218 11/19/1982, 779-780; reprinted in [HFR]
[Sim] Simpson, Stephen G.  Unprovable theorems and fast-growing functions,
 Contemp. Math. 65 1987, 359-394.
[HFR] Harrington, L.A. et.al. (editors)
 Harvey Friedman's Research on the Foundations of Mathematics,
 Elsevier 1985.

A: For a nice fast-growing function, consider the following:
Given rooted trees $S$ and $T$ whose vertices are labeled from $\{1,2,\cdots,k\}$, define a gap embedding as a label preserving embedding $h$ from $S$ into $T$ that satisfies the following: given $u$, $v$ vertices of $S$ such that $v$ is the child of $u$.  For any vertex $w$ of $T$ that lies in between $h(u)$ and $h(v)$, $label(w) \ge label(h(v))$.
Given this definition, define $ETree(k)$ to be the longest sequence $T_i$ of rooted trees labeled from $\{1,2,\cdots,k\}$ such that $T_i$ has no more than $i$ vertices, and for no $i < j$ is there a gap embedding from $T_i$ into $T_j$.
The above construction is due to Harvey Friedman.  He showed that no such sequence could be infinite (i.e. that rooted labeled trees are well-quasi-ordered under gap embedding), and it follows from Koenig's Tree Lemma that there is a longest such sequence.
The function $ETree(k)$ grows extremely fast.  It grows at the rate of $F_{\psi_{\Omega_1} (\Omega_\omega)} (k)$.  (Look up the fast-growing hierarchy.)
One can also get extremely fast growing functions using ordinal hierarchies. Let $I(a)$ be the $a$'th weakly inacessible cardinal.  Consider the following: (here $a,b,c,d,e$ are ordinals, $\phi$ is the Veblen function, $C_n(a,b)$ are sets of ordinals, $\psi$ and $f$ are functions on ordinals.)
$C_0(a,b) = b \cup {0}$
$C_{n+1}(a,b) = \{c+d, \phi(c,d), \aleph_c, I(c), \psi(e,d), f(e,c,d) | c,d,e \in C_n(a,b), e < a\}$
$C(a,b) = \cup C_n(a,b)$
$f(a,n,b) =$ largest finite ordinal in $C_n(a,b)$
$\psi(a,b) = b$'th ordinal such that $b \notin C(a,b)$
Then, for example, $f(I(I(I(I(0)))),x,x)$ is an extremely fast growing function, much faster than $ETree$.  To help understand this construction, see "Ordinal collapsing function" on wikipedia.  If that is still confusing, look at
http://math.ucr.edu/home/baez/week236.html
for an introduction to ordinals, and
http://groups.google.com/group/sci.math/browse_thread/thread/b4b2769c6359b3e9/5317b10cbf60196
for a description of how ordinals can be used to define large numbers.
EDIT:  Perhaps some more explanation is needed.  $C(a,b)$ is the smallest set of ordinals containing all ordinals less than $b$ and $0$ and closed under the operations listed in the second line.  The definition may appear circular, but it is well-defined by induction on $a$;  given $f(c,n,b)$ and $\psi(c,b)$ for $c < a$, we define $C_n(a,b)$, and given $C_n(a,b)$, we define $f(a,n,b)$ and $\psi(a,b)$.
Some analysis of $f(a,n,b)$:
$f(0,0,b)$ is the largest finite ordinal in $C_0(0,b) = b$, which is $b-1$.
$f(0,1,b)$ is $2(b-1)$ if $b \ge 2$, otherwise it is $\phi(0,0) = 1$.
$f(0,n,b)$ is $2^{b-1}$ if $b \ge 2$, otherwise it is $2^{n-1}$
$f(1,0,b)$ is again $b-1$ if $b \ge 1$, $0$ if $b = 0$
$f(1,1,b)$ is $2^{b-1} (b-1)$ if $b \ge 2$ otherwise it is $1$
$f(1,n,b) > Tower_n (b-1) > 2\uparrow\uparrow n$ for $b \ge 2$
$f(2,n,b) > 2\uparrow\uparrow\uparrow n$ for $b \ge 2$
$f(m,n,b) > 2 \uparrow^{m+1} n$ for $b \ge 2$
$f(\omega,0,b) = b-1$ for $b \ge 2$
$f(\omega,1,b) = f(b-1,b-1,b-1) \ge 2 \uparrow^{b}(b-1)$ for $b \ge 2$
$f(\omega,2,b) = f(f(\omega,1,b),f(\omega,1,b),f(\omega,1,b)) \ge 2 \uparrow^{2 \uparrow^b (b-1)}(2 \uparrow^b (b-1))$
$f(\omega,n,b)$ is the function $f(x,x,x)$ applied $n$ times starting from $b-1$, which is greater than $F_{\omega+1}(n)$ where $F$ is the fast-growing hierarchy.
$F(\omega+1,n,b)$ is the function $f(\omega,x,x)$ applied $n$ times starting from $b-1$, which is greater than $F_{\omega+2}(n)$.
Each time we add $1$ to $a$, we go to a function which iterates the previous one $n$ times;  each time we increase a to a limit ordinal, we diagonalize over previous functions.  So the task becomes defining very large countable ordinals.

A: I do not know whether it is the fastest, but historically the Ackermann function was the first (afaik):
$\qquad  A(m, n) =\begin{cases}n+1 & \mbox{if } m = 0 \\A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0.\end{cases}$
It generalises the idea that $+$, $\cdot$, $\exp$ and so on form a natural series of operators; $A$ excedes them all by controlling the stacking level in the second parameter.
It has been proven that $A$ (or rather $A(n,n)$) is not primitive recursive by showing that it grows faster than any primitive recursive function, including all exponential functions.

A: The fast growing hierarchy (FGH) is a personal favorite of mine because I think it is not only simple compared to things involving trees or the BB function, while still being able to outgrow, say, the Ackermann function.

First, a simple layman's explanation of what FAIL approximately does:
The lowest level is basic addition:
$Fn\#0=n+1=\text{addition}$
The next level is repeated application of the previous level:
$Fn\#1=F(F(F(\dots)\#0)n\#0)\#0=n\underbrace{+1+1+\dots+1}_n=n+n=2n=\text{multiplication}$
$Fn\#2=F(F(F(\dots)\#1)n\#1)\#1=\underbrace{2\cdot2\cdot\ldots\cdot2}_n\cdot n\approx2^n=\text{exponentiation}$
You can imagine this keeps going, and so I'm going to make a table of stuff:
$$\begin{array}{c|c}k&Fn\#k\approx\\\hline0&n+1\\1&2n\\2&2^n\\3&\underbrace{2^{2^{2^{\dots}}}}_n\\4&\text{Oh God help us}\\5&\text{can't really explain this well anymore}\\\vdots&\vdots\end{array}$$
Where each level is just doing the previous level $n$ times...
But... there is a function that grows faster than every function in the above list.  How?  Well, it diagonalizes along the list.  This function is given by...
$Fn\#0\#1$
At $n=1$, it is equivalent to the $k=1$ level with $n=1$ inside.  At $n=2$, it is equivalent to the $k=2$ level with $n=2$ inside.
Eventually, it will catch up to any function in the above list... and then go beyond it.  This is the smallest non-primitive-recursive function in FAIL.
We can then nest the function over itself:
$Fn\#1\#1=F(F(\dots)\#0\#1)\#0\#1$
$Fn\#2\#1=F(F(\dots)\#1\#1)\#1\#1$
And eventually, we get a list.  We then make a function that grows even faster by making it go from one function in the list to the next, so that it will always grow faster than any fixed level:
$Fn\#0\#2=Fn\#n\#1$
And then iterate over this function to get another list, then diagonalize over it, again and again until you come up with this list:
$$\begin{array}{c|c}k&Fn\#0\#k\approx\\\hline0&n+1\\1&Fn\#0\#1\\2&Fn\#0\#2\\3&Fn\#0\#3\\4&Fn\#0\#4\\5&Fn\#0\#5\\\vdots&\vdots\end{array}$$
Note I did not write most of these out explicitly because they are sooo large...
Anyways, we then diagonalize over this to end up with...
$Fn\#0\#0\#1$
And so on with the story.  FAIL actually goes beyond this, extending the notation through @ symbols, and it gets pretty hairy, but to get you thinking, consider the following list:
$$\begin{array}{c|c}k&\text{result}\\\hline1&Fn\#1\\2&Fn\#0\#1\\3&Fn\#0\#0\#1\\\vdots&\vdots\end{array}$$
Have fun diagonalizing this, then iterating it over itself and diagonalizing some more...

The following does, however, require a small bit of comfort level with ordinals, though you needn't have heard of the term before reading this.
FGH is defined by the simple recursive rules:
$f_0(n)=n+1$
$f_{\alpha+1}(n)=\underbrace{f_\alpha(f_\alpha(\dots f_\alpha(n)\dots))}_{n\text{ iterations of }f_\alpha}$
$f_\alpha(n)=f_{\alpha[n]}(n)$
Let's start with some basic examples:
$f_0(5)=5+1=6$
Simple enough.
$f_1(5)=f_0(f_0(f_0(f_0(f_0(5)))))=f_0(f_0(f_0(f_0(6))))=f_0(f_0(f_0(7)))=\dots=10$
Still relatively simple...
$f_3(2)=f_2(f_2(2))=f_2(f_1(f_1(2)))=\dots=2^{11}=2048$
Ok, so if you fill in the $\dots$ part of the previous example, you'll start to notice that it takes quite a while to reach $f_0(n)$ to be able to apply rule one.
You will also notice that in terms of Knuth's up-arrow notation,
$f_k(n)\approx n\uparrow^{k-1}n$
Which so far, isn't too much.  We then, however, reach the next stage, where rule 3 comes into play:
Let us define $\omega[n]=n$.  It thus follows that
$f_\omega(2)=f_{\omega[2]}(2)=f_2(2)$
Relatively small huh?  How about if we try $\omega+1$?
$f_{\omega+1}(2)=f_\omega(f_\omega(2))=f_\omega(f_2(2))=f_\omega(8)=f_8(8)$
And now it got significantly bigger, just at $n=2$.  We then have
$f_{\omega\cdot2}(2)=f_{\omega+\omega}(2)=f_{\omega+2}(2)$
In general,
$\omega\cdot(k+1)[n]=\omega\cdot k+n$
And further,
$\omega^{k+1}[n]=\omega^k\cdot n$
To see how $\omega^3$ is expanded, as an example, see Calculation of $f_{\omega^3}(2)$ in the fast growing hierarchy.
What's worse is we can take this to greater heights:
$$\omega^\omega,\omega^{\omega^{\omega^{\dots}}},\text{and beyond}\dots$$
And the unique part is we can define this to go as high as we want.  It's all about how far you dare to define the ordinals.
A nice series that not only explains this, but explains how to expand higher and higher ordinals.
Extremely large numbers
Simply Beautiful Art's guide to large numbers, the fast growing hierarchy, and ordinal collapsing functions.

A: I'm gonna take another look at this problem.  That is, consider the fast growing total computable function I can describe in a few lines of Ruby code.  It's pretty large.  Let's start with this small appetizer:
def f(a,b)a.times{a*=b<0?a:f(a,b-1)}&&a end

Function alone: https://repl.it/Hvr5/63
Function with inputs: https://repl.it/Hvr5/62
This function grows pretty fast and only requires 43 characters to write (including spaces).  It basically works as follows:
f(a,-1) = a^(2^a)
f(a,b) >/≈ f(f(f(...f(a,b-1),...,b-1),b-1),b-1), with a nestings of f(-,b-1)
In terms of the Ackermann function, f(a,b) ≈ A(b+4,a).  An explicit expansion:
f(2,2) > f(f(2,1),1) > f(f(f(2,0),0),1) > f(f(f(f(2,-1),-1),0),1) = f(f(f(16,-1),0),1) = f(f(2^2^18,0),1) > ...

We can make a slightly larger function:
def f(a,b,c=a)c>0?a.times{a*=f a,b,c-1}&&a:b<0?a:f(a,b-1)end

Function alone: https://repl.it/Hvr5/67
Function with inputs: https://repl.it/Hvr5/66
Now we're at 60 characters (including spaces).  Still pretty small.  It basically works as follows:
f(a,-1,0) = a
f(a,-1,1) = a^(2^a)
f(a,b,c) >/≈ f(f(f(...f(a,b,c-1),...,b,c-1), with a nestings of f(-,b,c-1)
f(a,b,0) = f(a,b-1,a)
So f(a,-1,b+1) ≈ f(a,b) from before, but we then can make much larger numbers.  It quickly catches up to Graham's number, which is approximately f(64,0,1).  Let's look at an expansion:
f(2,0,1) > f(f(2,0,0),0,0) = f(f(2,-1,2),0,0) > f(f(f(2,-1,1),-1,1),0,0) = f(f(16,-1,1),0,0) = f(2^2^18,0,0) = f(2^2^18,-1,2^2^18) ≈ A(2^2^18,2^2^18)

Okay, that wasn't so bad, but you'll quickly find that gets out of hand very fast...
We could try throwing in a few more arguments while we're at it:
def f(a,b=a,c=a,d=a,e=a,g=a,h=a,i=a,j=a,k=a,l=a,m=a,n=a,o=a,p=a,q=a)a.times{a**=q>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n,o,p,q-1):p>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n,o,p-1):o>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n,o-1):n>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n-1):m>0?f(a,b,c,d,e,g,h,i,j,k,l,m-1):l>0?f(a,b,c,d,e,g,h,i,j,k,l-1):k>0?f(a,b,c,d,e,g,h,i,j,k-1):j>0?f(a,b,c,d,e,g,h,i,j-1):i>0?f(a,b,c,d,e,g,h,i-1):h>0?f(a,b,c,d,e,g,h-1):g>0?f(a,b,c,d,e,g-1):e>0?f(a,b,c,d,e-1):d>0?f(a,b,c,d-1):c>0?f(a,b,c-1):b<0?a:f(a,b-1)}&&a end

Function alone: https://repl.it/Hvr5/58
Function with input: https://repl.it/Hvr5/59
This one's a whopping 494 characters (including spaces), but if you take a look at the code... its just... really repetitive... of nothing new compared to the above.  This would be where one defines this function for arbitrarily many arguments... which gives way to a whole new scheme of what you can do...

And to save space, one can incorporate half a variable by taking advantage of negative numbers.  For example, if the second argument is negative, replace it with the first argument.  If the second argument is zero, do the normal base case.  If the second argument is greater than zero, do the normal case.
def f(a,b=-a,c=a,d=a,e=a,g=a,h=a,i=a,j=a,k=a,l=a,m=a,n=a,o=a,p=a,q=a)a.times{a**=q>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n,o,p,q-1):p>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n,o,p-1):o>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n,o-1):n>0?f(a,b,c,d,e,g,h,i,j,k,l,m,n-1):m>0?f(a,b,c,d,e,g,h,i,j,k,l,m-1):l>0?f(a,b,c,d,e,g,h,i,j,k,l-1):k>0?f(a,b,c,d,e,g,h,i,j,k-1):j>0?f(a,b,c,d,e,g,h,i,j-1):i>0?f(a,b,c,d,e,g,h,i-1):h>0?f(a,b,c,d,e,g,h-1):g>0?f(a,b,c,d,e,g-1):e>0?f(a,b,c,d,e-1):d>0?f(a,b,c,d-1):c>0?f(a,b,c-1):b<0?f(a,a):b<1?a:f(a,b-1)}&&a end

Function alone: https://repl.it/Hvr5/72
Function with inputs: https://repl.it/Hvr5/74

Of course, all of the above can be drastically reduced down to a function that intakes arrays as arguments of arbitrary length:
def f(a,b=Array.new(a,a),c=a)d,*e=b;a.times{a+=(b.class==Fixnum)?a:b.size<2?f(a,d,c):d<0?f(a,e,c+1):c<0?a:f(a,[a,d-1,e],c-1)};a end

Function alone: https://repl.it/Jfgb/4
Function with inputs: https://repl.it/Jfgb/6
Function with handy dandy stuff on the side: https://repl.it/Jfgb/8

Lengthy explanations: https://repl.it/Jfcr/3

In terms of the fast growing hierarchy,
$$f(a,b)\approx f_{b+2}(a)$$
$$f(a,b,c)\approx f_{\omega b+c}(a)$$
$$f(a,b,c,d,e,g,h,i,j,k,l,m,n,o,p,q)\approx f_{\omega^{14}b+\omega^{13}c+\dots+\omega^2 o+\omega p+q}(a)$$
$$f(a,-b,c,d,e,g,h,i,j,k,l,m,n,o,p,q)\approx f_{\omega^{15}+\omega^{13}c+\dots+\omega^2 o+\omega p+q}(a)$$
Not really sure on the arbitrary length array yet.

Inspired by Largest printable number.

A: Came up with a simple to understand function using polynomials that grows pretty decently:
Let us define $S:(\text{polynomial, integer})\mapsto\text{integer}$ as follows:
$$S(P,n)=\begin{cases}n+1,&P=0\\S(Q,S(Q,n)),&\text{else}\end{cases}$$
where $Q$ is the fastest growing polynomial that is eventually less than $P$ and has integer coefficients between $0$ and $n$.
More rigorously, we define an ordering over polynomials $A,B$ by $A>B\iff\exists N,\forall x>N,A(x)>B(x)$. We then have $Q=\max\{R~|~P>R\land R\text{'s coefficients}\subseteq[0,n]\}$.
For example, we have
\begin{align}S(x^2,2)&=S(2x+2,S(2x+2,2))\\&=S(2x+2,S(2x+1,S(2x+1,2)))\\&=S(2x+2,S(2x+1,S(2x,S(2x,2))))\\&=\dots\\&=S(2x+2,S(2x+1,S(2x,S(x+2,S(x+1,S(x,S(2,S(1,S(0,S(0,2))))))))))\end{align}
Despite it's simplicity, $S(x^2,2)>2\uparrow\uparrow\uparrow10$, and $S(x^3,1)>g_{g_{g_{g_1}}}$, where $g_{64}$ is Graham's number.
One can then extend this pretty easily by replacing "polynomial" with anything formable using $0$, $+$, and $x~\widehat~$ e.g. $x^x=x^{x^{x^0}}$ or $x^{2x}$ etc. Under such an extension, $S(x\uparrow\uparrow n,n)$ grows about as fast as the Goodstein sequence.

A: Well, for example:
Rule 1 (only 2 entries):
{a,b} = a^b
Rule 2 (2nd entry is 1):
{a,1 #} = a
Rule 3 (last entry is 1):
{#,1} = {#}
Rule 4 (string of 1's from the 3rd entry to nth):
{a,b,1,1,...,1,1,c #} = {a,a,a,a,...,a,{a,b-1,1,1,...,1,1,c #},c-1 #}
Rule 5 (otherwise):
{a,b,c #} = {a,{a,b-1,c #},c-1 #}
Here # denotes the unchanged remainder of array. Then my function is f(n) = {n,n,n,...,n,n,n}.

A: Few lines??? I'm not even an ingenious mathematician and I can do this in half a line:
$$x!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!$$
, let alone what an ingenious mathematician will do with few lines. Maybe, you should put more restriction to your character limit.
I think this function suits the description of fastest growing as it's value at $x=0$ is 1. At $x=1$, it disguises you by staying constant. It takes your trust by growing by just 1 at $x=2$. Now, it has your trust and you, who wanted a decently growing function, would chose this one and reject other candidates like $10^x$, $x^2$, etc. But as soon as you step further, it shows its true nature and grows up to God knows where at $x=3$.
If the faster growing function competition was a race where all the functions had to start at 0 and reach 1 Googol ($10^{100}$) the fastest and functions with less than 5 characters where allowed, my money would be on $\tan{x}$ because we all know how slow it is at $x=1.4$, that's when $10^x$ would think it's far ahead, but just after $x=1.57$, $\tan{x}$ would look like it just teleported to $1 Googol$. As for, $x!!!!$, I don't think it's of much use if the race starts at 0.
When you think about it, the simplest function which easily grows up fastest to infinity starting from 0 is a well-known trigonometric function and it beats $\tan{x}$ by a slight margin and its name is $\sec{x}$.
At $x=1.57$, $\tan{x}$ is merely 1255, whereas $\tan^{-1}(\text{Googol})=1.5707963267948966192313216916398$. So, by merely increasing $x$ by 0.000707963267948966192313216916398, $\tan{x}$ grows from 1255 to 1Googol. So, I guess I was correct when I said $\tan{x}$ teleports to 1Googol.


text:
Q: Why does operating system need to know subnet mask? If I understand correctly, the operating system gets subnet mask together with IP and other stuff from the DHCP server. And this subnet mask seems to be important for router because it knows if packet goes from/to LAN or should be sent somewhere else or it's received from Internet. But why is the subnet mask needed for the operating system? What does the operating system do with the knowledge of the subnet mask?

A: There are 3 major components to the network configuration:

*

*IP Address

*Network Mask

*Default Gateway

The Operating System needs to know the network mask in order to determine where the data needs to travel. Your IP address combined with the network mask tell the OS whether a target IP address exists on the local subnet, or if it exists outside of your subnet. Some computers have multiple network connections, whether physical (multi NIC) or logical (think VPN). Without a subnet mask for each network, the OS would not be able to determine which traffic should leave which interface.
If the target exists within your subnet:

*

*Your OS determines the hardware address of the destination by referencing its ARP table. If there is no entry in the ARP table for that address, the system sends out a hardware broadcast that is flooded to all devices on the layer 2 network. The system who owns the IP address would then respond to the broadcast with its hardware address (MAC ADDR). The OS would then send the data along, with it never leaving the local network.

If the target does NOT exist within your subnet:

*

*Your OS determines where to send the packet based on its routing table. Most often than not, the packet will be destined for the default gateway. This gateway is generally a router which will use its own routing tables to send the packet on its way to its final destination. The process of sending to the default gateway is the same as sending to another host on the subnet. If the gateways MAC address isn't in the ARP table, it will send a broadcast out to determine the gateways hardware address, and then forward the frame.

So as you can see, the subnet mask is very important as it is used to determine the location of the destination network, and route them accordingly.

A: Based on the combination of an IP and a subnet mask the OS can figure out if a destination IP that it's user space application wants to contact is in it's local network or needs to be sent via some router. If it needs to be sent via a router, it does a routing table lookup to determine which router to use.

A: See Mauro's answer, but in addition the subnet mask allows the host to determine the IP broadcast address. I think this is less important in these days of DNS based name resolution, but in the old days before Active Directory NETBIOS name lookup could fail if the subnet mask was wrong because the broadcast address would be wrong.


text:
Q: Read data from text file and sort into a vector I have a data file like so ...
Control,3
Test,3
Control,3
Control,3
Test,1
Control,3
Control,1

I want to load them into 2 vectors test and control.
Any ideas?

A: Try read.csv()
dat <- read.csv(text = "Control,3
Test,3
Control,3
Control,3
Test,1
Control,3
Control,1", header = FALSE)

> dat
       V1 V2
1 Control  3
2    Test  3
3 Control  3
4 Control  3
5    Test  1
6 Control  3
7 Control  1

However, you'll need read.csv(file = "foo.csv", header = FALSE) and replace foo.csv with the path to and name of your file.
Then
test <- with(dat, V2[V1 == "Test"])
control <- with(dat, V2[V1 == "Control"])

> test
[1] 3 1
> control
[1] 3 3 3 3 1

Presuming I have understood what you want?


text:
Q: Can't assign jquery value to session variable in Yii In the following code the value item.rmid is provided by jQuery. The value is fetched from database, displayed in item.rmid and has to be stored in Yii::app()->SESSION["rid"] but it's not working.
In view I have the following code:
$("#pct").html('');
        $.each(<?php echo $ar; ?>, function (i, item) {

            $("#pct").append('

    fss"
    <?php Yii::app()->SESSION["rid"]=' + item.rmid + ' ; ?>"
    <?php echo Yii::app()->SESSION["rid"];?>

')

}
What am I doing wrong?
UPD
 when i var_dump($ar);
following is what i get
string '[{"pimg":"12.jpg","pid":"3","createdate":"2014-01-15 12:12:47","rid":"25"},{"pimg":"WP9.JPG","pid":"1","createdate":"2014-01-15 12:14:23","rid":"26"},{"pimg":"n2.jpg","pid":"4","createdate":"2014-01-16 11:01:27","rid":"54"}]

but the am unable to assign the rid value ......... know i got it i have multiple rid and am assign it to one Yii::app()->SESSION["rid"] which cant store all value at each iteration...
how do i pass it in the querystring but the valueto be hidden

A: You can't update stuff on the server via javascript without AJAX.
Use ajax to send a request to the server and update the session value using
 Yii::app()->session['var'] = $_POST['received_value'];

Read up about ajax here.

A: The main thing to note is that PHP part of the code is already finished working when your browser runs your javascript. What your code doing is just assigning the string ' + item.rmid + ' to some PHP variable. It's just a constant string which is not connected to your javascript at all. After that your browser gets something like the following javascript:
$("#pct").html('');
$.each(some_array_from_php, function (i, item) {
    $("#pct").append('

            fss""
             + item.rmid +

')
}

Notice how it gets "preprocessed" by PHP. It's not even good javascript really, because you can't use multiline string literals in javascript.
What you can do is to push some value from javascript to your server. So you need to feed javascript code to your browser first, get your value available in javascript and then somehow make another HTTP request passing the value as a GET parameter or something. There is a technology for this purpose, it's called AJAX. Check this out.
But from your code example it looks like you already have all the values on the server (in $ar variable, in JSON format), so you can just assign session variable on PHP and use javascript only for client-side visualization.
First you need to decode JSON:
$decoded = json_decode($ar);

Now $decoded is just an array of PHP objects, so you can do something like:
Yii::app()->session["rid"] = $decoded[0]->rid;

Above we are storing the "rid" of the first object to session. If you want to store all of them just loop through $encoded while pushing values to session like this:
foreach ($decoded as $obj) {
    Yii::app()->session["rids"][] = $obj->rid;
}


text:
Q: Access internal forget gate value in lstm node I have currently created an LSTM network using Keras and have to get the internal forget gate values for each node of the network. I have to get the forget gate/values everytime the predict() function is called. is it possible to do so?
If not then is there any other library which gives access to these internal gate values in a convenient manner at every step?
Looking forward to some help on this at the earliest.
Thank you.

A: How to get internal weights and parameters?
If you are using Keras with Tensorflow backend (which is the recommended backend), you can access to the internal layer values (like weights & biases) using tf.global_variables(). For convenience, create a dictionary which map the layer names to the corresponding tf.Variable:
variable_dict = dict([])
for variable in tf.global_variable():
    variable_dict[variable.name] = variable

After this simple mapping, you can refer to a variable directly by its name. The LSTM layer of Keras (let's say, the model.summary() shows that the LSTM layer is named as 'lstm_1') has the following internal variables: 'lstm_1/kernel:0', 'lstm_1/recurrent_kernel:0', and 'lstm_1/bias:0'. To get their values, you will need to have some understanding of Session and Tensor objects of Tensorflow.
Now is the tricky part: how does Keras store the variables in these tensors? The documentation does not specify any information about it, so unfortunately you will have to refer to the source code. Look at the LSTMCell class, especially the build (describes which variables are defined) and call (describes how these variables are used in calculation) methods. Seems like the internal parameters are stored in the variables, named as *_i, *_f, *_c, *_o (e.g. self.kernel_o).

How to get in-between values during calculation?
Unfortunately, you will have to directly modify the calculation graph. It is easier than it sounds: just edit the Tensorflow's code and store these variables somewhere in a named tensor in the global scope.

If not then is there any other library which gives access to these
  internal gate values in a convenient manner at every step?

As you see, Keras with a Tensorflow backend is very convenient. I don't think that you can get any more convenient than that.


text:
Q: reshape2 dcast without aggregation - problems with seq I try to reshape a dataset from this (mydata - snippet)
    sample          species         cell_nr biovol
1   41442bay_1      Mytilus sp.     6.22    1243.04
2   41502elba_1     Mytilus sp.     1.35    260.64
3   41502bay_3      Mytilus sp.     2.74    548.21
4   41443bay_2      M. edulis       599.14  114028.15
5   41411elba_2     M. edulis       5107.51 1021502.16

to this (result)
  sample     variable Mytilus sp.    M. edulis
1 41442bay_1 cell_nr  6.22           0
2 41442bay_1 biovol   1243.04        0
3 41443bay_2 cell_nr  0              599.14
4 41443bay_2 biovol   0              114028.15

So far I used reshape2 in R
mymelt <- melt(mydata, id=c("species", "sample"))
result <- dcast(mymelt, sample+variable~species)

But it aggregates my variables
Aggregation function missing: defaulting to length

I  need unique IDs for my pair of variables to reshape without aggregation - as fas as I understand by reading these two threads: how-to-use-cast-in-reshape-without-aggregation & reshaping-data-frame-with-duplicates
However, I'm stuck at this point. Any help is welcome and thank you in advance.
//edited
//edit2
this is a subset of "mydata" - the starting table - two sampling sites and two variables & and the taxa
structure(list(sample = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("41411bay_1",
"41411elba_1"), class = "factor"), genspec = structure(c(1L,
2L, 5L, 6L, 8L, 9L, 10L, 11L, 13L, 18L, 14L, 15L, 16L, 17L, 19L,
20L, 21L, 22L, 23L, 12L, 24L, 25L, 26L, 27L, 3L, 4L, 5L, 6L,
7L, 7L, 8L, 9L, 10L, 11L, 14L), .Label = c("Achnanthes_taeniata",
"Asterionella_formosa", "Chaetoceros_ceratosporus", "Chaetoceros_compressus",
"Chaetoceros_simplex", "Chaetoceros_socialis", "Chaetoceros_sp.",
"Chaetoceros_wighamii", "Chroococcus_minimus", "Chrysophyte_",
"Cryptophyte_", "decaying_dino", "decaying_dino_", "Gymnodinium_sp.",
"Melosira_nummuloides", "Monoraphidium_contortum", "Mougeotia_sp.",
"Mytilus_sp.", "Navicula_sp.", "Protoperidinium_pellucidum",
"Protoperidinium_sp.", "Quadrigula_sp.", "Rhabdoderma_lineare",
"Skeletonema_costatum", "Surirella_sp.", "Thalassionema_nitzschioides",
"Thalassiosira_sp."), class = "factor"), total_cell_nr = c(570.14,
142.54, 30.54, 95.02, 213.8, 6246.1, 1924.23, 71.27, 47.51, 23.76,
71.27, 23.76, 35.63, 11.88, 35.63, 59.39, 47.51, 35.63, 95.02,
59.39, 6235.91, 11.88, 35.63, 11.88, 487.34, 314.42, 15.72, 110.05,
408.74, 31.44, 267.25, 35471.82, 13119.72, 534.51, 15.72), total_biovol = c(114028.15,
74830.97, 25900.68, 23850.89, 500084.7, 51217.98, 769690, 15465.07,
342702.1, 11877.93, 5485537.87, 102340.26, 1460.99, 64200.22,
74830.97, 1640342.42, 656754.62, 7483.1, 2375.59, 428377.62,
860556.18, 950234.57, 37059.15, 35633.8, 207121.44, 107530.22,
13331.23, 27621.43, 163904.98, 12608.08, 625105.87, 290868.96,
5247886.36, 115988.01, 1210045.12)), .Names = c("sample", "genspec",
"total_cell_nr", "total_biovol"), class = "data.frame", row.names = c(NA,
-35L))

and I'm doing this
mymelt <- melt(mydata, id.vars=c("genspec", "sample"))
mymelt$indx <- with(mymelt, ave(seq_along(genspec), genspec, sample, FUN=seq_along))
result <- dcast(mymelt, sample+variable+indx~genspec, value.var='value', fill=0)

I would expect, that I get as a result 4 obs. (two sites and two variables), but instead I get 7 obs. with duplicated samples for bay_1 but not elba_1 - and this happens throughout the whole results in the original dataset. I guess it's a very basic problem with a simple answer, but I can't see it.
//edit3
Alright, I see what happened here - there were duplicated genspec (i.e. species) in my samples. This brought the chaos into the overall working answer from akrun. And to see what I mean, use the following commands with the above pasted df - I removed the duplicated sample and everything works fine:
mydata <- mydata[-30,]
mymelt <- melt(mydata, id.vars=c("genspec", "sample"))
mymelt$indx <- with(mymelt, ave(seq_along(genspec), genspec, sample, FUN=seq_along))
result <- dcast(mymelt, sample+variable+indx~genspec, value.var='value', fill=0)

A: You may need to create a sequence column
mymelt$indx <- with(mymelt, ave(seq_along(species), species, FUN=seq_along))
dcast(mymelt, sample+variable+indx~species, value.var='value', fill=0)
#        sample variable indx  M. edulis Mytilus sp.
#1  41411elba_2  cell_nr    2    5107.51        0.00
#2  41411elba_2   biovol    4 1021502.16        0.00
#3   41442bay_1  cell_nr    1       0.00        6.22
#4   41442bay_1   biovol    4       0.00     1243.04
#5   41443bay_2  cell_nr    1     599.14        0.00
#6   41443bay_2   biovol    3  114028.15        0.00
#7   41502bay_3  cell_nr    3       0.00        2.74
#8   41502bay_3   biovol    6       0.00      548.21
#9  41502elba_1  cell_nr    2       0.00        1.35
#10 41502elba_1   biovol    5       0.00      260.64

EDIT
If the dataset still has duplicates, try
 mymelt$indx <- with( mymelt,
                      ave(seq_along(species),
                          species,
                          sample,
                          FUN=seq_along
                      )
                )
 dcast(mymelt, sample+variable+indx~species, value.var='value', fill=0)

data
 mydata <- structure(
               list(sample  = c("41442bay_1", "41502elba_1", "41502bay_3", "41443bay_2", "41411elba_2"),
                    species = c("Mytilus sp.", "Mytilus sp.", "Mytilus sp.", "M. edulis", "M. edulis"),
                    cell_nr = c(6.22, 1.35, 2.74, 599.14, 5107.51),
                    biovol  = c(1243.04, 260.64, 548.21, 114028.15, 1021502.16)
               ),
               .Names    = c("sample", "species", "cell_nr", "biovol"),
               class     = "data.frame",
               row.names = c("1", "2", "3", "4", "5")
           )


text:
Q: VB.Net ShowDialog how to close Hello i have a code here that shows a loading dialog and i cant seem to close it
can anyone please help me
        'Show Loading
        Dim MLUI As New MiniLoadingUI()
        MLUI.ShowDialog()

A: For what it is worth, you should be wrapping your declaration in Using statements:
Using MLUI As New MiniLoadingUI()
   MLUI.ShowDialog()
End Using

As far as your problem goes, you should simply call the following:
MLUI.Close()

However it is worth noting that ShowDialog shows the form as a modal dialog box which means that unless you would be calling the Close method in a timer, it would need to be closed by the user.

A: you can try Dispose() or close() for close form.
Dim MLUI As New MiniLoadingUI()
MLUI.ShowDialog()
MLUI.dispose()


text:
Q: h step ahead forecast I have a problem consists of forecasting the next 16 values for 250 time series of daily demands, Can I forecast just for one period ahead and then multiple it by 16? is it correct?  I was wondering if you give me your suggestions.

A: Only if your model is a random walk or a simple mean model ,otherwise you will have to forecast out 16 periods for each of your 250 time series. You might want to take into account some factors like 1) day-of-the-week-effects 2 ) auto-projective structure i.e. the impact of previous values on the forecast 3) the impact of events like holidays such as lead,contempraneous and lag effects 4) possible changes in the model parameters over time 5) possible changes in the variance of the errors over time 6) level shifts in your time series 7) local time trends in your time series 8) the impact of unusual values ( one time anomalies ) . If you deal corrrectly with these eight considerations you forecast might be useful.


text:
Q: How to calculate the bounding box for a given lat/lng location and querying the database in c# I have given a location defined by latitude and longitude. Now i want to calculate a bounding box within e.g. 500 meters of that point.
The bounding box should be defined as latmin, lngmin and latmax, lngmax.
My database has almost 152.000 records ( locations of objects defined by lat long), and if the user enters the specific object in the search bar (search by name), I should find objects to the specific radius e.g. within 500 meters.
For example this is one record: Latitude = 41.72213058512578, Longitude = 44.77684020996094, Name = company1
If I find latmin, lngmin and latmax, lngmax how to query the database? I want to achieve this in C#.

A: Look into the Haversine Formula.
Create this query in your application or Stored Procedure from your database. It will return the 15 closest locations to given latpoint and longpoint within a given radius. The radius is now set to 50 feel free to change that.
 SELECT z.zip,
        z.primary_city,
        z.latitude, z.longitude,
        p.distance_unit
                 * DEGREES(ACOS(COS(RADIANS(p.latpoint))
                 * COS(RADIANS(z.latitude))
                 * COS(RADIANS(p.longpoint) - RADIANS(z.longitude))
                 + SIN(RADIANS(p.latpoint))
                 * SIN(RADIANS(z.latitude)))) AS distance_in_meters
  FROM zip AS z
  JOIN (   /* these are the query parameters */
        SELECT  42.81  AS latpoint,  -70.81 AS longpoint,
                50.0 AS radius,      111054.0 AS distance_unit
    ) AS p ON 1=1
  WHERE z.latitude
     BETWEEN p.latpoint  - (p.radius / p.distance_unit)
         AND p.latpoint  + (p.radius / p.distance_unit)
    AND z.longitude
     BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
         AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
  ORDER BY distance_in_meters
  LIMIT 15

change 111054.0 to 69.0 for distance_in_miles
Something like this in your C# application to call a stored procedure and get the data back from the query in a list.
private List<DataModel> getData(double latitude, double longitude, int radius)
{
    SqlParameter[] param =
                     {
                        new SqlParameter("@lat", latitude),
                        new SqlParameter("@lon", longitude),
                        new SqlParameter("@rad", radius)
                     };
  //Call stored procedure
  var data db.Database.SqlQuery<DataModel("Haversine",param)
  return data.ToList();
}


text:
Q: Quadratic constraint with ROI package I have a quadratic optimization function (solution on x) with a quadratic constraint that I want to be on (x-y) rather than on x as i currently have it. I am currently working with the ROI package and the alabama solver.
x <- c(0.2, 0.3, 0.1, 0.25, 0.15)
y <- rep(0.2, 5)
C <- matrix(rep(0.5, 25),nrow=5,ncol=5,byrow=TRUE)
z <- x-y

The constraint is currently as below and works on x.
Risk_constraint <- Q_constraint(Q = list(C),rep(0, 5), dir =  "<=", rhs =  0.2)

How could i change the constraint so that it is applied on z - i still need the optimization solution to be for x though.


text:
Q: How to get macros take again same line's from the file, when he came to the end of file How to get macros take again same line's from the txt file, when he came to the end of file. I have script that takes google+ url pages from file which have 35 links, then i have another one file with website links that i need to post on wall. Each web-link need to be posted on each of 35 google+ pages. At the moment script visit's all url's post first link from file as i need, but when he came's to the end of file, macros stops to work. Any sugestion's how can i make it?
Here is my script
var macros;
var loop = 1;
macros = "CODE:";
macros += "SET !DATASOURCE google_pages.txt" + "\n";
macros += "SET !DATASOURCE_LINE {{i}}" + "\n";
macros += "URL GOTO={{!COL1}}" + "\n";
macros += "TAG POS=1 TYPE=DIV ATTR=CLASS:\"kqa es\"" + "\n";
macros += "SET !DATASOURCE links.txt" + "\n";
macros += "SET !DATASOURCE_LINE {{!LOOP}}" + "\n";
macros += 'EVENTS TYPE=KEYPRESS SELECTOR="div[class=\\"df b-K b-K-Xb URaP8 editable\\"]" CHARS={{!COL1}}' + "\n";
macros += "TAG POS=1 TYPE=DIV ATTR=CLASS:\"d-k-l b-c b-c-Ba qy jt\"" + "\n";
loop += prompt("How many times to play macros?:", loop);

for(i = 1; i <= loop; i++) {
    iimSet("i",i)
    iimDisplay("Loop Plays: "+i)
    iimPlay(macros)
}

A: As I understood this issue, you should view the following snippet:
var linesInTxt = 35;
var numToRepeat = 2;
var loop = numToRepeat*linesInTxt;
for (i = 1; i <= loop; i++) {
    var j = (i % linesInTxt == 0) ? linesInTxt : i % linesInTxt;
    iimSet("i", j);
    // further code here
}


text:
Q: Pass "uniform sampler2D" to glsl shader in libgdx(using modelBatch) I have trouble with passing sampler2d uniform from my code to shader. I have this line in my shader:
uniform sampler2D u_texture;

In code, I am using g3db models created in blender(with textures):
AssetManager assets = new AssetManager();
    assets.load(data+"/earth.g3db", Model.class);
    assets.finishLoading();
    Model earthModel = assets.get(data+"/earth.g3db", Model.class);
    earthPlanet = new ModelInstance(earthModel,0,-1,0);

I render this using modelBatch:
 modelBatch.begin(cam);
    modelBatch.render(earthPlanet, shader);
    modelBatch.end();

I have shader class in my code, and a render method within:
public void render(Renderable renderable) {
    program.setUniformMatrix(u_worldTrans, renderable.worldTransform);
        //how to pass texture??
    //program.setUniformf(sampler2D, ????);
    renderable.mesh.render(program,
            renderable.primitiveType,
            renderable.meshPartOffset,
            renderable.meshPartSize);
}

I would be happy for any response. Thanks!

A: Your confusion stems from the fact that you think you pass textures to sampler uniforms. This is not the case.
When you give a value to a sampler uniform, the value you are supposed to supply is the texture unit. Say you had a texture and bound it to GL_TEXTURE0, then you would give the sampler uniform the value: 0. Generally you treat samplers as integer uniforms, by the way, so the proper code would probably be: program.setUniformi (sampler2D, 0);
This tells GLSL that the sampler will use texture unit 0, the actual texture used will depend on whatever is bound to that texture unit.


text:
Q: Inaccessible variable from locals() after "exec" function I have a python file "test.py" with code inside:
    variable = 10

Open python3 and enter next code:
    def main():
        with open("test.py") as f:
            exec(f.read())
        print(locals())
        print(variable)
    main()

And get output:
{'f': <_io.BufferedReader name='test.py'>, 'variable': 10}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in main
NameError: name 'variable' is not defined

Why locals() has "variable", but don't able executable it?

A: OK. Here is my explanation. If you will use the dis module, you will see the following:
 32 LOAD_GLOBAL              3 (print)
 34 LOAD_GLOBAL              4 (variable)
 36 CALL_FUNCTION            1

LOAD_GLOBAL - Loads the global named co_names[namei] onto the stack.
But why doesn't the python try to search first in the local namespace? I think this is due to python optimization.
If done:
print(main.__code__.co_varnames)
print(main.__code__.co_names)

Can see:
('f',)
('open', 'exec', 'read', 'print', 'variable')

In this way is the interpreter at compile time into bytecode, sees that there is no such variable in the local scope and generates code to search the global scope. But at the same time, the values for the variables themselves are taken from the locals and globals and exec update exactly locals scope, adding there value for variable

A: This will work
def f():
    with open("temp.py") as f:
        temp = f.read()
    exec(temp)
    print(locals())
    print(variable)
f()

Explanation
Python works with nested scope, Where any variable defined in outer scope becomes automatically available in the inner scope, but the reverse is not true.
When you are using exec within the scope of with, the variable variable is going to be available only within that scope. it will not be available in the scope of the function f() which is outside the scope of the with block


text:
Q: What heap structure does C++ STL priority queue use? Specifically, what heap variant does the STL priority queue container adaptor use? I'm benchmarking it vs my own hand rolled binary heap and double bucket structure implementations, so just wondering.  Bonus points for any interesting implementation knowledge!

A: This question is tagged C++ (as opposed to asking for implementation-specific details on a particular compiler), so I've checked the standard for any information. In various sections of 23.6.4 we learn that the priority_queue simply behaves as-if it uses make_heap, push_heap, and pop_heap. Then these functions are documented (in 25.4.6 sections) as having complexity At most 3 * (last - first) comparisons., At most log(last - first) comparisons., and At most 2 * log(last - first) comparisons. respectively. So certain heap implementations may be indicated by these characteristics, but no specific heap is called out.

A: You can choose the container underlying the priority_queue. If not specified the default is to use a std::vector:
template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

Container -   The type of the underlying container to use to store the
  elements. The container must satisfy the requirements of
  SequenceContainer. Additionally, it must provide the following
  functions with the usual semantics: front() push_back() pop_back() The
  standard containers std::vector and std::deque satisfy these
  requirements.

The heap is implemented by the *_heap functions, in a straightforward way. You can inspect the code here:
 http://www.sgi.com/tech/stl/stl_heap.h


text:
Q: Need class for custom config in app.config of collection refering another I need custom class for following Custom config in app.config of collection referring another
<Tasks >

        <Task Name="Abc" Type="local">
    <TaskName>Abc(note full name goes here)</TaskName>
    <Priority>1<Priority>
        </Task>
        <Task Name="xyz" Type="test">
    <TaskName>xyz</TaskName>
    <Priority>4<Priority>
        </Task>
        <Task Name="123" Type="dev">
    <Task Name>123</Task Name>
    <Priority>5<Priority>
    </Task>
      </Tasks>

      <Activities>
        <Activity Name="coding">
          <Tasks>
            <Task>Abc</Task>
            <Task>123</Task>
          </Tasks>
         </Activity>
        <Activity Name="planing">
          <Tasks>
            <Task>xyz</Task>
            <Task>123</Task>
          </Tasks>
         </Activity>
      </Activities>

I tried many but I am running to many errors to get list of activities with their tasks please help me

A: Your XML structure can be represented by this class. Your XML structure is quite inconsistent. If you want a class structure as accurate as possible, then please fix your XML.
class Program
{
    static void Main(string[] args)
    {
        List<Activity> activities = new List<Activity>();
    }
}

public class Activity
{
    public string Name { get; set; }
    List<Task> Tasks { get; set; }
}

public class Task
{
    public string Name { get; set; }
    public string Type { get; set; }
    public Priority Priority { get; set; }
}

public class Priority
{
    public string Name { get; set; }//--or however you want to structure this class, this could also be an enum
}