text:
Q: How to create Generics Pooling System for components/scripts? My awareness of Generics is that they can help me streamline my pooling, but can't figure out how.
My pooling system is minimalistic, but messy. And now getting unwieldy and messy, and MESSY. It doesn't scale nicely...
My FXDistribrutor.cs class is a component attached to an object in the initial scene, designed to permanently exist throughout all scenes of the game. It has a static reference to itself, so that I can call into it from anywhere easily. More on that contrivance at the end. I'm not even sure if that's the 'right' way to do this. But it works nicely.
FXDistributor has a public slot for each type of FX Unit it is able to distribute, and an array for the pool of this type of FX, and an index for the array and a size of the pool.
Here are two examples:
    public BumperFX BmprFX;
    BumperFX[] _poolOfBumperFX;
    int _indexBumperFX, _poolSize = 10;

    public LandingFX LndngFX;
    LandingFX[] _poolOfLndngFX;
    int _indexLndngFX, _poolSizeLndngFX = 5;

In the Unity Start call, I fill the pools of each FX Unit:
void Start(){

    _poolOfBumperFX = new BumperFX[_poolSize];
    for (var i = 0; i < _poolSize; i++) {
    _poolOfBumperFX[i] = Instantiate(BmprFX, transform );
    }

    _poolOfLndngFX = new LandingFX[_poolSizeLndngFX];
    for ( var i = 0; i < _poolSizeLndngFX; i++ ) {
    _poolOfLndngFX[i] = Instantiate( LndngFX, transform );
    }
}

And in the body of the class I have a bunch of methods for each FX type, to provide them to wherever they're needed:
public LandingFX GimmeLandingFX ( ){
    if ( _indexLndngFX == _poolSizeLndngFX ) _indexLndngFX = 0;
    var lndngFX = _poolOfLndngFX[_indexLndngFX];
    _indexLndngFX++; return lndngFX;
}
public BumperFX GimmeBumperFX ( ) {
    if ( _indexBumperFX == _poolSize ) _indexBumperFX = 0;
    var bumperFX = _poolOfBumperFX[_indexBumperFX];
    _indexBumperFX++;   return bumperFX;
}

So when I want one of these FX, and to use it, I call like this, from anywhere, into the static reference:
    FXDistributor.sRef.GimmeLandingFX( ).Bounce(
            bounce.point,
            bounce.tangentImpulse,
            bounce.normalImpulse
            );

How do I streamline this approach with Generics so I can easily and less messily do this sort of thing for a couple of dozen types of FX Units?

A: In Unity, the Instantiate() and Destroy() functions are used to create copy of objects especially prefabs and destroy them. When it comes to pooling, the pool object is usually represented in the pool as a Type of GameObject. When you need to access a component from the pool you first retrieve the pool GameObject then use the GetComponent function to retrieve the component from a GameObject.

Reading your question and comments carefully, you want to avoid the GetComponent section and represent just the components not the GameObject so that you can also access the components directly.
If this is what you want then this is where Unity's Component is required. See below for steps required to do this.
Note that when I say component/script, I am referring to your scripts that derive from MonoBehaviour that can be attached to GameObjects or built-in Unity components such as Rigidbody and BoxCollider.
1. Store the components/scripts to a List of  Component.
List<Component> components;

2. Store the List of Components in a Dictionary with Type as the key and List<Component> as the value. This makes it easier and faster to group and find components by Type.
Dictionary<Type, List<Component>> poolTypeDict;

3. The rest is really easy. Make the function that adds or retrieves the pool items from and to the Dictionary to be generic then use Convert.ChangeType to cast between the generic type to Component type or from generic to what ever type that is requested to be returned.
4. When you need to add item to the Dictionary, check if the Type exist yet, if it does, retrieve the existing key, create and add new Component to it with the Instantiate function then save it to the Dictionary.
If the Type doesn't exist yet, no need to retrieve any data from the Dictionary. Simply create new one and add it to the Dictionary with its Type.
Once you add item to the pool de-activate the GameObject with component.gameObject.SetActive(false)
5. When you need to retrieve an item from the pool, check if the Type exist as key then retrieve the value which is List of Component. Loop over the components and return any component that has a de-activated GameObject. You can check that by checking if component.gameObject.activeInHierarchy is false.
Once you retrieve item from the pool activate the GameObject with component.gameObject.SetActive(true)
If no component is found, you can decide to either return null or instantiate new component.
6. To recycle the item back to the pool when you're done using it, you don't call the Destroy function. Simply de-activate the GameObject with component.gameObject.SetActive(false)*. This will make the component able to be found next time you search for available components in the Dictionary and List.
Below is an example of minimum generic pool system for scripts and components:
public class ComponentPool
{
    //Determines if pool should expand when no pool is available or just return null
    public bool autoExpand = true;
    //Links the type of the componet with the component
    Dictionary<Type, List<Component>> poolTypeDict = new Dictionary<Type, List<Component>>();

    public ComponentPool() { }

    //Adds Prefab component to the ComponentPool
    public void AddPrefab<T>(T prefabReference, int count = 1)
    {
        _AddComponentType<T>(prefabReference, count);
    }

    private Component _AddComponentType<T>(T prefabReference, int count = 1)
    {
        Type compType = typeof(T);

        if (count <= 0)
        {
            Debug.LogError("Count cannot be <= 0");
            return null;
        }

        //Check if the component type already exist in the Dictionary
        List<Component> comp;
        if (poolTypeDict.TryGetValue(compType, out comp))
        {
            if (comp == null)
                comp = new List<Component>();

            //Create the type of component x times
            for (int i = 0; i < count; i++)
            {
                //Instantiate new component and UPDATE the List of components
                Component original = (Component)Convert.ChangeType(prefabReference, typeof(T));
                Component instance = Instantiate(original);
                //De-activate each one until when needed
                instance.gameObject.SetActive(false);
                comp.Add(instance);
            }
        }
        else
        {
            //Create the type of component x times
            comp = new List<Component>();
            for (int i = 0; i < count; i++)
            {
                //Instantiate new component and UPDATE the List of components
                Component original = (Component)Convert.ChangeType(prefabReference, typeof(T));
                Component instance = Instantiate(original);
                //De-activate each one until when needed
                instance.gameObject.SetActive(false);
                comp.Add(instance);
            }
        }

        //UPDATE the Dictionary with the new List of components
        poolTypeDict[compType] = comp;

        /*Return last data added to the List
         Needed in the GetAvailableObject function when there is no Component
         avaiable to return. New one is then created and returned
         */
        return comp[comp.Count - 1];
    }

    //Get available component in the ComponentPool
    public T GetAvailableObject<T>(T prefabReference)
    {
        Type compType = typeof(T);

        //Get all component with the requested type from  the Dictionary
        List<Component> comp;
        if (poolTypeDict.TryGetValue(compType, out comp))
        {
            //Get de-activated GameObject in the loop
            for (int i = 0; i < comp.Count; i++)
            {
                if (!comp[i].gameObject.activeInHierarchy)
                {
                    //Activate the GameObject then return it
                    comp[i].gameObject.SetActive(true);
                    return (T)Convert.ChangeType(comp[i], typeof(T));
                }
            }
        }

        //No available object in the pool. Expand array if enabled or return null
        if (autoExpand)
        {
            //Create new component, activate the GameObject and return it
            Component instance = _AddComponentType<T>(prefabReference, 1);
            instance.gameObject.SetActive(true);
            return (T)Convert.ChangeType(instance, typeof(T));
        }
        return default(T);
    }
}

public static class ExtensionMethod
{
    public static void RecyclePool(this Component component)
    {
        //Reset position and then de-activate the GameObject of the component
        GameObject obj = component.gameObject;
        obj.transform.position = Vector3.zero;
        obj.transform.rotation = Quaternion.identity;
        component.gameObject.SetActive(false);
    }
}

USAGE:
It can take a any prefab component script. Prefabs are used for this since pooled objects are usually prefabs instantiated and waiting to be used.
Example prefab scripts (LandingFX, BumperFX) :
public class LandingFX : MonoBehaviour { ... }

and
public class BumperFX : MonoBehaviour { ... }

Two variables to hold the Prefabs references. You can either use public variables and assign them from the Editor or load them with the Resources API.
public LandingFX landingFxPrefab;
public BumperFX bumperFxPrefab;

Create new Component Pool and disable auto-resize
ComponentPool cmpPool = new ComponentPool();
cmpPool.autoExpand = false;

Create 2 pools for LandingFX and BumperFX components. It can take any component
//AddPrefab 2 objects type of LandingFX
cmpPool.AddPrefab(landingFxPrefab, 2);
//AddPrefab 2 objects type of BumperFX
cmpPool.AddPrefab(bumperFxPrefab, 2);

When you need a LandingFX from the pool, you can retrieve them as below:
LandingFX lndngFX1 = cmpPool.GetAvailableObject(landingFxPrefab);
LandingFX lndngFX2 = cmpPool.GetAvailableObject(landingFxPrefab);

When you need a BumperFX from the pool, you can retrieve them as below:
BumperFX bmpFX1 = cmpPool.GetAvailableObject(bumperFxPrefab);
BumperFX bmpFX2 = cmpPool.GetAvailableObject(bumperFxPrefab);

When you're done using the retrieved component, recycle them back to the pool instead of destroying them:
lndngFX1.RecyclePool();
lndngFX2.RecyclePool();
bmpFX1.RecyclePool();
bmpFX2.RecyclePool();

A: I'm not that pleased with the solution, but combining a nice object pool with a use of simple Dictionary<K, V> yields the following:
// pool of single object type, uses new for instantiation
public class ObjectPool<T> where T : new()
{
    // this will hold all the instances, notice that it's up to caller to make sure
    // the pool size is big enough not to reuse an object that's still in use
    private readonly T[] _pool = new T[_maxObjects];
    private int _current = 0;

    public ObjectPool()
    {
        // performs initialization, one may consider doing lazy initialization afterwards
        for (int i = 0; i < _maxObjects; ++i)
            _pool[i] = new T();
    }

    private const int _maxObjects = 100;  // Set this to whatever

    public T Get()
    {
        return _pool[_current++ % _maxObjects];
    }
}

// pool of generic pools
public class PoolPool
{
    // this holds a reference to pools of known (previously used) object pools
    // I'm dissatisfied with an use of object here, but that's a way around the generics :/
    private readonly Dictionary<Type, object> _pool = new Dictionary<Type, object>();

    public T Get<T>() where T : new()
    {
        // is the pool already instantiated?
        if (_pool.TryGetValue(typeof(T), out var o))
        {
            // if yes, reuse it (we know o should be of type ObjectPool<T>,
            // where T matches the current generic argument
            return ((ObjectPool<T>)o).Get();
        }

        // First time we see T, create new pool and store it in lookup dictionary
        // for later use
        ObjectPool<T> pool = new ObjectPool<T>();
        _pool.Add(typeof(T), pool);

        return pool.Get();
    }
}

Now, you can simply do the following:
pool.Get<A>().SayHello();
pool.Get<B>().Bark();

This however still leaves a room for improvements as it instantiates classes with new rather than your factory method, as well as does not provide a way to customize pool size in a generic way.


text:
Q: Ubuntu 13.04 install gone wrong: no GUI in ubuntu and CANNOT boot into Windows 8 I tried to install Ubuntu 13.04 alongside Windows 8. I had shrunk the Windows partition 21 GBs, and did not format it. Then, I disabled fast boot and secure boot from the BIOS, and made the UEFI: sandisk with the 13.04 copied with Universal USB installer, the first priority for boot.
When Ubuntu installer loaded, I chose Install Ubuntu, and then chose install alongside ubuntu.
When it restarted, GRUB showed up with no problem, but when I try to load Ubuntu, I get no GUI. I tried startx, but it told me no screens found.
When I try to boot into Windows 8, by choosing it from GRUB loader, It gives me the following errors:
error: can't find command "drivemap"
error: invalid efi filepath

But, when I go to the BIOS, the boot options have changed to include Ubuntu, and also the already existing Windows Boot Manager. I choose Windows Boot Manager again, which, upon restart, bypasses GRUB, and loads directly into Windows 8.
I am not sure whether these are two separate problems so I wrote them both in a single question.
The laptop I use is Samsung ATIV book 9, with 128 GB SSD.

A: Ok, I am very sorry. As I said, I had a little trouble with the 13.04 (it is also an unstable version). Just got with the Long Term Support version 12.04 LTS. This version is very stable and no problems on it. I can't propose any solution because I haven't tried deeply 13.04 so far. But if I find the solution to your problem, I'll let you know.
12.04 is stable and supported until 2017. If you try to install it alonside Windows 8, format a partition (to ext2 or ext4) then install Ubuntu on it. It is advided to use the swap partition (1GB) if you computer has less than 4GB. After installing, you should have GRUB and then boot ubuntu. Any trouble with 12.04, tell me

A: This is why your windows option fails:
The Ubuntu grub has a BIOS friendly menu item created by os-prober, which generates all the non-Ubuntu boot menu items. os-prober is not UEFI-ready (late-2013). Your system is UEFI and you will have to create your own menu item to boot windows, if you want to use Ubuntu grub2 to choose your OS, you can add menu items by editing this file: etc/grub.d/40_custom
add this menu item to it, by: sudo gedit etc/grub.d/40_custom
menuentry 'Windows 8' {
search --fs-uuid --no-floppy --set=root 28ED-4D40
chainloader (${root})/EFI/Microsoft/Boot/bootmgfw.efi
}
replace the 28E... with the UUID of your EFI partition. Find the UUID of the EFI partition using sudo blkid command in linux terminal.
if you want windows to be at the top of the list, just rename 40_custom to 09_custom.
Then run sudo grub2-mkconfig -o /boot/grub/grub.cfg to regenerate the file that holds the bootloader menu items. You can also customize the menu items completely.
Regarding the problem where Ubuntu doesnt seem to boot properly, I recommend running Ubuntu boot-repair after booting from a Ubuntu live USB. You can make the live USB in windows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Complex SQL query I have the these tables:

- Users
    - id
- Photos
    - id
    - user_id
- Classifications
    - id
    - user_id
    - photo_id

I would like to order Users by the total number of Photos + Classifications which they own.
I wrote this query:

SELECT users.id,
COUNT(photos.id) AS n_photo,
COUNT(classifications.id) AS n_classifications,
(COUNT(photos.id) + COUNT(classifications.id)) AS n_sum
FROM users
LEFT JOIN photos ON (photos.user_id = users.id)
LEFT JOIN classifications ON (classifications.user_id = users.id)
GROUP BY users.id
ORDER BY (COUNT(photos.id) + COUNT(classifications.id)) DESC

The problem is that this query does not work as I expect and returns high numbers while I have only a few photos and classifications in the db. It returns something like this:
id n_photo n_classifications   n_sum
29  19241   19241                   38482
16  16905   16905                   33810
1    431     0                       431
...

A: You are missing distinct.
  SELECT U.ID, COUNT(DISTINCT P.Id)+COUNT(DISTINCT C.Id) Count
  FROM User U
  LEFT JOIN Photos P ON P.User_Id=U.Id
  LEFT JOIN Classifications C ON C.User_Id=U.Id
  GROUP BY U.Id
  ORDER BY COUNT(DISTINCT P.Id)+COUNT(DISTINCT C.ID)

A: I could be misinterpreting your schema, but shouldn't this:
LEFT JOIN classifications ON (classifications.user_id = users.id)

Be this:
LEFT JOIN classifications ON (classifications.user_id = users.id)
                         AND (classifications.photo_id = photos.id)

?

A: SELECT users1.id, users1.n_photo, users2.n_classifications
FROM (
    SELECT users.id, COUNT(photos.id) AS n_photo
    FROM users LEFT OUTER JOIN photos ON photos.user_id = users.id
    GROUP BY users.id
  ) users1
  INNER JOIN (
    SELECT users.id, COUNT(classifications.id) AS n_classifications
    FROM users LEFT OUTER JOIN classifications ON classifications.user_id = users.id
    GROUP BY users.id
  ) users2 ON users1.id = users1.id

A: Try something more like this instead:
SELECT users.id as n_id,
(SELECT COUNT(photos.id) FROM photos WHERE photos.user_id = n_id) AS n_photos,
(SELECT COUNT(classifications,id) FROM classifications WHERE classifications.user_id = n_id) AS n_classifications,
(n_photos + n_classifications) AS n_sum
FROM users
GROUP BY n_id
ORDER BY n_sum DESC


text:
Q: Forma de mapear un checkbox como bool (bit en SQL server)? Se que siempre piden codigo, pero es basica mi pregunta. Tambien se que lo pueden calificar como "conocimiento general" o "respuesta subjetiva", pero aunque paresca increible, no hay muchos topicos en español que hablen del tema.
Basicamente tengo un HTML Helper Checkbox y quiero capturar su valor con AJAX/JSON y enviarlo a mi controller para que lo guarde en el modelo.
Ahora el problema es que no se como tratar al checkbox por que su valor pueder ser "on" o Nothing, cuando quiero capturar eso para llevarlo a la BD el modelo me exige que lo convierta en "true" o "false", asi que hago la conversion en el controller. Ahora lo interesante es que cuando veo la BD encuentro que los valores posibles (bit) pueden ser 0 o 1 y cuando hago el mapeo en vez de guardarme 1 (true) me guarda 0. Alguno sabe como debo "convertir" el dato para que lo considere como 1 o 0 en la BD? gracias!!

A: Podrías adicionar estos input para controlar el valor que llega cuando se selecciona o no:
<form>
  <input type='hidden' value='0' name='selfdestruct'>
  <input type='checkbox' value='1' name='selfdestruct'>
</form>

Si es 1 lo conviertes a true en el modelo y si es cero a false.
Luego nuevamente a 1 y 0 en el sql.
Esta solución no es optima pero responde a tu pregunta, saludos


text:
Q: What Promoted Object should I use when creating an AdSet with lead_generation optimization goal? I'm using facebookads python api, v2.6.
I'm trying to create an AdSet with optimization goal = lead_generation.
This is my code:
ad_set = AdSet(parent_id = 'act_%s' % FB_ACCOUNT)
ad_set[AdSet.Field.name]= 'Teste AdSet'
ad_set[AdSet.Field.campaign_id]='6043402838999'
ad_set[AdSet.Field.status]=AdSet.Status.paused
ad_set[AdSet.Field.billing_event] = AdSet.BillingEvent.impressions
ad_set[AdSet.Field.optimization_goal] = AdSet.OptimizationGoal.lead_generation
ad_set[AdSet.Field.daily_budget]= 100
ad_set[AdSet.Field.bid_amount]= 1
ad_set[AdSet.Field.start_time]= '2016-07-01'
ad_set[AdSet.Field.promoted_object]=
ad_set[AdSet.Field.targeting]= {Targeting.Field.geo_locations: { 'countries': ['BR']},Targeting.Field.genders: [1],Targeting.Field.age_min: 20,Targeting.Field.age_max: 24}

ad_set.remote_create()

But when I run this I get this error:
 Status:  400
  Response:
    {
      "error": {
        "code": 100,
        "is_transient": false,
        "error_subcode": 1885024,
        "error_user_msg": "When creating an ad set within a campaign using the Body of an error/warning message. Title is: Promoted Object Missing objective, a promoted object must be specified.",
        "error_user_title": "Promoted Object Missing",
        "message": "Invalid parameter",
        "type": "OAuthException",
        "fbtrace_id": "B9hyZlpzS7O"
      }
    }

I tried to find any documentation about this, but could not. On the official docs I don't see LEAD_GENERATION on the promoted objects options:
https://developers.facebook.com/docs/marketing-api/reference/ad-campaign#Creating
Anyone had this problem?

A: In case anyone has the same issue, you have to use page_id.

A:
The ad set must have its promoted_object set to the corresponding <PAGE_ID>.

reference:
https://developers.facebook.com/docs/marketing-api/guides/lead-ads/create#create

A: you have to specify your associated page_id
promoted_object={"page_id": "<PAGE_ID>"}

Below code may help u
from facebook_business.adobjects.adaccount import AdAccount
from facebook_business.adobjects.adset import AdSet
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<AD_ACCOUNT_ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
]
params = {
  'name': 'A CPA Ad Set',
  'campaign_id': '<adCampaignLinkClicksID>',
  'daily_budget': '5000',
  'start_time': '2019-01-09T21:31:19-0800',
  'end_time': '2019-01-16T21:31:19-0800',
  'billing_event': 'IMPRESSIONS',
  'optimization_goal': 'REACH',
  'bid_amount': '1000',
  'promoted_object': {'page_id':'<pageID>'},
  'targeting': {'geo_locations':{'countries':['US']}},
  'user_os': 'iOS',
  'publisher_platforms': 'facebook',
  'device_platforms': 'mobile',
}
print AdAccount(id).create_ad_set(
  fields=fields,
  params=params,
)


text:
Q: Is it okay to use "and", "or" etc. instead of "&&", "||"? I'm used to the and and or keywords in C++. I've always used them and typing them is fast and comfortable for me. Once I've heard that these aliases are non-standard and may not work on all compilers. But I'm not sure of it, I don't really know if it's true.
Let's assume that I give someone my code, will he have problems compiling it?
Is it all right when I use and, or instead of &&, ||? Or are these keywords really non-standard?
P.S.I use the MinGW compiler.

A: These keywords ARE standard and are described in section 2.5 of the standard.  Table 2 is a table of these "alternative tokens".  You can use them all you want, even though everyone will hate you if you do.

A: They are standard in the new c++0x standard. Up-to-date modern compilers should recognise them, although I don't believe they are obliged to yet. Whatever floats your boat, I assume.

A: They are in fact standard in C++, as defined by the ISO 14882:2003 C++ standard 2.5/2 (and, indeed, as defined by the 1998 edition of the standard). Note that they are built into the language itself and don't require that you include a header file of some sort.
However, they are very rarely used, and I have yet to see production code that actually uses the alternative tokens. The only reason why the alternative tokens exist in the first place is because these characters on some keyboards (especially non-QWERTY ones) were either nonexistent or clumsy to type. It's still in the standard for backwards compatibility.
Even though they are standard, I highly recommend that you don't use them. The alternative tokens require more characters to type, and the QWERTY keyboard layout already has all the characters needed to type out C++ code without having to use the alternative tokens. Also, they would most likely bewilder readers of your code.

2.5/2 Alternative tokens
In all respects of the language, each
  alternative token behaves the same,
  respectively, as its primary token,
  except for its spelling. The set of
  alternative tokens is defined in Table
  2.

Table 2 - alternative tokens
+--------------+-----------+
| Alternative  |  Primary  |
+--------------+-----------+
|    <%        |    {      |
|    %>        |    }      |
|    <:        |    [      |
|    :>        |    ]      |
|    %:        |    #      |
|    %:%:      |    ##     |
|    and       |    &&     |
|    bitor     |    |      |
|    or        |    ||     |
|    xor       |    ^      |
|    compl     |    ~      |
|    bitand    |    &      |
|    and_eq    |    &=     |
|    or_eq     |    |=     |
|    xor_eq    |    ^=     |
|    not       |    !      |
|    not_eq    |    !=     |
+--------------+-----------+

A: they're standard C++, but with older compilers and possibly also with MSVC 10.0 (i haven't checked) you may have to include a special header, [isosomethingsomething.h]
cheers & hth.,

A: I have always messed up ^ (xor) and the ~ (two complement) operators. With the alternative tokens (that I believe should be primary ones) there is no question about what they do, yes, I agree with former posters that the textual ones are much more descriptive.
There is another possible messup using the digraphs, it is possible to forget one of the characters in ||, && that will cause subtle bugs and strange behaviours.
With the textual operators, it is much harder to make such a mistake.
I believe what I mentioned above are real valid arguments to improve code safety and clarity. Most C++ programmers SHOULD in my opinion try to get used to the textual operators in favor of the old cryptic ones.
I am surprised that so few programmers know about them. These operators should have taken over  long time ago as I see it.

A: Wow, i've been using and looking at many C++ code examples for years.. and never, until now, knew about these so I guess that means most people don't use them. So, for the sake of consistency (if you plan on working in group projects etc) it's probably best to make a habit of using && and ||.

A: It's syntactically valid, given those are required alternative tokens.

In all respects of the language, each alternative token behaves the same, respectively, as its primary token, except for its spelling.

However, some tokens are used for more than just logical or bitwise operators. So one can see the idiosyncratic:
auto& foo(auto and T) { // C++20 forwarding reference
    return T;
}

Or even
auto& foo(auto bitand T) { // lvalue reference
    return T;
}

That's gonna make one scratch their head for a while.

A: Section 2.5 of the ISO/IEC 14882:1998 standard (the original C++ standard) says:

§2.5 Alternative tokens [lex.digraph]
1 Alternative token representations are provided for some operators and punctuators16).
2 In all respects of the language, each alternative token behaves the same, respectively, as its primary token,
  except for its spelling17). The set of alternative tokens is defined in Table 2.
16) These include "digraphs" and additional reserved words. The term "digraph" (token consisting of two characters) is not perfectly
  descriptive, since one of the alternative preprocessing tokens
  is %:%: and of course several primary tokens contain two characters.
  Nonetheless, those alternative tokens that aren't lexical keywords are colloquially known as "digraphs".
17) Thus the "stringized" values (16.3.2) of [ and <: will be different, maintaining the source spelling, but the tokens can otherwise be
  freely interchanged.

                 Table 2—alternative tokens
_______________________________________________________________________________
    alternative  primary  |  alternative  primary  |  alternative  primary
     <%            {      |     and          &&    |    and_eq       &=
     %>            }      |    bitor         |     |    or_eq        |=
     <:            [      |     or           ||    |    xor_eq       ^=
     :>            ]      |     xor          ^     |     not         !
     %:            #      |    compl         ~     |    not_eq       !=
     %:%:          ##     |    bitand        &     |
_______________________________________________________________________________

There is no discussion of 'if you include some header' (though in C, you need #include <iso646.h>).  Any implementation that does not support the keywords or digraphs is not compliant with the 1998 edition, let alone later editions, of the C++ standard.

A: Obviously in regards to backward compatability the "and/or" keywords are not the issue. I would believe them to be the newer standard. It is just old programmers not understanding that some noob might have to be able to read the code and not want to look up what && means. Then again if any IT department is worth it's salt it will make the programmers conform to the standards of the company! That is my belief so (and/or) are futuristic and real possible standard going towards the future. && is backward compatable not(pun) (and/or).


text:
Q: Android - ping, Cannot resolve method "findViewById(int)" I am absolute beginner in Android programming and i have following code:
public class First_Fragment extends Fragment {

    View myView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.first_layout, container, false);
        return myView;

    }

    public boolean executeCommand(){
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try
        {
            Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue " + mExitValue);
            if(mExitValue==0){
                return true;
            }else{
                return false;
            }

            TextView tv = (TextView)findViewById(R.id.textView2);
            tv.setText(mExitValue);

        }
        catch (InterruptedException ignore)
        {
            ignore.printStackTrace();
            System.out.println(" Exception:"+ignore);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println(" Exception:"+e);
        }
        return false;

    }

}

I have few questions:
1) Why I have error "Cannot resolve method "findViewById(int)"" in part
TextView tv = (TextView)findViewById(R.id.textView2);

changing it to "...view.findViewById(..." does not work ("Cannot resolve method "view(int)""
2) Is that right when I want to have that "label" as text output for "ping"
3) How to export only that part with "ping" and if the server have no response (timed out or etc.) it will change text of that label to something else etc "server down")
I will be really happy if you help me with this, I just want to say again, that I am absolute beginner, so please dont blame me. Thank you!

A: Try this:
 public class First_Fragment extends Fragment {

        View myView;
        TextView tv;
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            myView = inflater.inflate(R.layout.first_layout, container, false);
         tv = (TextView) myView.findViewById(R.id.textView2);
            return myView;

        }

        public boolean executeCommand(){
            System.out.println("executeCommand");
            Runtime runtime = Runtime.getRuntime();
            try
            {
                Process  mIpAddrProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
                int mExitValue = mIpAddrProcess.waitFor();
                System.out.println(" mExitValue " + mExitValue);
                if(mExitValue==0){
                    return true;
                }else{
                    return false;
                }

                tv.setText(mExitValue);

            }
            catch (InterruptedException ignore)
            {
                ignore.printStackTrace();
                System.out.println(" Exception:"+ignore);
            }
            catch (IOException e)
            {
                e.printStackTrace();
                System.out.println(" Exception:"+e);
            }
            return false;

        }

    }

In addition fragment needs to define the view whose component it is using. Here myView is the view in which layout is inflated and hence we need to define that fragment is using textview of myView by doing:
tv = (TextView) myView.findViewById(R.id.textView2);


text:
Q: doxygen generate doc for machine read Is it possible to use doxygen generate a machine readable metadata, like json, I googled, but found nothing.

... generate an on-line documentation browser (in HTML) and/or an off-line reference manual (in LaTeX) from a set of documented source files. There is also support for generating output in RTF (MS-Word), PostScript, hyperlinked PDF, compressed HTML, DocBook and Unix man pages.

There must some internal abstract metadata to support doxygen. I want to use the doxygen's metadata so I don't have to parse the source code to get something like methods, args,from doxygen, I also got comments for free.
With these data I can generate glue code for some other languages. So, how can I get these metadata out of doxygen ?

A: doxygen can also generate XML.
The schema can be found in the source code:
https://github.com/doxygen/doxygen/blob/master/templates/xml/compound.xsd
The xsd is also available in the generated output, in the xml directory.
With an XSLT transformation, you can process the generated XML and extract the data needed.


text:
Q: E2E testing: Karma+JQuery vs Protractor Question
In terms of e2e testing, what can't we do with Karma and JQuery that is possible with Protractor?
Explanation
I'm currently building a testing framework for my JavaScript application.
I'm using Karma for Unit Testing and Protractor for E2E Testing as suggested by many people.
I'm aware of the conceptual differences between unit testing and e2e testing, but, in the context of JavaScript, I don't clearly understand why we need framework like Protractor.
As far as I know, the point of e2e testing is to use the application as a simple end-user. For that, tools like Protractor use a webdriver to interact with a browser and let us simulate some user events (clicking on element, filling forms...).
The thing is, why can't we simply do this by using Karma and JQuery?
Indeed, JQuery comes with lots of methods to interact with a DOM element (trigger event, get/set element's property, set value to an input...). Furthermore, it provides selectors which make the selection of DOM element very easy.
From my point of view, Karma and JQuery has (almost) everything needed for e2e testing (if we don't take care of the browser's window's operations available in Protractor which enable for example to set the window size or location).
I'm obviously missing something, any clarification will be helpful.

A: Using Jquery and Karma the way you would, is a behavior-driven-test but not an end-to-end test.
With Jquery and Karma, you can't detect cross-browser issues like you would in protractor. Protractor on the other hand runs your tests as if it was an end-user. It literally opens the browser you want and tests your application in that browser.


text:
Q: Javascript - Getting document width I'd like to get the document's width with javascript (jQuery available), which I could achieve simply with document.width. The problem comes up when the contents are positioned with a negative value, because document.width will retrieve the width less that value (you can see this behavior in http://jsfiddle.net/McgzK/1/). So, is there a way I can get the document's width straight forward, or should I do something like document.width - parseInt($(container).css('left'))?

A: There is no straight forward way to get that width. This width does not make any sense. document.width is the value of documents width. If you put something outside document layout its not included in documents width as its not in the document. So for your Total width you have to add that portion.
Use the scrollWidth property of your element and add absolute left value of css position.
See http://jsfiddle.net/McgzK/11/
Note:

*

*if you want the width of content use scrollWidth property.

*If you want to get the width of the element  use offsetWidth.

A: Try setting your body width to 100% in your CSS, then use jQuery to get the width of the body rather than the document.


text:
Q: How can I disable Alt-Enter in IE? As the default behavior of IE is to switch to the full screen mode on Alt-Enter command. I've to avoid this and have to attach a custom behavior.
Is it doable?

A: Not in JavaScript, no.
This is a behaviour of the application, which you don't really have control over (aside from browser extensions, and such).
You could try catching the key presses on your page, but it wouldn't prevent the user from easily circumventing it.
See http://www.webonweboff.com/tips/js/event_key_codes.aspx for a list of the character codes for keys. I'm pretty sure it's not reliable for catching combinations of key presses.
Besides, Alt+Enter in IE results in an expected behaviour and you should not try to override this via a webpage.

A: Since you can't beat 'em, join 'em.  Meaning, since you can catch the event but can't stop it, how about you just run the same command in a timeout after the user presses alt+enter?
Example:
<script type="text/javascript">

document.onkeydown = handleHotKeys;

function handleHotKeys(e) {
    var keynum = getKeyCode(e);
    var e = e || window.event;
    if (keynum==13 && e.altKey) { // handle enter+alt
        setTimeout("toggleFullscreenMode",100);
    }

}
function getKeyCode(e){
    if (!e)  { // IE
        e=window.event;
        return e.keyCode;
    } else { // Netscape/Firefox/Opera
        return e.which;
    }
}

function toggleFullscreenMode() {
  var obj = new ActiveXObject("Wscript.shell");
  obj.SendKeys("{F11}");
}
</script>

DISCLAIMER:  Tested in IE8. You will have to look at the browser and version to get this to work for the specific version of the browser you are targeting.  This also assumes that the user will have javascript and activex objects enabled.


text:
Q: get a href attribute and set this attribute to other div I have 3 classes with such a structure (this is slider in my web app):

/div>

I want to get href attribute of a and set a href atribute with this url to dig-pub. It is very important to me that this is the link (which class I clicked), because 3 classes have different links.
   I would like to use jQuery.

A: You bind a click event to your anchor tag. you'll need to assign a class to the anchor tag too if you have many on the page so replace 'className' with your class name. I'm not sure how you want to assign it to the div so I've done it as a data-attribute as this is the conventional way to go.
$('a.className').on('click', function (){
    $(this).closest('.dig-pub').attr('data-href', $(this).attr('href'));
});

A: First, add an id to the link and the div (easier to fetch the elements)

Then, get the href
var href = $('#id').attr('href');

Set the value to the div
$('#dig-pub').html(href);

However, you could have find this easily on JQuery documentation.

A: (Don't forget to close the div on line 3 in your snippet)
jQuery('.dig-pub').on('click', function() {
   url = jQuery(this).parent().find('a').attr('href');
   jQuery(location).attr(url);
});

https://codepen.io/Kidkie/pen/gdaJjZ


text:
Q: create global variables from column names and row values table clients has 29 columns.
as an example, wi'll take five of them:
earth, sun, moon, jupiter, venus
row id=1 has the following values:
blue, gold, silver, lessons, arts
function giveme_vars($id){
    global $db;
    $sql = "select * from clients where id = :aid";
    $st = $db->prepare($sql);
    $st->execute([
        ":aid" => $id
    ]);
    $row = $st->fetch();
    // here I need something like this:
    foreach($row as $key=>$val){
        $variable_key = $row_value;
        //then make all of them global;
    }
}

As a result I'm expecting:
$earth = 'blue';
$sun = 'gold';
$mon = 'silver';
$jupiter = 'lessons';
$venus = 'arts';

All of the variables should be global i.e. accessible for all files on the server.
Any help?

A: Like your first commentor pointed out: this post clarifies it
 class global{
        static $variable= "something";
    }

access and use:
function dosomething(){
    echo global::$var;
}


text:
Q: Flutter: How to adjust the size of ElevatedButton which is a child element of ListView. And why we can use Align widget at this situation? import 'package:flutter/material.dart';

void main(){
  runApp(MaterialApp(home:MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:ListView(
        children:[
          SizedBox(height:50.0,),
          SizedBox(
            width:200.0,
            height:200.0,
            child: ElevatedButton(
              child:Text('push'),
              onPressed:(){},

            ),
          ),
        ],
      ),
    );
  }
}

The first question: Why can't the width of the ElevatedButton, a child element of ListView, be adjusted using SizedBox in the above code?
Even though the width is specified as 200.0 in SizedBox, the button expands to the full width of the screen.
(The height of the button can be adjusted.)

The second question: as a solution to the above situation, I was able to adjust the width of the button using margin as below.
          Container(
            margin:EdgeInsets.symmetric(horizontal: 30.0,),
            child: SizedBox(
              width:200.0,
              height:200.0,
              child: ElevatedButton(
                child:Text('push'),
                onPressed:(){},
              ),
            ),
          ),

This works, but using margin doesn't seem to be a very intuitive way to specify the size.
So, as a result of searching for other methods, it became possible to adjust the width by wrapping with Align as shown below.
          Align(
            child: SizedBox(
              width:300.0,
              height:200.0,
              child: ElevatedButton(
                child:Text('push'),
                onPressed:(){},
              ),
            ),
          ),

I think this method is more intuitive, but I'm not sure why we can adjust the width by wrapping it with Align.
At this point, my perception is that the Align widget is generally used to specify the on-screen position of child widgets.

A: Its Default behavior of ListView. it will take the full width/height if you set the axis as vertical/horizontal.
By default, the axis is set as vertical.
For that, you can use Column with SingleChildScrollView
SingleChildScrollView(
  child: Column(
    children: [
      SizedBox(
        height: 50.0,
      ),
      SizedBox(
        width: 200.0,
        height: 200.0,
        child: ElevatedButton(
          child: Text('push'),
          onPressed: () {},
        ),
      ),
    ],
  ),
)


text:
Q: Same Shortcode not executing second time I am developing a theme for our organisation, I have developed the following shortcode that generates a card view.
public function omnizzCard( $atts, $content = "" )
{
    $atts = shortcode_atts( array(
        'width' => '20 rem',
        'icon' => 'face',
        'title' => 'Card title'
    ), $atts, 'omnizz_card' );

    ob_start();
    include_once('shortcode_templates/card.php');
    return ob_get_clean();
}

shortcode_templates/Card.php

            <?php echo $atts['icon'] ?>

<?php echo $atts['title'] ?>

<?php echo do_shortcode( $content ) ?>

I am applying the shortcode like following:
But it showing single card not the second.
I also checked to inspect element on the chrome, its only displaying the single card element not the second one.
Can anyone help me to find out what wrong i have done?


text:
Q: Is it conventional to raise a NotImplementedError for methods whose implementation is pending, but not planned to be abstract? I like to raise a NotImplementedError for any method that I want to implement, but where I haven't gotten around to doing it yet.  I might already have a partial implementation, but prepend it with raise NotImplementedError() because I don't like it yet.  On the other hand, I also like to stick to conventions, because this will make it easier for other people to maintain my code, and conventions might exist for a good reason.
However Pythons documentation for NotImplementedError states:

This exception is derived from RuntimeError. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.

That is a much more specific, formal use case than the one I describe.  Is it a good, conventional style to raise a NotImplementedError simply to indicate that this part of the API is a work in progress?  If not, is there a different standardised way of indicating this?

A: This will be understood, whether you do it or not should depend on local (team or company) conventions.  Note that it makes less sense in the context of TDD as the TEST should be what determines that the method isn't implemented.
The short version is: use if you and your team consider it appropriate.

A: It's worth noting that, while the Python documentation provides a use case (and probably the canonical one) for this exception, it doesn't specifically exclude its use in other scenarios.
I would consider it appropriate to raise a NotImplementedError exception if you haven't overridden a method in a base class yet (to satisfy the "interface").
A cursory check on Google suggests that people will understand what you mean if you use the exception in this fashion.  There are no side effects or unintended consequences that I know of; the method will simply throw an exception if it is called, and it will throw an exception that is well-understood by everyone.

The documentation for Python 3 reflects this exact usage:

In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added. [Emphasis added]

A: It seems that NotImplementedError is usually being raised for Python feature developments itself, like the following:
@classmethod
def fromkeys(cls, iterable, v=None):
    # There is no equivalent method for counters because setting v=1
    # means that no element can have a count greater than one.
    raise NotImplementedError(
        'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

Documetation

fromkeys(iterable)
This class method is not implemented for Counter objects.

Source
Collections.Counter.fromkeys


text:
Q: How can I optimize linux for encoding lots of video or a set of the same cpu intensive tasks? I have a set of 4-5 machines which almost exclusively encode video all day, and sometimes all night too.  I've searched many times to find ways to optimize them for this purpose, but not had any success.
My premise:  I should be able to use nearly all of my cpu for video encoding, if and only if, I am running multiple encoding processes simultaneously, which I am.
The Problem: ( from 'top' )

Tasks: 382 total,   2 running, 380 sleeping,   0 stopped,   0 zombie
%Cpu(s): 51.6 us, 36.8 sy,  0.0 ni,  9.6 id,  0.0 wa,  2.0 hi,  0.0 si,  0.0 st
KiB Mem:  16425680 total, 16171664 used,   254016 free,    30492 buffers
KiB Swap: 16769020 total,   406056 used, 16362964 free. 15198692 cached Mem

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
31308 root      20   0  486568  26000   5560 S  92.2  0.2 188:10.72 avconv
10340 root      20   0  475832  19920   5532 S  91.2  0.1  13:40.42 avconv
12547 root      20   0  473832  23672   5528 S  89.9  0.1   5:40.23 avconv
 8179 root      20   0  477132  21200   5560 S  89.2  0.1  71:50.15 avconv
 9059 root      20   0  472776  17960   5540 S  89.2  0.1  48:12.62 avconv
 9798 root      20   0  477812  16976   5532 S  88.9  0.1  25:23.15 avconv
 8725 root      20   0  476068  21696   5560 S  87.2  0.1  62:12.02 avconv
12657 root      20   0  472332  22012   5524 S  86.9  0.1   6:21.28 avconv
12915 root      20   0  473732  41888   5516 S  86.6  0.3   5:22.63 avconv
 8578 root      20   0  476840  24100   5536 S  85.6  0.1  63:17.07 avconv
 7822 root      20   0  472740  18940   5536 S  85.2  0.1  75:22.04 avconv
 9948 root      20   0  485420  18116   5560 S  84.9  0.1  22:18.23 avconv
 7356 root      20   0  476744  20084   5560 S  84.6  0.1  92:31.91 avconv
 9425 root      20   0  471096  19684   5552 S  82.9  0.1  37:48.28 avconv
12464 root      20   0  475004  24304   5532 R  81.6  0.1   6:30.16 avconv

Despite encoding 14 different video files at once, the cpu usage hovers at around only 50-55%.  If I am running less streams at once, the individual streams will run up to about 400 %CPU, where as pictured above they only use about 80-90 %CPU.
This is the only thing I want this box to do, is it possible to make more use of the CPU power or is my premise flawed?
I have thus far experimented with renice, to utterly no effect.  I set NI of -20 and 19 it made no greater or less cpu usage overall or on individual encodes.
I did some reading about vm.swappiness, but I didn't get a clear grasp for my use case if more or less swappiness would be better.  Could this increase performance?
More details: The machine I'm including top from is a Dell R900 running Ubuntu 14.04. cat /proc/cpuinfo lists 16 Intel(R) Xeon(R) CPU E7330  @ 2.40GHz processors and cat /proc/meminfo 16 Gb Ram.  The other machines in the group are similar and show the same behavior.  All of this encoding is DV video to Mpeg2 video, sometimes we encode other kinds of video too.  The source for these encodes are on a networked raid that is not writing anything as of the top post above, and gets read speeds in the 300+Mb/s.  The destination is also networked raids, not quite as fast, but the resulting mpeg data is much smaller than the input data.

A: First a high end GPU will boost encoding by orders of magnitude.  Usually a high end video card will reduce rendering from hours to minutes.  You may need a NVIDIA GPU.
'-hwaccel_device[:stream_specifier] hwaccel_device (input,per-stream)'

    Select a device to use for hardware acceleration.

    This option only makes sense when the '-hwaccel' option is also specified. Its exact meaning depends on the specific hardware acceleration method chosen.
    'vdpau'

        For VDPAU, this option specifies the X11 display/screen to use. If this option is not specified, the value of the DISPLAY environment variable is used
    'dxva2'

        For DXVA2, this option should contain the number of the display adapter to use. If this option is not specified, the default adapter is used.

In addition you need this for the CPU
'-threads[:stream_specifier] integer (input/output,video)'

    Possible values:

    'auto'

        autodetect a suitable number of threads to use


text:
Q: пытаюсь установить wine на chromebook, но выдает какую-ту непонятную мне ошибку код:
~$ winecfg
002c:fixme:winediag:LdrInitializeThunk wine-staging 5.17 is a testing version containing experimental patches.
002c:fixme:winediag:LdrInitializeThunk Please mention your exact version when filing bug reports on winehq.org.
0044:err:winediag:nodrv_CreateWindow Application tried to create a window, but no driver could be loaded.
0044:err:winediag:nodrv_CreateWindow Make sure that your X server is running and that $DISPLAY is set correctly.
0044:err:explorer:initialize_display_settings Failed to query current display settings for L"\\.\DISPLAY1".
0044:err:appbar:initialize_appbar Could not create appbar message window
0044:err:ole:apartment_createwindowifneeded CreateWindow failed with error 0
0044:err:ole:apartment_createwindowifneeded CreateWindow failed with error 0
0044:err:ole:apartment_createwindowifneeded CreateWindow failed with error 0
Wine cannot find the ncurses library (libncurses.so.5).
00e8:err:winediag:nodrv_CreateWindow Application tried to create a window, but no driver could be loaded.
00e8:err:winediag:nodrv_CreateWindow Make sure that your X server is running and that $DISPLAY is set correctly.
помогите пожалуйста


text:
Q: How can I download a Unicode file and load it in a TTreeView? I need to download a file of TreeView in Unicode using idHTTP (String := idHTTP.Get). After downloading, I need do something with the string and then put it in a TTreeView. I'm using Delphi 2010.
s:=form2.idhttp1.Get(Adres+'list.ttt');
....
StrStream:=TStringStream.Create(s,t encoding.Unicode);
form2.TreeView1.LoadFromStream(strstream);
StrStream.Free;

I cannot see Unicode in S or TreeView1. I only see Unicode in S if I try to download not list.ttt but list.html. What do I need to set in idHTTP or something else to work properly?

A: How to make it work with TIdHttp
Don't use a TStringStream, use a TMemoryStream so you don't get any re-encodings of the contents. Example:
var ResponseStream: TMemoryStream;
begin
  ResponseStream := TMemoryStream.Create;
  try
    H.Get(URL, ResponseStream);
    ResponseStream.Position := 0;
    Tree.LoadFromStream(ResponseStream);
  finally ResponseStream.Free;
  end;
end;

A: @Michael - I gather that you do see data in S, but it is ansiString and not Unicode, correct? Are you sure your source 'list.ttt' is Unicode? Have you tried declaring s explicitely as a unicodeString or using the unicodeString function? Just some things to consider - not really an answer. HTH


text:
Q: Sensitivity and specificity changes using a single threshold and a gradient of thresholds at 0.5 using pROC in R I am trying to calculate ROC for a model of multi-class image. But since I didn't find any best way for multi-class classification, I have converted it to binary class. I have 31 classes of image. Using binary methods I am trying to find ROC of each 31 classes individually.
    df <- read.xlsx("data.xlsx",sheetName = 1,header = F)
    dn <- as.vector(df$X1) # 31 class
    model_info <- read.csv("all_new.csv",stringsAsFactors = F) # details of
    model output (Actual labels, Model labels, probabablity values)

head(model_info)
           Actual_labels             App_labels                      X1st
1 tinea cruris and corporis tinea cruris and corporis tinea cruris and corporis
2 tinea cruris and corporis tinea cruris and corporis tinea cruris and corporis
3 tinea cruris and corporis              no diagnosis             acne vulgaris
4                    eczema                    eczema                    eczema
5                    eczema              no diagnosis                 psoriasis
6              folliculitis    impetigo and pyodermas    impetigo and pyodermas
                       X2nd                      X3rd X.st.. X2nd.. X3rd..
1                 psoriasis             herpes zoster   0.89   0.05   0.03
2                 psoriasis                    eczema   0.89   0.03   0.02
3                 psoriasis     molluscum contagiosum   0.29   0.16   0.14
4 tinea cruris and corporis                 psoriasis   0.62   0.09   0.08
5                   melasma tinea cruris and corporis   0.27   0.27   0.25
6             acne vulgaris                 psoriasis   0.73   0.07   0.03

head(dn)
[1] "acne vulgaris"      "alopecia areata"    "anogenital warts"
[4] "bullous pemphigoid" "candidiasis"        "chicken pox"

App_call function basically converts the probability values to 0 or 1 based on whether model call is true or not
app_call <- function(cut_off, category){
            labels_thr <- rep(0,nrow(app_res))
            ind <- which(model_info$X.st.. >= cut_off) # index of instances
             above threshold
            true_val <- which(app_res$App.Diagnosis[ind] == category) # index of instances where actual labels are similar to model labels for 1st class out of 31 class.
            labels_thr[ind[true_val]] <- 1
            return(labels_thr)}

    index0 <- grep(pattern = paste0("^",dn[i],"$"),x = model_info$Actual_labels)

    actual_labels <- rep(0,nrow(model_info))

    if(length(index)>= 1){
        actual_labels[index0] <- 1
        actual_labels[-index0] <- 0}

    app_labels <- app_call(cut_off = 0.5,category  = dn[i])
    res <- roc(actual_labels,app_labels)
    res1 <-   roc(actual_labels,model_info$X.st..)

dput(actual_labels)
 c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0,
0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,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 0.34, 0.34, 0.6, 0.24, 0.49,
0.47, 0.35, 0.62, 0.76, 0.67, 0.51, 0.48, 0.72, 0.81, 0.9, 0.89,
0.92, 0.94, 0.2, 0.87, 0.98, 0.99, 0.98, 0.85, 0.89, 0.87, 0.62,
0.19, 0.86, 0.49, 0.5, 0.2, 0.48, 0.51, 0.49, 0.3, 0.11, 0.88,
0.35, 0.81, 0.59, 0.67, 0.31, 0.94, 0.22, 0.4, 0.52, 0.21, 0.31,
0.19, 0.79, 0.64, 0.33, 0.27, 0.19, 0.74, 0.78, 0.41, 0.35, 0.8,
0.39, 0.28, 0.92, 0.37, 0.66, 0.66, 0.44, 0.77, 0.49, 0.27, 0.32,
0.65, 0.21, 0.95, 0.51, 0.16, 0.33, 0.85, 0.26, 0.61, 0.25, 0.57,
0.26, 0.21, 0.45, 0.44, 0.83, 0.31, 0.35, 0.91, 0.34, 0.89, 0.77,
0.56, 0.31, 0.26, 0.84, 0.15, 0.27, 0.47, 0.73, 0.28, 0.44, 0.52,
0.65, 0.72, 0.38, 0.99, 0.46, 0.35, 0.25, 0.42, 0.82, 0.24, 0.56,
0.31, 0.52, 0.91, 0.94, 0.68, 0.21, 0.28, 0.68, 0.67, 0.61, 0.6,
0.43, 0.37, 0.28, 0.28, 0.24, 0.4, 0.92, 0.9, 0.45, 0.96, 0.53,
0.72, 0.26, 0.47, 0.47, 0.97, 0.49, 0.25, 0.51, 0.3, 0.92, 0.43,
0.33, 0.95, 0.25, 0.51, 0.98, 0.23, 0.51, 0.75, 0.84, 0.54, 0.5,
0.54, 0.33, 0.64, 0.29, 0.93, 0.13, 0.27, 0.93, 0.59, 0.27, 0.81,
0.57, 0.59, 0.47, 0.24, 0.53, 0.53, 0.43, 0.24, 0.94, 0.6, 0.7,
0.23, 0.69, 0.95, 0.95, 0.49, 0.73, 0.31, 0.94, 0.15, 0.85, 0.92,
0.34, 0.95, 0.91, 0.36, 0.55, 0.55, 0.29, 0.86, 0.31, 0.48, 0.48,
0.45, 0.5, 0.49, 0.3, 0.33, 0.39, 0.8, 0.42, 0.51, 0.52, 0.66,
0.19, 0.58, 0.94, 0.51, 0.39, 0.84, 0.95, 0.85, 0.72, 0.35, 0.83,
0.5, 0.91, 0.83, 0.61, 0.79, 0.5, 0.87, 0.3, 0.5, 0.53, 0.22,
0.82, 0.74, 0.73, 0.65, 0.88, 0.31, 0.75, 0.74, 0.92, 0.38, 0.47,
0.26, 0.77, 0.78, 0.82, 0.59, 0.59, 0.33, 0.67, 0.31, 0.67, 0.44,
0.77, 0.61, 0.44, 0.77, 0.83, 0.58, 0.6, 0.78, 0.76, 0.47, 0.72,
0.47, 0.29, 0.14, 0.32, 0.17, 0.56, 0.68, 0.3, 0.46, 0.56, 0.68,
0.61, 0.7, 0.23, 0.39, 0.79, 0.38, 0.32, 0.58, 0.46, 0.5, 0.57,
0.93, 0.4, 0.37, 0.75, 0.76, 0.36, 0.84, 0.19, 0.18, 0.94, 0.53,
0.53, 0.24, 0.23, 0.51, 0.53, 0.84, 0.23, 0.44, 0.85, 0.53, 0.23,
0.56, 0.26, 0.38, 0.78, 0.93, 0.65, 0.22, 0.52, 0.35, 0.47, 0.33,
0.31, 0.65, 0.72, 0.46, 0.44, 0.74, 0.92, 0.99, 0.72, 0.41, 0.18,
0.85, 0.89, 0.31, 0.4, 0.98, 0.46, 0.16, 0.58, 0.25, 0.21, 0.32,
0.43, 0.56, 0.34, 0.35, 0.7, 0.43, 0.17, 0.25, 0.33, 0.44, 0.44,
0.58, 0.74, 0.37, 0.68, 0.52, 0.8, 0.96, 0.52, 0.25, 0.81, 0.94,
1, 0.58, 0.42, 0.46, 0.41, 0.18, 0.37, 0.9, 0.54, 0.29, 0.38,
0.38, 0.53, 0.99, 0.57, 0.44, 0.33, 0.45, 0.95, 0.85, 0.75, 0.19,
0.97, 0.27, 0.94, 0.77, 0.79, 0.57, 0.33, 0.98, 0.47, 0.55, 0.27,
0.43, 0.66, 1, 0.62, 0.34, 0.81, 0.4, 0.56, 0.33, 0.25, 0.4,
0.25, 0.91, 0.28, 0.4, 0.73, 0.32, 0.49, 0.37, 0.19, 0.35, 0.29,
0.77, 0.36, 0.31, 0.85, 0.33, 0.61, 0.63, 0.41, 0.98, 0.28, 0.31,
0.91, 0.34, 0.24, 0.82, 0.46, 0.5, 0.39, 0.72, 0.67, 0.51, 0.41,
0.81, 0.74, 0.5, 0.97, 0.65, 0.44, 0.71, 0.35, 0.84, 0.97, 0.42,
0.75, 0.91, 0.61, 0.94, 0.48, 0.42, 0.63, 0.81, 0.83, 0.66, 0.55,
0.61, 0.41, 0.63, 1, 0.63, 0.41, 0.75, 0.27, 0.28, 0.24, 0.55,
0.35, 0.85, 0.97, 0.64, 0.79, 0.92, 0.47, 0.81, 0.23, 0.16, 0.75,
0.12, 0.43, 0.18, 0.69, 0.21, 0.39, 0.19, 0.85, 0.57, 0.97, 0.56,
0.81, 0.13, 0.4, 0.47, 0.95, 0.43, 0.9, 0.67, 0.36, 0.38, 0.83,
0.97, 0.48, 0.93, 0.67, 0.44, 0.34, 0.83, 0.77, 0.39, 0.56, 0.85,
0.55, 0.22, 0.48, 0.46, 0.59, 0.89, 0.99, 0.57, 0.96, 0.97, 0.95,
0.98, 0.24, 0.89, 0.5, 0.94, 0.6, 0.41, 0.71, 0.5, 0.2, 0.96,
0.18, 0.93, 0.92, 0.85, 0.92, 0.82, 0.48, 0.62, 0.53, 0.59, 0.38,
0.8, 0.49, 0.91, 0.58, 0.94, 0.68, 0.15, 0.96, 0.98, 0.89, 0.84,
0.5, 0.88, 0.29, 0.24, 0.31, 0.29, 0.33, 0.49, 0.33, 0.76, 0.54,
0.88, 0.78, 0.26, 0.52, 0.75, 0.97, 0.93, 0.27, 0.69, 0.19, 0.69,
0.2, 0.21, 0.84, 0.31, 0.19, 0.8, 0.6, 0.19, 0.51, 0.98, 0.27,
0.39, 0.77, 0.95, 0.73, 0.28, 0.79, 0.19, 0.98, 0.77, 0.31, 0.84,
0.35, 0.19, 0.26, 0.82, 0.63, 0.38, 0.38, 0.26, 0.63, 0.65, 0.55,
0.88, 0.6, 0.71, 0.85, 0.99, 0.28, 0.42, 0.65, 0.58, 0.97, 0.35,
0.36, 0.32, 0.79, 0.68, 0.39, 0.45, 0.71, 0.98, 0.34, 0.62, 0.24,
0.55, 0.43, 0.95, 0.32, 0.6, 0.63, 0.98, 0.2, 0.31, 0.9, 0.3,
0.32, 0.37, 0.52, 0.64, 0.9, 0.22, 0.31, 0.39, 0.21, 0.93, 0.64,
0.4, 0.96, 0.31, 0.46, 0.86, 0.56, 0.99, 0.83, 0.87, 0.36, 0.59,
0.98, 0.72, 0.21, 0.52, 0.17, 0.21, 0.42, 0.97, 0.34, 0.96, 0.18,
0.63, 0.45, 0.36, 0.31, 0.48, 0.94, 0.86, 0.16, 0.32, 0.97, 0.29,
0.9, 0.38, 0.88, 0.6, 0.17, 0.19, 0.44, 0.98, 0.35, 0.36, 0.2,
0.39, 0.53, 0.35, 0.57, 0.18, 0.26, 0.17, 0.77, 0.51, 1, 0.17,
0.57, 0.48, 0.58, 0.25, 0.32, 0.33, 0.76, 0.16, 0.13, 0.46, 0.44,
0.31, 0.56, 0.46, 0.6, 0.17, 0.36, 0.34, 0.44, 0.43, 0.86, 0.86,
0.44, 0.34, 0.92, 0.32, 0.78, 0.21, 0.46, 0.92, 0.27, 0.98, 0.52,
0.34, 0.27, 0.59, 0.45, 0.58, 0.27, 0.48, 0.21, 0.24, 0.29, 0.89,
0.25, 0.33, 0.96, 0.56, 0.29, 0.97, 0.98, 0.59, 0.28, 0.22, 0.76,
0.91, 0.92, 0.91, 0.94, 0.83, 0.48, 0.53, 0.56, 0.5, 0.75, 0.4,
0.98, 0.6, 0.74, 0.66, 0.97, 0.62, 0.99, 0.39, 0.89, 0.86, 0.66,
0.92, 0.34, 0.99, 0.69, 0.71, 0.8, 0.47, 0.5, 0.83, 0.83, 0.41,
0.72, 0.98, 0.76, 0.65, 0.71, 0.9, 0.9, 1, 0.4, 0.46, 0.35, 0.72,
0.92, 0.74, 0.44, 0.67, 0.97, 0.88, 0.84, 0.71, 0.45, 0.78, 0.9,
0.72, 0.57, 0.68, 0.85, 0.84, 0.46, 0.91, 0.53, 0.96, 0.49, 0.93,
0.49, 0.37, 0.95, 0.47, 0.87, 0.49, 0.58, 0.64, 0.84, 0.8, 0.49,
0.67, 0.75, 0.44, 0.87, 0.71, 0.47, 0.46, 0.83, 0.74, 0.99, 0.86,
0.64, 0.74, 0.43, 0.44, 0.57, 0.89, 0.67, 0.59, 0.89, 0.45, 0.62,
0.81, 0.93, 0.81, 0.98, 0.95, 0.63, 0.64, 0.96, 0.55, 0.49, 0.59,
0.47, 0.42, 0.6, 0.51, 0.4, 0.3, 0.29, 0.45, 0.94, 0.29, 0.33,
0.14, 0.71, 0.41, 0.6, 0.31, 0.95, 0.94, 0.87, 0.8, 0.53, 0.66,
0.71, 0.19, 0.49, 0.97, 0.48, 0.43, 0.38, 0.4, 0.22, 0.38, 0.27,
0.25, 0.45, 0.75, 0.38, 0.23, 0.92, 0.7, 0.68, 0.17, 0.39, 0.65,
0.38, 0.39, 0.21, 0.28, 0.55, 0.89, 0.24, 0.34, 0.92, 0.31, 0.64,
0.86, 0.94, 0.28, 0.43, 0.44, 0.82, 0.23, 0.81, 0.71, 0.53, 0.96,
0.9, 0.55, 0.83, 0.64, 0.51, 0.32, 0.66, 0.45, 0.72, 0.28, 0.34,
0.98, 0.76, 0.52, 0.95, 0.83, 0.47, 0.9, 0.31, 0.23, 0.61, 0.94,
0.61, 0.42, 0.34, 0.55, 0.33, 0.93, 0.24, 0.51, 0.65, 0.17, 0.81,
0.68, 0.51, 0.78, 0.37, 0.37, 0.99, 0.94, 0.64, 0.59, 0.61, 0.9,
0.88, 0.64, 0.49, 0.09, 0.51, NA, 0.86, 0.45, 0.61, 0.24, 0.85,
0.26, 0.29, 0.21, 0.66, 0.26, 0.47, 0.19, 0.99, 0.51, 0.91, 0.37,
0.56, 0.71, 0.47, 0.44, 0.48, 0.52, 0.22, 0.52, 0.29, 0.46, 0.54,
0.94, 0.24, 0.24, 0.47, 0.37, 0.9, 0.79, 0.81, 0.41, 0.38, 0.71,
0.34, 0.46, 0.23, 0.54, 0.43, 0.85, 0.56, 0.26, 0.9, 0.25, 0.3,
0.39, 0.89, 0.38, 0.18, 0.78, 0.37, 0.45, 0.51, 0.8, 0.61, 0.52,
0.84, 0.4, 0.31, 0.28, 0.24, 0.23, 0.43, 0.77, 0.78, 0.95, 0.9,
0.81, 0.15, 0.77, 0.77, 0.87, 0.75, 0.16, 0.49, 0.23, 0.93, 0.45,
0.33, 0.75, 0.32, 0.75, 0.41, 0.24, 0.46, 0.17, 0.41, 0.45, 0.48,
0.15, 0.66, 0.53, 0.75, 0.57, 0.46, 0.78, 0.24, 0.29, 0.95, 0.77,
0.66, 0.94, 0.27, 0.29, 0.58, 0.6, 0.46, 0.58, 0.84, 0.69, 0.47,
0.45, 0.48, 0.35, 0.89, 0.98, 0.93, 0.2, 0.94, 0.91, 0.75, 0.5,
0.44, 0.69, 0.8, 0.76, 0.85, 0.84, 0.72, 0.25, 0.73, 0.26, 0.93,
0.15, 0.33, 0.3, 0.6, 0.24, 0.21, 0.28, 0.51, 0.79, 0.77, 0.85,
0.52, 0.39, 0.68, 0.83, 0.36, 0.15, 0.87, 0.55)

res1 = roc(actual_labels,app_labels)
res2= roc(actual_labels,model_info$X.st..)

The calls in the actual label class where it is "1" and have have a probablity threshold (model_info$X.st..) value more than 0.5 is named as "1" for app_labels and rest all zero
Both res1 and res2 have different values for sensitivitiy and specificity.

A: A ROC curve shows the sensitivity and specificity tradeoff as the decision threshold of a classifier is varied. Typically ROC curve functions expect to get the prediction and the truth value as input.
This is exactly what you do when you run:
res2= roc(actual_labels,model_info$X.st..)

However your app_labels is of a very different nature: you have already merged in the "correct classification" aspect, which makes it more like a flattened contingency table than the "predictions" the ROC function expects. So you can no longer use a regular ROC function and need to calculate the sensitivity and specificity manually.
TP <- sum(app_labels & actual_labels)
TN <- sum(app_labels & !(actual_labels))
FP <- sum(!(app_labels) & !(actual_labels))
FN <- sum(!(app_labels) & actual_labels)

# Sensitivity:
TP / (TP+FN)

# Specificity:
TN / (TN + FP)


text:
Q: Authentication Required for jqueryrotate.googlecode.com I have a web page that uses this link below, now every time I access the page a dialog box shows up asking for authentication with user name and password. I never had that hapenning before. Is this a bug or something new, has anyone seeing this before, is there a way to fix this?
http://jqueryrotate.googlecode.com/svn/trunk/jQueryRotate.js
Thank you!

A: I believe this behaviour occurs when the script has been deleted or no longer located at that address or permissions deny public access.
I would use a locally hosted copy, if you have one, or a similar script such as https://github.com/jcubic/jquery.rotate.
Edit: Found the author of the script your using on Github
https://github.com/wilq32
https://github.com/wilq32/jqueryrotate
https://raw.githubusercontent.com/wilq32/jqueryrotate/master/jQueryRotate.js

A: Just in case - a new webpage for plugin is here: http://jqueryrotate.com/
It's open source project so please don't flood my server and download plugin instead of serving it directly from my server. Thanks!

A: Find library and download local web site folder. :)
I got the same problem

A: Yup the SVN Author for that script changed the access permissions.
You will need to find a new link or download a copy of the plugin and link to it relatively on your site rather than externally linking it.
This same issue hit five of my clients websites today, rather embarrassing for developers and businesses unfortunately... :(


text:
Q: Fragment button affecting other instances of the same fragment I have a button that adds an instance of a fragment, ActivityFragment, when pressed. There is an edit_button in the fragment that, when pressed, changes the activity_text textview in the fragment. However, when multiple instances of ActivityFragment are added, any edit_button pressed in any fragment will only affect the first ActivityFragment added. I believe this is happening because each fragment shares the same id, but would there be any way to get around this so that each edit_button only affects the fragment that it is in, preferably without changing the fragment id upon creation?
Here is the Activity Fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/activity_fragment">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/activity_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="5dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="Edit Activity"
        android:textSize="18sp"
        app:layout_constraintBaseline_toBaselineOf="@+id/checkbox"
        app:layout_constraintLeft_toRightOf="@+id/checkbox"
        app:layout_constraintRight_toLeftOf="@+id/edit_button"/>

    <Button
        android:id="@+id/edit_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="16dp"
        android:onClick="editActivity"
        android:text="Edit Activity"
        app:layout_constraintBaseline_toBaselineOf="@+id/checkbox"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

Here is my MainActivity.java with the ActivityFragment class. The onClick method for the edit_button is at the very bottom:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public static class ActivityFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup
        container, Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.activity_fragment, container,
            false);
        }
    }

    public void addActivity(View view) {
        ActivityFragment fragment1 = new ActivityFragment();
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, fragment1).commit();
    }

    //This is the editButton method
    public void editActivity(View view) {
        TextView activityText = (TextView) findViewById(R.id.activity_text);
        activityText.setText("success");
    }

}

*This is my first time posting a question, sorry if I'm doing anything incorrectly.

A: This is happening because you're adding lots of fragments to your view. You haven't noticed that because all of them are equals to each other. I think you have to change this:
public void addActivity(View view) {
    ActivityFragment fragment1 = new ActivityFragment();
    getSupportFragmentManager().beginTransaction()
            .add(R.id.fragment_container, fragment1).commit();
}

to this:
public void addActivity(View view) {
    ActivityFragment fragment1 = new ActivityFragment();
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.fragment_container, fragment1).commit();
}

You have to remember that, when you're adding, all the views are appended and the findViewById will find the first one. And you can remove the static from the Fragment.

A: By using this :
getSupportFragmentManager().beginTransaction()
        .add(R.id.fragment_container, fragment1).commit();

You are stacking up fragments one over the other. Change it to
getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_container, fragment1).commit();


text:
Q: PublishSubject's onNext call in different thread after I update to Retrofit 2.0 I have a following class that my coworker created while we were using Retrofit 1.9
public class SomeApiCallAction {

  private Subscription subscription;
  private NoInternetConnectionInterface noInternetConnectionInterface;

  public interface NoInternetConnectionInterface {
      PublishSubject<Integer> noInternetConnection(Throwable throwable);
  }

  public void execute(Subscriber subscriber, NoInternetConnectionInterface noInternetConnectionInterface) {
      this.noInternetConnectionInterface = noInternetConnectionInterface;
      this.subscription = retrofit.someService().someApiCall()
          .subscribeOn(Schedulers.newThread())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(subscriber)
          .retryWhen(retryFunction);
  }

  public void cancel() {
      if (this.subscription != null) {
          this.subscription.unsubscribe();
      }
  }

  private Func1<Observable<? extends Throwable>, Observable<?>> retryFunction = new Func1<Observable<? extends Throwable>, Observable<?>>() {
      @Override
      public Observable<?> call(Observable<? extends Throwable> observable) {
          return observable.flatMap(new Func1<Throwable, Observable<?>>() {
              @Override
              public Observable<?> call(final Throwable throwable) {
                  if (noInternetConnectionInterface!= null && (throwable instanceof IOException || throwable instanceof SocketTimeoutException)) {
                      return noInternetConnectionInterface.noInternetConnection(throwable);
                  }else{
                      return Observable.error(throwable);
                  }
              }
          });
      }
}

SomeApiCallAction is just a simple class that wrap retrofit api call inside, the only thing special is its retry function. The retry function will check if throwable is kind of IOException or SocketTimeoutException or not, if it is, it will call the interface so that we can present retry dialog to user to ask whether they want to retry the operation or not. Our usage is similar to following snippet
public class SomeActivity implement NoInternetConnectionInterface {

    @OnClick(R.id.button)
    public void do(View v) {
        new SomeApiCallAction().execute(
            new Subscriber(),
            this
        )
    }

    @Override
    public PublishSubject<Integer> noInternetConnection(final Throwable throwable) {
        Log.i("Dev", Thread.currentThread() + " Error!");
        final PublishSubject<Integer> subject = PublishSubject.create();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                NoInternetDialogFragment dialog = NoInternetDialogFragment.newInstance();
                dialog.setNoInternetDialogFragmentListener(new NoInternetDialogFragmentListener{
                    @Override
                    public void onUserChoice(boolean retry, NoInternetDialogFragment dialog) {
                        Log.i("Dev", Thread.currentThread() + " Button Click!");
                        if (retry) {
                            subject.onNext(1);
                        } else {
                            subject.onError(throwable);
                        }

                        dialog.dismiss();

                    }
                });
                dialog.show(getSupportFragmentManager(), NoInternetDialogFragment.TAG);
            }
        });
        return subject;
    }
}

When we were using Retrofit 1.9.0, this implementation was working perfectly. We test by turn on Airplane Mode and press the button to execute api call.

*

*first execution fail and I got UnknownHostException in retry function.

*so, I call the interface (Activity) to present retry dialog

*I press retry button while still on Airplane mode to repeat the execution

*as expected, every execution that happen after user press retry button failed to, I always get UnknownHostException in retry function.

*If I keep pressing the retry button, retry dialog will appears forever until I turn off the airplane mode.

But after we update our dependencies to
'com.squareup.retrofit2:retrofit:2.0.2'
'com.squareup.retrofit2:adapter-rxjava:2.0.2'

We try again but this time the behaviour change,

*

*first execution fail and I got UnknownHostException in retry function same as before.

*so, I call the interface (Activity) to present retry dialog

*I press retry button while still on Airplane mode to repeat the execution

*But this time, in the retry function, instead of receiving UnknowHostException like what it was, I got NetworkOnMainThreadException instead

*so the condition is not match, interface not gets call, and result as only 1 retry dialog presented to user.

Following is the log from above code
Thread[android_0,5,main] Error!
Thread[main,5,main] Button Click!

Do you have any idea what would cause this? Any suggestion, comment will be very appreciate.
Note : Following are other dependencies that we been using and might related. But they are not recently updated, been using these version since the beginning of this project.
'com.jakewharton:butterknife:8.0.1'

'io.reactivex:rxandroid:1.1.0'
'io.reactivex:rxjava:1.1.0'

'com.google.dagger:dagger-compiler:2.0'
'com.google.dagger:dagger:2.0'
'javax.annotation:jsr250-api:1.0'

More Info
I just reset my code back to the point when we were using Retrofit 1.9, I found the the print log is different
Thread[Retrofit-Idle,5,main] Error!
Thread[main,5,main] Button Click!

Not sure if this relevant to the issue or not, but clearly that in 1.9.0 I call interface in different thread compare to 2.0.0
Final Edit
After reading the answer from @JohnWowUs and follow to the link he provide I found that in Retrofit 2, network call will be synchronous by default
To resolve my issue, there are 2 ways to do this
1.) Do as @JohnWowUs suggest by specify the thread for retryFunction
this.subscription = retrofit.someService().someApiCall()
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(subscriber)
  .retryWhen(retryFunction, Schedulers.io());

2.) When create retrofit object, specify thread when create RxJavaCallAdapterFactory
retrofit = new Retrofit.Builder()
  .baseUrl(AppConfig.BASE_URL)
  .client(client)
  .addConverterFactory(GsonConverterFactory.create(getGson()))
  .addCallAdapterFactory(
     RxJavaCallAdapterFactory.createWithScheduler(
       Schedulers.from(threadExecutor)
     )
   )
  .build();

A: I think the problem is that when you resubscribe you're subscribing on the main thread as a consequence of using the default trampoline scheduler in retryWhen. Retrofit 1.9 handled the scheduling for you so using subscribeOn was pointless. The issue discussion is here. In Retrofit 2 I believe this has changed so you should try something like
this.subscription = retrofit.someService().someApiCall()
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(subscriber)
      .retryWhen(retryFunction, Schedulers.io());

A: For a quick solution this is what I do to resolve this issue
new Thread(new Runnable(){
    public void run() {
        choice.onNext(1);
    }
}).start();

The app work as we expect again. But, I don't think this is the right way to resolve this issue so I'll keep this question open for further comment.


text:
Q: How to find number of non negative integral solutions of $ax+by+cz= d$ ( no relation between $a,b,c,d$). My question stems from this one

Find the no. of non negative integral solutions for $x+y+3z=33$

and i did it by taking the $3z$ to the other side and thinking that z can only be one of these $\{0,1,2,...,11 \}$ and then for each one i found out how many such x and y can be .
For ex: for $z=0$ that is $x+y=33$ you can think of distributing 33 ones or $\{1,1,...\text{33 terms} \}$ between two different people , which gives $^{34}C_1$ or $34$ .
Similarly you will get the total = $$34+31+28+...1=210$$

That is fine but what if y had a different coefficient than x ( for example $x+2y+3z=33$ )was my actual question so I generalized the coefficients.

A: The number of nonnegative integer solutions of $ax + by + cz = d$ can be obtained as the coefficient of $X^d$ in the series expansion of $1/((1-X^a)(1-X^b)(1-X^c))$.
Alternatively, it is $F_3(d)$ where $F_3(m) = F_3(m-a) + F_2(m)$ for $m \ge a$, $F_3(m) = F_2(m)$ for $0 \le m < a$, $F_2(m) = F_2(m-b) + F_1(m)$ for $m \ge b$, $F_2(m) = F_1(m)$ for $0 \le m < b$, and $F_1(m) = 1$ if $m$ is a multiple of $c$, $0$ otherwise.
EDIT: The point about the series expansion is this.  We have the geometric series formula (convergent for $|X|<1$, but convergence doesn't play any role here)
$$ \dfrac{1}{1-X^a} =  1 + X^a + X^{2a} + X^{3a} + \ldots = \sum_{k=0}^\infty X^{ka}$$
and similarly for $b$ and $c$.  If you expanded out
$$ \dfrac{1}{(1-X^a)(1-X^b)(1-X^c)} = (1 + X^a + X^{2a}+\ldots)(1+X^b+X^{2b}+\ldots)(1+X^c+X^{2c}+\ldots)$$
you get the sum of terms $X^{ax}X^{by}X^{cz} = X^{ax+by+cz}$ for all nonnegative integers $x,y,z$.  You get an $X^n$ for each triple $(x,y,z)$ with $ax+by+cz = n$,
so the coefficient of $X^n$ counts the number of such triples.  The function $g(X) = 1/((1-X^a)(1-X^b)(1-X^c))$ is called the generating function for the sequence of coefficients.  These pop up all over combinatorics.
Now, how do you calculate it?  Certainly not by differentiating.  But computer algebra systems can generate series quite efficiently, e.g. you can ask Wolfram Alpha.  Also, you can use partial fractions to simplify
$g(X)$ and then find a formula for the coefficients.

A: So, we've to find the number of non-negative integral solutions of the equation $ax+by+cz=d$ i.e. the number of ways of distributing $d$ identical objects to $3$ distinct groups where a group must contain at least one object.
It is obvious that the number of objects received by group $1, 2,3$ are multiples of $a, b, c$ respectively. Now, you have to calculate the min. and max. value that $x, y, z$ can take (as you showed in your question that $z=\{0, 1,\dots, 11\}, z\in Z$) like, $$a_1\le x\le a_2\\b_1\le y\le b_2\\c_1\le z\le c_2$$
The total number of solutions of the given equation is equal to coefficient of $x^d$ in
$\displaystyle \{(x^a) ^{a_1}+(x^a) ^{a_1+1}+\dots+(x^a) ^{a_2}\}\times \{(y^b)^{b_1}+(x^b) ^{b_1+1}+\dots+(x^b)^{b_2}\}\times \{(z^c)^{c_1}+(z^c) ^{c_1+1}+\dots+(z^c)^{c_2}\}$


text:
Q: Elaboração de cifra de césar em python Opa galera, sou novo por aqui e no mundo da programação, então toda crítica é bem vinda.
Estou com um problema com essa cifra de cesar que venho tentando fazer.
Poderiam me apontar possíveis erros, e formas de melhorar esse código, adicionando funções.
   print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-")
print("Criptografia de César")
print(" ")

#recebe a chave de critografia e valida
chave = int(input("digite a chave de criptografia (ate 26)\n"))
while chave > 26 or chave < 0:
    print(" ")
    chave = input("chave inválida, tente novamente")

base = 'abcdefghijklmnopqrstuvwxyz'

#escolhe o modo
modo = str(input("Deseja encriptar ou descriptar\n"))

#insere e formata o texto
text= str(input("Digite o texto a ser criptografado\n"))
tamanho_txt = len(text)
text = text.lower()

#insere o texto final
cripto =''

char = 0
    #escolhe o modo
if (modo == 'e' or modo == 'encriptar') :

    while char <= tamanho_txt:

            #recebe o word de comparação
        word = text[char]

            #enquanto o word estiver coontido na base de comparação
        for word in base[0:len(base)]:

                #encontra o numero da posição dp word na base
            posicion = base.find(word)

                #soma a chave á posição
            posicion + chave

                # se a posição for maior que a base ira calcular a diferença
            if(posicion > len(base)):
                posicion = posicion - len(base)

        #concatena a o word encontrado
        cripto = cripto + base[posicion]

        char = char +1

if (modo == 'd' or modo == 'decriptar'):
        # contador do texto
    while char <= tamanho_txt:
            # recebe o word da posição
        word = text[char]
            #condição se o word estiver contido na base
        for word in base[0:len(base)]:
                #encontra a posição
            posicion = base.find(word)
                #subtrai a chave
            posicion - chave
                #condicional se a posição foi menor que 0
            if posicion <= 0:
                    # subtrai o valor absoluto da base para encontrar a posição
                posicion = len(base)- abs(posicion)

        #resultado
        cripto = cripto + base[posicion]
        char = char + 1

print("sua mensagem \n" + cripto)

A: Olá. Bem, seu código está bem bagunçado. Além disso, possui muitas irregularidades que não podem acontecer ou que são extremamente redundantes.
Posso citar os dois que logo vi ao ler seu código:

*

*Dois IFs para mesmos dados:
Quando estamos tratando duas ou mais possibilidades para um certo dado (no caso aqui é o input do usuário), o ideal é por um if/elif/else. Se quiser saber mais sobre a causa, temos já uma pergunta  e resposta no SOpt.
Então podemos já substituir o segundo if por um elif.

*

*Laço for com construção estranha
O laço for percorre todos os itens de um objeto iterável (strings, tuplas, sets, dicionários e listas), e no seu caso não há necessidade de percorrer usando o [0:len(base)], uma vez que isso é exatamente a mesma coisa que por a própria base como argumento do for.
Ou seja, basta renomearmos for word in base[0:len(base)]: para for word in base.

*

*Há uma linha que não faz nada.

Quando você faz qualquer operação, o Python apenas executa. O resultado você só salva na memória se atribuir numa variável, ou adicionar em algum objeto que pareça um array (como um dict ou um list). A linha em questão é a
posicion + chave

, onde o correto seria
posicion += chave

De resto, acredito que o erro seja mesmo de lógica. No caso, você poderia explicar o seu algoritmo? Eu realmente não consegui entender bem qual foi sua intenção digitando o que foi digitado. Mas sobre a lógica, posso apontar uns erros:

*

*Me parece que você não entendeu muito bem o conceito do laço for. Ele não verifica a condição, ele faz aquilo que falei agora pouco: itera cada item de um objeto iterável, no caso da string, cada item é um caractere. E ao invés de usar a base, você deveria usar o texto do input do usuário.

*O laço while nesse caso também é inútil, uma vez que a limitação do tamanho do input já pode ser imposta num laço for, que percorre exatamente todos os caracteres dos dados que o usuário inseriu (input).

*Além disso, os dois ifs para caso haja "sobrecarga" (quando a letra for z e eu tenha de ir para a, ou vice-versa) você apenas aplicou uma lógica incorreta. O correto seria, respectivamente, if(posicion > len(base)): e if posicion < 0:. Onde o primeiro deve indicar caso seja apenas maior que o comprimento do alfabeto e no segundo apenas se for menor que 0.

Corrigindo todos os erros, chegamos ao código final:
print ("-=-=-=-=-=-=-=-=-=-=-=-=-=-")
print("Criptografia de César")
print(" ")

#recebe a chave de critografia e valida
chave = int(input("digite a chave de criptografia (ate 26)\n"))
while chave > 26 or chave < 0:
    print(" ")
    chave = input("chave inválida, tente novamente")

base = 'abcdefghijklmnopqrstuvwxyz'

#escolhe o modo
modo = str(input("Deseja encriptar ou descriptar\n"))

#insere e formata o texto
text= input("Digite o texto a ser criptografado\n")
text = text.lower()

#insere o texto final
cripto =''

    #escolhe o modo
if (modo == 'e' or modo == 'encriptar') :
    for word in text:
                #encontra o numero da posição dp word na base
        posicion = base.find(word)

            #soma a chave á posição
        posicion += chave

            # se a posição for maior que a base ira calcular a diferença
        if(posicion > len(base)):
            posicion = posicion - len(base)

    #concatena a o word encontrado
        cripto = cripto + base[posicion]

elif (modo == 'd' or modo == 'decriptar'):
        # contador do texto
            # recebe o word da posição
            #condição se o word estiver contido na base
    for word in text:
            #encontra a posição
        posicion = base.find(word)
            #subtrai a chave
        posicion -= chave
            #condicional se a posição foi menor que 0
        if posicion < 0:
                # subtrai o valor absoluto da base para encontrar a posição
            posicion = len(base)- abs(posicion)

    #resultado
        cripto = cripto + base[posicion]

print("sua mensagem \n" + cripto)

A: O python possui uma função perfeita para a cifra de césar, que é a str.translate:
def cesar(texto, deslocamento):
    alfabeto = string.ascii_lowercase
    alfabeto_deslocado = alfabeto[deslocamento:] + alfabeto[:deslocamento]
    tabela = string.maketrans(alfabeto, alfabeto_deslocado)
    return texto.translate(tabela)

Por exemplo:
>>> print(cesar('ola', 10))
yvk

para descriptografar é só inverter o sinal do deslocamento:
>>> print(cesar('yvk', -10))
ola


text:
Q: Add dropdown list of cities in Woocommerce checkout page I want to add specific cities list in dropdown in checkout page of Woocommerce.
Any best solution to add a dropdown of specific cities.
I want to add dropdown on this website http://www.pkbrand.com

A: It can be done using a custom function hooked in woocommerce_checkout_fields action hook, where you will define in an array your desired cities:
// Change "city" checkout billing and shipping fields to a dropdown
add_filter( 'woocommerce_checkout_fields' , 'override_checkout_city_fields' );
function override_checkout_city_fields( $fields ) {

    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
         '' => __( 'Select your city' ),
        'Karachi' => 'Karachi',
        'Lahore' => 'Lahore',
        'Faisalabad' => 'Faisalabad',
        'Rawalpindi' => 'Rawalpindi',
        'Gujranwala' => 'Gujranwala',
        'Peshawar' => 'Peshawar',
        'Multan' => 'Multan',
        'Hyderabad' => 'Hyderabad',
        'Islamabad' => 'Islamabad'
    );

    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = $option_cities;
    $fields['shipping']['shipping_city']['type'] = 'select';
    $fields['shipping']['shipping_city']['options'] = $option_cities;

    return $fields;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works.


text:
Q: Coq: Defining a function by pattern matching on the arity of its argument I want to define a function, the behavior of which depends on whether it's argument is (at least) an n-place function. A rudimentary (failed) attempt is
Definition rT {y:Type}(x:y) := ltac: (match y with
 | _ -> _ -> _ => exact True
 | _ => exact False end).

Check prod: Type -> Type -> Type.
Compute rT prod. (*= False: Prop*)
Print rT. (*rT = fun (y : Type) (_ : y) => False: forall y : Type, y -> Prop*)

As you see, rT maps everything to False. Why? The result remains the same if I replace y in the match clause w/ type of x

A: The function you want cannot exist within Gallina at the type you expect.
Your function is accepted, but if you print it, you can see its body is:
rT = fun (y : Type) (_ : y) => False

Gallina has no way of match-ing on a Type. There are ways to deal with n-ary functions, in such a way that you can inspect their arity, but it involves dependent types to statically capture the arity. For instance, for uniform n-ary functions:
https://coq.inria.fr/library/Coq.Numbers.NaryFunctions.html