text:
Q: Shortest way to calculate difference between two numbers? I'm about to do this in C++ but I have had to do it in several languages, it's a fairly common and simple problem, and this is the last time. I've had enough of coding it as I do, I'm sure there must be a better method, so I'm posting here before I write out the same long winded method in yet another language;
Consider the (lilies!) following code;
// I want the difference between these two values as a positive integer
int x = 7
int y = 3
int diff;
// This means you have to find the largest number first
// before making the subtract, to keep the answer positive
if (x>y) {
     diff = (x-y);
} else if (y>x) {
     diff = (y-x);
} else if (x==y) {
    diff = 0;
}

This may sound petty but that seems like a lot to me, just to get the difference between two numbers. Is this in fact a completely reasonable way of doing things and I'm being unnecessarily pedantic, or is my spidey sense tingling with good reason?

A: Just get the absolute value of the difference:
#include <cstdlib>
int diff = std::abs(x-y);

A: All the existing answers will overflow on extreme inputs, giving undefined behaviour. @craq pointed this out in a comment.
If you know that your values will fall within a narrow range, it may be fine to do as the other answers suggest, but to handle extreme inputs (i.e. to robustly handle any possible input values), you cannot simply subtract the values then apply the std::abs function. As craq rightly pointed out, the subtraction may overflow, causing undefined behaviour (consider INT_MIN - 1), and the std::abs call may also cause undefined behaviour (consider std::abs(INT_MIN)). It's no better to determine the min and max of the pair and to then perform the subtraction.
More generally, a signed int is unable to represent the maximum difference between two signed int values. The unsigned int type should be used for the output value.
I see 3 solutions. I've used the explicitly-sized integer types from stdint.h here, to close the door on uncertainties like whether long and int are the same size and range.
Solution 1. The low-level way.
// I'm unsure if it matters whether our target platform uses 2's complement,
// due to the way signed-to-unsigned conversions are defined in C and C++:
// >  the value is converted by repeatedly adding or subtracting
// >  one more than the maximum value that can be represented
// >  in the new type until the value is in the range of the new type
uint32_t difference_int32(int32_t i, int32_t j) {
    static_assert(
        (-(int64_t)INT32_MIN) == (int64_t)INT32_MAX + 1,
        "Unexpected numerical limits. This code assumes two's complement."
    );

    // Map the signed values across to the number-line of uint32_t.
    // Preserves the greater-than relation, such that an input of INT32_MIN
    // is mapped to 0, and an input of 0 is mapped to near the middle
    // of the uint32_t number-line.
    // Leverages the wrap-around behaviour of unsigned integer types.

    // It would be more intuitive to set the offset to (uint32_t)(-1 * INT32_MIN)
    // but that multiplication overflows the signed integer type,
    // causing undefined behaviour. We get the right effect subtracting from zero.
    const uint32_t offset = (uint32_t)0 - (uint32_t)(INT32_MIN);
    const uint32_t i_u = (uint32_t)i + offset;
    const uint32_t j_u = (uint32_t)j + offset;

    const uint32_t ret = (i_u > j_u) ? (i_u - j_u) : (j_u - i_u);
    return ret;
}

I tried a variation on this using bit-twiddling cleverness taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax but modern code-generators seem to generate worse code with this variation. (I've removed the static_assert and the comments.)
uint32_t difference_int32(int32_t i, int32_t j) {
    const uint32_t offset = (uint32_t)0 - (uint32_t)(INT32_MIN);
    const uint32_t i_u = (uint32_t)i + offset;
    const uint32_t j_u = (uint32_t)j + offset;

    // Surprisingly it helps code-gen in MSVC 2019 to manually factor-out
    // the common subexpression. (Even with optimisation /O2)
    const uint32_t t = (i_u ^ j_u) & -(i_u < j_u);
    const uint32_t min = j_u ^ t; // min(i_u, j_u)
    const uint32_t max = i_u ^ t; // max(i_u, j_u)
    const uint32_t ret = max - min;
    return ret;
}

Solution 2. The easy way. Avoid overflow by doing the work using a wider signed integer type. This approach can't be used if the input signed integer type is the largest signed integer type available.
uint32_t difference_int32(int32_t i, int32_t j) {
    return (uint32_t)std::abs((int64_t)i - (int64_t)j);
}

Solution 3. The laborious way. Use flow-control to work through the different cases. Likely to be less efficient.
uint32_t difference_int32(int32_t i, int32_t j)
{   // This static assert should pass even on 1's complement.
    // It's just about impossible that int32_t could ever be capable of representing
    // *more* values than can uint32_t.
    // Recall that in 2's complement it's the same number, but in 1's complement,
    // uint32_t can represent one more value than can int32_t.
    static_assert( // Must use int64_t to subtract negative number from INT32_MAX
        ((int64_t)INT32_MAX - (int64_t)INT32_MIN) <= (int64_t)UINT32_MAX,
        "Unexpected numerical limits. Unable to represent greatest possible difference."
    );

    uint32_t ret;
    if (i == j) {
        ret = 0;
    } else {

        if (j > i) { // Swap them so that i > j
            const int32_t i_orig = i;
            i = j;
            j = i_orig;
        } // We may now safely assume i > j

        uint32_t magnitude_of_greater; // The magnitude, i.e. abs()
        bool     greater_is_negative; // Zero is of course non-negative
        uint32_t magnitude_of_lesser;
        bool     lesser_is_negative;

        if (i >= 0) {
            magnitude_of_greater = i;
            greater_is_negative = false;
        } else { // Here we know 'lesser' is also negative, but we'll keep it simple
            // magnitude_of_greater = -i; // DANGEROUS, overflows if i == INT32_MIN.
            magnitude_of_greater = (uint32_t)0 - (uint32_t)i;
            greater_is_negative = true;
        }

        if (j >= 0) {
            magnitude_of_lesser = j;
            lesser_is_negative = false;
        } else {
            // magnitude_of_lesser = -j; // DANGEROUS, overflows if i == INT32_MIN.
            magnitude_of_lesser = (uint32_t)0 - (uint32_t)j;
            lesser_is_negative = true;
        }

        // Finally compute the difference between lesser and greater
        if (!greater_is_negative && !lesser_is_negative) {
            ret = magnitude_of_greater - magnitude_of_lesser;
        } else if (greater_is_negative && lesser_is_negative) {
            ret = magnitude_of_lesser - magnitude_of_greater;
        } else { // One negative, one non-negative. Difference is sum of the magnitudes.
            // This will never overflow.
            ret = magnitude_of_lesser + magnitude_of_greater;
        }
    }
    return ret;
}

A: Using the std::abs() function is one clear way to do this, as others here have suggested.
But perhaps you are interested in succinctly writing this function without library calls.
In that case
diff = x > y ? x - y : y - x;

is a short way.
In your comments, you suggested that you are interested in speed. In that case, you may be interested in ways of performing this operation that do not require branching. This link describes some.

A: Well it depends on what you mean by shortest. The fastet runtime, the fastest compilation, the least amount of lines, the least amount of memory. I'll assume you mean runtime.
#include <algorithm>    // std::max/min
int diff = std::max(x,y)-std::min(x,y);

This does two comparisons and one operation (this one is unavoidable but could be optimized through certain bitwise operations with specific cases, compiler might actually do this for you though). Also if the compiler is smart enough it could do only one comparison and save the result for the other comparison. E.g if X>Y then you know from the first comparison that Y < X but I'm not sure if compilers take advantage of this.

A: #include <cstdlib>

int main()
{
    int x = 7;
    int y = 3;
    int diff = std::abs(x-y);
}


text:
Q: Comparation jQuery and jQuery Mobile In my job I was asked to do a comparison table between these two libraries ... So I started reading about this but all I found was people saying "mobile its for ... mobile and jQuery its for desktop browsers" so ... Any one can help me to do a comparison table of characteristics and functionality of those two? Its this possible? Its really important for me to do this comparison!

A: There really isn't a comparison because they are not competing libraries.  JQuery Mobile is a HTML 5 based UI framework built on top of the jQuery and jQuery UI libraries.  You can't use jQuery Mobile without jQuery.

A: This is ridiculous...jQuery mobile is dependent on jQuery. Do some homework

redpajama_set_name: RedPajamaStackExchange


text:
Q: LinkedIn Profile PlugIn does not load logo #linkedin I've been dealing with an issue regarding the LinkedIn Company Profile Plugin, using the following code:
<script src="//platform.linkedin.com/in.js" type="text/javascript"></script
<script type="IN/CompanyProfile" data-id="1337" data-format="inline" data-related="false"></script>

Which  was provided in this page https://developer.linkedin.com/plugins/company-profile I'm able to embed the profile but the company logo just does not seem to load and uppon inspection its throwing a 404 error on the logo resource.

I must note that this also happens in the above mentioned page, with different browsers and logged in users.
If there is a #linkedin Dev/Admin out there it would be helpful to clarify is this a problem on their side, thanks!.

A: so i check and i found out that the image they had in the example just does not exist anymore, here is an example with the image still intact.
https://developer.linkedin.com/plugins/member-profile
so probably your image is just invalid.


text:
Q: I can't store a large list of object in the appfabric cache, how to do? I have a list which is contains 10500 of objects.
When I tried to put it in the cache this made an exeption.
Then I decreased the list objects number to 9000, then the cache worked fine.
So can anyone please tell me how to store all of that list in the cache??
below is the dataCacheClient in my web.config :
<dataCacheClient requestTimeout="600000"
                  channelOpenTimeout="12000"
                  maxConnectionsToServer="1">
<hosts>
  <host name="Platform.Almanhal.local" cachePort="22233" />
</hosts>

<transportProperties connectionBufferSize="131072"
                     maxBufferPoolSize="568435456"
                     maxBufferSize="183886080"
                     maxOutputDelay="2"
                     channelInitializationTimeout="60000" />
</dataCacheClient>

and the below is the appfabric api I used to store this list :
public T Data<T>(string cacheKey, int expirationSeconds, Func<T> method)
    {
        T data = default(T);
        try
        {
            string key = GetEncryptedKey(cacheKey);
            var cache = GetFromCache(key);

            data = cache == null ? default(T) : (T)cache;
            if (data == null)
            {
                data = method();
                if (expirationSeconds > 0 && data != null)
                {
                    lock (sync)
                    {
                        PutInCache(key, data, TimeSpan.FromSeconds(expirationSeconds));
                    }
                }
                Logger.LogInfo(string.Format("{0} Loaded From DB", typeof(T).GetProperties()[2].PropertyType.Name));
            }
            else
            {
                Logger.LogInfo(string.Format("{0} Loaded From Cache", typeof(T).GetProperties()[2].PropertyType.Name));
            }
        }
        catch (Exception ex)
        {
            Logger.LogInfo(ex.InnerException.Message);
        }
        return data;
    }

The PutInCache function is below :
 public void PutInCache(string key, object obj, TimeSpan tspan)
    {
        //TracingLibrary.TraceEvents.AddEvent("Inside Put in Cache");
        try
        {
            _cache.Put(key, obj, tspan);
        }
        catch (Exception e)
        {
            string msg = e.InnerException.ToString();
            Logger.LogInfo(string.Format("Cannot put object in cache {0}, \nException: {1} \nMessage:{2}", key, e.InnerException.ToNullOrString(), e.Message.ToNullOrString()));
            //write to logger ("Exception putting in cache", e.InnerException);
        }
    }

And this is the exeption message :

ErrorCode:SubStatus:There is a temporary failure.
  Please retry later. (One or more specified cache servers are
  unavailable, which could be caused by busy network or servers. For
  on-premises cache clusters, also verify the following conditions.
  Ensure that security permission has been granted for this client
  account, and check that the AppFabric Caching Service is allowed
  through the firewall on all cache hosts. Also the MaxBufferSize on the
  server must be greater than or equal to the serialized object size
  sent from the client.)

A: The answer is in the error message:

the MaxBufferSize on the server must be greater than or equal to the
  serialized object size sent from the client

You set this in the advancedProperties section of the cluster config:
<advancedProperties>
    <transportProperties maxBufferSize="183886080" />
</advancedProperties>


text:
Q: Reset JavaScript Counter after Deleting a field I have a javascript function that adds input fields with a counter. now, when i remove one of the fields it gets deleted but the counter continues! is there a way in JS or JQuery to reset the counter and auto increment the counter?
JS code:
$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;

        $('#addScnt').live('click', function() {
                $('
<input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value'+i+'" /> Remove
').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').live('click', function() {
                if( i > 2 ) {
                        $(this).parents('p').remove();

                }
                return false;
        });
});

please check the jsfiddle
Clarifying:
my fields are like:
no. 1
no. 2
no. 3

what i want is: After deleting #2:
no. 1
no. 3
**To**:
no. 1
no. 2

Thank you

A: Html

Add Another Input Box

        <input type="text" class="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />

Js
function resetIndexes(){
    var j = 1;
    $('.p_scnt').each(function(){
        if( j > 1){
            $(this).attr('name', 'p_scnt_' + j);
            $(this).attr('placeholder', 'Input Value'+j);
        }
        j++;
    });
}

$(function() {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents .p_scnt').size() + 1;

    $('#addScnt').on('click', function() {
        i = $('#p_scents .p_scnt').size() + 1;
        $('
<input type="text" size="20" class="p_scnt" name="p_scnt_' + i +'" value="" placeholder="Input Value'+i+'" /> Remove
').appendTo(scntDiv);
        i++;
        return false;
    });

    $('#p_scents').on('click', '.remScnt', function() {
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    resetIndexes();
            }
            return false;
    });
});

Here is the JSFiddle

A: have you tried the following?
       $('#remScnt').live('click', function() {
            if( i > 2 ) {
                    $(this).parents('p').remove();
              i--;
            }
            return false;
    });

A: A suggestion, NOT the answer.
Well you must need to change 'live' for 'on'
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
$('#addScnt').live('click', function() {

with on
$('document.body').on('click', '#addScnt', function() {

jQuery live deprecated


text:
Q: ¿Cómo transformar una Tabla en un triangulo? Tengo una estructura como la siguiente:
datos <- read.table(header = T, text = "
                    anno mes venta
                    1999 12 5
                    1999 36 10
                    1999 24 5
                    2000 12 10
                    2000 24 20
                    2000 36 35
                    3000 12 40
                    3000 36 45
                    1999 12 50")

Me gustaría poder obtener el siguiente triangulo:
anno    12  24  36
1999    55  5   10
2000    10  20  35
3000    40  NA  45

El problema lo tengo el dato del último año (3000/36) que me lo pone en el mes 24 dejándome el 36 con un NA.
El codigo que tengo generado es el siguiente:
datos<-datos[order(datos$anno, datos$mes),]
datos2 <- datos %>%
  group_by(anno, mes) %>%
  summarise(ventas=sum(venta))

d2 <- datos2 %>%
  select(anno, ventas) %>%
  group_by(anno) %>%
  mutate(rn = row_number()) %>%
  spread(rn, ventas)

Muchas gracias.

A: Me parece que el problema lo tienes en la forma que planteas el spread(), realmente es mucho más sencillo a partir de los datos agrupados, hacer directamente: spread(mes, ventas). El código completo te quedaría así:
datos %>%
    group_by(anno, mes) %>%
    summarise(ventas=sum(venta)) %>%
    spread(mes, ventas)

# A tibble: 3 x 4
# Groups:   anno [3]
   anno  `12`  `24`  `36`
  <int> <int> <int> <int>
1  1999    55     5    10
2  2000    10    20    35
3  3000    40    NA    45


text:
Q: how to get system drives through php?
Possible Duplicate:
How to get system info in PHP?

I am building a simple file browser, I want to know as how to get the system information like the total drives and there names through php script?
thanks

A: This is gotten from the manual, and is for windows (Since you didn't specify the OS.) using the COM class.
Note : This has nothing to do with the client side.
<?php
 $fso = new COM('Scripting.FileSystemObject');
    $D = $fso->Drives;
    $type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk");
    foreach($D as $d ){
       $dO = $fso->GetDrive($d);
       $s = "";
       if($dO->DriveType == 3){
           $n = $dO->Sharename;
       }else if($dO->IsReady){
           $n = $dO->VolumeName;
           $s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize);
       }else{
           $n = "[Drive not ready]";
       }
   echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>";

    }

      function file_size($size)
      {
      $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
      }

?>

Would output something similar to
Drive C: - Fixed - Bla - 88.38 GB free of: 444.14 GB
Drive D: - Fixed - Blas - 3.11 GB free of: 21.33 GB
Drive E: - Fixed - HP_TOOLS - 90.1 MB free of: 99.02 MB
Drive F: - CD-ROM - [Drive not ready] -
Drive G: - CD-ROM - Usb - 0 Bytes free of: 24.75 MB
Drive H: - Removable - [Drive not ready] -


text:
Q: Why is my sound script interfering with my advertises I added sound effects to android game after I set up the rewarded advertises with admob on Unity. Here is my script for rewarded ads:
string adUnitId = "ca-app-pub-5920324855307233/4458481507";
RewardBasedVideoAd rewardBasedVideo = null;

void Start () {
    managerScript = gameObject.GetComponent<GameManager>();
    isCalled = false;
    rewardBasedVideo = RewardBasedVideoAd.Instance;
}

public void adButton(){
    isCalled = true;
    AdRequest request = new AdRequest.Builder().Build();
    rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
    rewardBasedVideo.LoadAd(request, adUnitId);
}

void Update(){
    if(isCalled == true){
        adButton();
        showAd();
    }
}

public void showAd(){
    if (rewardBasedVideo.IsLoaded()){
        rewardBasedVideo.Show();
    }
}

public void HandleRewardBasedVideoRewarded(object sender, Reward args){
    isCalled = false;
    managerScript.revival();
    managerScript.Loading.SetActive(false);
    rewardBasedVideo.OnAdRewarded -= HandleRewardBasedVideoRewarded;
}

Here is my script for sound effects (sound script):
public AudioClip Death;
public static bool toggled;
public static Sounds Instance;

public void DeathSound(){
    if(toggled == true){
    GetComponent<AudioSource>().PlayOneShot(Death);
  }
}

public void SoundToggle(){
if(toggled == false){
        toggled = true;
}else if(toggled == true){
        toggled = false;
    }
}

Finally how I call for a sound in another script:
Sounds sound;
GameObject soundManager;

public void Start(){
    soundManager = GameObject.Find("Sound Manager");
    sound = soundManager.GetComponent<Sounds>();
}

public void Death(){
    sound.DeathSound();
}

The problem is for some reason when the boolean "toggled" is true in the Sound script, the HandleRewardBasedVideoRewarded method does not occur after the rewarded video advertise finishes. When sound is not toggled the method is called after the advertise and works fine. How is the sound effects being on affecting the method that happens after an advertise finishes? This problem is bothering me. Can someone help?
Update:
I tried disabling sound before the ad is loaded and then re enabling it after the ad. The problem still happens. Im not 100% certain but maybe the toggle bool has some effect, but I dont know how.

A: Either your code is not complete in the question or you made a mistake because GetComponent<AudioSource>().PlayOneShot(Death) is not being called anywhere in the script. You are calling DeathSound() from Death() but nothing is calling Death() to call DeathSound() which actually plays the sound. Take a closer look at your code. Call Death() function from somewhere and your sound should play.
EDIT:
Did not read your question well first time.
Before you call the showAd() function, Check if the audio is playing then stop playing it. Also change your Death from AudioClip to AudioSource. If possible don't use static in your code. It will introduce lots of other problems. If you want to share variables between scenes, you can do that with the PlayerPrefs class instead of using static variables.
public void showAd(){

    if (Death.isPlaying)
    {
        Death.Stop();
    }

    if (rewardBasedVideo.IsLoaded()){
        rewardBasedVideo.Show();
    }
}


text:
Q: Why no intellisense when LINQ statement has no where clause? Can anyone tell me why I do not get intellisense with this code:
var testDocuments = (from u in db.TestDocuments
                     orderby u.WhenCreated descending
                     select u).

but I do get intellisense with this code:
var testDocuments = (from u in db.TestDocuments
                     orderby u.WhenCreated descending
                     where 1==1
                     select u).

A: I was in the similar situation, then I added the following line..
using System.Linq;

A: When I run into this kind of problem I switch my coding style a little:
var testDocuments = (from u in db.TestDocuments
                     orderby u.WhenCreated descending
                     select u).

Translates into
var testDocuments = db.TestDocuments.OrderBy(u => u.WhenCreated).

And assuming the Linq object is valid it will pull up the intellisense.


text:
Q: Oscillation of nucleons mediated by polarizing electron charge on opposite ends of the nucleus? Assuming I have a nucleus and its known that there are nucleons inside its shell. Lets say I have an electron that alternates its position from the top of the nucleus to the opposite bottom, back and forth. Will the negative charge of the electron pull the nucleons up and down as the electrons move causing the nucleons to oscillate inside the nucleus.

A: For nuclei in our universe there aren't any electron wavefunctions that would oscillate in the way you describe; the electrons are either (a) smeared out over the entire nuclear volume or (b) unbound.
However, the nucleons in the nucleus can certainly vibrate, and the study of these vibrations and their allowed energy levels is "nuclear spectroscopy."  Your specific scenario reminds me of the giant dipole resonance.


text:
Q: How to connect an action to a value change in C++/Qt I do have a question. I'm currently developing an app and this app is reporting the available space on a device.
The display is done in my Window class of my file mainwindow.cpp
void MainWindow::createInfoSection()
{
    uint64_t space;
    CreateInfoSection = new QWidget();
    CreateInfoSection->setFixedHeight(40);

    QGridLayout *CreateInfoLayout = new QGridLayout(CreateInfoSection);

    NbOfItemsLabel = new QLabel(tr("%1 Files").arg(m_device.getNbOfFiles()));

    space = m_device.getAvailableFreeSpaceInBytes();

    if(space < MEGABYTE)
        SpaceAvailLabel = new QLabel(tr("%1 KB Remaining").arg(space/KILOBYTE));
    else if (space < GIGABYTE)
        SpaceAvailLabel = new QLabel(tr("%1 MB Remaining").arg(space/MEGABYTE));
    else
        SpaceAvailLabel = new QLabel(tr("%1 GB Remaining").arg(space/GIGABYTE));

    CreateInfoLayout->addWidget(NbOfItemsLabel, 0,0);
    CreateInfoLayout->addWidget(SpaceAvailLabel, 0,1);
    CreateInfoLayout->setAlignment(Qt::AlignCenter);

}

And I had a second method to just update the section when I want
void MainWindow::RefreshInfoSection()
{
    uint64_t space;

    NbOfItemsLabel = new QLabel(tr("%1 Files").arg(m_device.getNbOfFiles()));

    space = m_device.getAvailableFreeSpaceInBytes();

    if(space < MEGABYTE)
        SpaceAvailLabel = new QLabel(tr("%1 KB Available").arg(space/KILOBYTE));
    else if (space < GIGABYTE)
        SpaceAvailLabel = new QLabel(tr("%1 MB Available").arg(space/MEGABYTE));
    else
        SpaceAvailLabel = new QLabel(tr("%1 GB Available").arg(space/GIGABYTE));
}

the space available is get from a method declared in another class that I'm accessing using m_device. getAvailableFreeSpaceInBytes is defined as below in my mtp_wrapper class (in mtp_wrapper.cpp)
uint64_t mtp_wrapper::getAvailableFreeSpaceInBytes() {
    return PulsDeviceMngr->device->storage->FreeSpaceInBytes;
}

The PulsDeviceMngr is a structure which contain multiple elements.
What I'm looking for is a way to detect the change/update the value of FreeSpaceInBytes and update the section defined in my MainWindow using RefreshInfoSection as RefreshInfoSection due have a way to update the section and QLabel.
I'm pretty sure that it can be done by CONNECT/SLOT/SIGNAL
Any idea/examples.

A: What is m_device? It is the responsibily of m_device to notify others of changes. If it is possible, add a signal ChangeInBytes to m_device and then connect interested parties to that signal using roughly the following:
connect(SIGNAL(m_device->ChangeInBytes), SLOT(interested_party->slot))

If you can't modify m_device, you should probably create a wrapper-class, checking for changes in an appropriate way.

A: You cannot monitor a variable, you need either a setter for the variable, that as suggested, raise a signal, or some sort of pooling on the variable itself to detect changes but this may be overkill.


text:
Q: Why werl executes the same code in one shell window and freezes in another? I am trying to solve excercise 5-2 from O'Reilly Erlang Programming book.
My setup is Win10, werl Eshell V7.3.
Here are steps to reproduce my problem:

*

*c(frequency).

*frequency:start().

*CTRL-G -> S -> C -- to switch to new Erlang shell

*frequency:allocate().

*frequency:deallocate(10).
If I omit point 3 then all goes fine, but when I do everything according to above procedure, then shell gets stuck in line 30 or 43.
Can someone explain me what am I doing wrong and how to get the exactly same behavior for these two cases: with one, and with two shells?
Module's code (there are two warnings here, but it compiles anyway, I was trying to get deallocation allowed only when called from the same Pid from which allocation was being done):
-module(frequency).
-export([start/0, stop/0, allocate/0, deallocate/1]).
-export([init/0]).

%% These are the start functions used to crate and
%% initialize the server.

start() ->
  register(frequency, spawn(frequency, init, [])).

init() ->
  Frequencies = {get_frequencies(), []},
  loop(Frequencies).

% Hard Coded
get_frequencies() -> [10, 11, 12, 13, 14, 15].

%% The client Functions

stop()          -> call(stop).
allocate()      -> call(allocate).
deallocate(Freq)-> io:format("Calling deallocate~n",[]), call({deallocate, Freq}).

%% We hide all message passing and the message
%% protocol in a functional interface.

call(Message) ->
  Self = self(),
  io:format("Self: ~w~n", [Self]),
  frequency ! {request, Self, Message},
  receive
    {reply, Reply} -> Reply
  end.

%% The Main Loop

loop(Frequencies) ->
  receive
    {request, Pid, allocate} ->
      {NewFrequencies, Reply} = allocate(Frequencies, Pid),
      reply(Pid, Reply),
      loop(NewFrequencies);
    {request, Pid2, {deallocate, Freq}} ->
      io:format("Dealocate ~w from pid ~w~n", [Freq, Pid2]),
      NewFrequencies = deallocate(Frequencies, Freq), %, Pid2),
      reply(Pid2, ok),
      loop(NewFrequencies);
    {request, Pid, stop} ->
      reply(Pid, ok)
  end.

reply(Pid, Reply) ->
  Pid ! {reply, Reply}.

%% The Internal Help Functions used to allocate and
%% deallocate frequencies.

allocate({[], Allocated}, _Pid) ->
  {{[], Allocated}, {error, no_frequency}};
allocate({[Freq|Free], Allocated}, Pid) ->
  {{Free, [{Freq, Pid}| Allocated]}, {ok, Freq}}.

deallocate({Free, Allocated}, Freq) -> %, Pid) ->
  Response = lists:keysearch(Freq, 1, Allocated),
  io:format("Response: ~w~n", [Response]),
  case Response of
    {value, {Freq, OPid}} ->
        case OPid of
          Pid ->
            NewAllocated = lists:keydelete(Freq, 1, Allocated),
            io:format("Removed freq~n",[]),
            {[Freq|Free], NewAllocated};
          _OtherPid ->
            io:format("Not allowed to remove freq~n",[]),
            {Free, Allocated}
        end;
    _ -> io:format("Not removed freq~n",[]), {Free, Allocated}
  end.

A: I have not a complete explanation of the problem, but it is linked to the usage of io:format, there is an obscure (obscure for me :o) concept of group leader which is used to determine on which shell an io:format should display a message.
In general, it is not a good idea to display messages in a server loop, which is executed in the server process, it is better to do it in the interface functions executed in the calling process.
I have change your code a little, removing the useless print and corrected the test of pid and it works fine in multiple shells.
-module(freq).
-export([start/0, stop/0, allocate/0, deallocate/1]).
-export([init/0]).

%% These are the start functions used to crate and
%% initialize the server.

start() ->
  register(frequency, spawn(freq, init, [])).

init() ->
  Frequencies = {get_frequencies(), []},
  loop(Frequencies).

% Hard Coded
get_frequencies() -> [10, 11, 12, 13, 14, 15].

%% The client Functions

stop()          -> call(stop).
allocate()      -> call(allocate).
deallocate(Freq)-> io:format("Calling deallocate~n",[]), call({deallocate, Freq}).

%% We hide all message passing and the message
%% protocol in a functional interface.

call(Message) ->
  Self = self(),
  frequency ! {request, Self, Message},
  receive
    {reply, Reply} -> Reply
  end.

%% The Main Loop

loop(Frequencies) ->
  receive
    {request, Pid, allocate} ->
      {NewFrequencies, Reply} = allocate(Frequencies, Pid),
      reply(Pid, Reply),
      loop(NewFrequencies);
    {request, Pid, {deallocate, Freq}} ->
      {NewFrequencies,Reply} = deallocate(Frequencies, Freq, Pid),
      reply(Pid, Reply),
      loop(NewFrequencies);
    {request, Pid, stop} ->
      reply(Pid, ok)
  end.

reply(Pid, Reply) ->
  Pid ! {reply, Reply}.

%% The Internal Help Functions used to allocate and
%% deallocate frequencies.

allocate({[], Allocated}, _Pid) ->
  {{[], Allocated}, {error, no_frequency}};
allocate({[Freq|Free], Allocated}, Pid) ->
  {{Free, [{Freq, Pid}| Allocated]}, {ok, Freq}}.

deallocate({Free, Allocated}, Freq, Pid) ->
  Response = lists:keysearch(Freq, 1, Allocated),
  case Response of
    {value, {Freq, Pid}} ->
      NewAllocated = lists:keydelete(Freq, 1, Allocated),
      {{[Freq|Free], NewAllocated},removed};
    {value, {Freq, _OtherPid}} ->
      {{Free, Allocated},not_owner};
    _ ->
      {{Free, Allocated},not_found}
  end.


text:
Q: Amazon saying S3 bucket doesn't exist I created a bucket on Amazon S3 and went to the url (which is a url I need to put in an initializer in my rails app)
https://mtest73.s3.amazonaws.com/

and got this message
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
NoSuchBucket
<Message>The specified bucket does not exist</Message>
<BucketName>mtest73</BucketName>
<RequestId>9FBDCC50303F4306</RequestId>
<HostId>
owG6PSSjvcS7QZwEMKzTjMnYiwclXkRG7QGIF/Ly+jc8mHnmbvWHXqitDzfjnzgM
</HostId>
</Error>

However, in the Amazon console i've even uploaded a small file to this bucket.
Is there a reason for this? I thought it might be saying the bucket doesn't exist due to security reasons, but if there's something I've done wrong it might be why I can't get my Rails application to work...

A: @JohnFlatness and @pjotr pointed out, I wrote the wrong url
https://mtest73.s3.amazonaws.com/

It should have been
https://73mtest.s3.amazonaws.com/


text:
Q: Inserting variable values into variable columns in C#/MySQL My issue is that I import any kind of excel file which leads to a random amount of Columns and therefor values stores in these columns.
This is my string to  ExecuteNonQuery it;

    getAllValuesString = "INSERT INTO " + dbName + " (" + addHeader + " ) VALUES ('" + addValue + "')";

dbName is just the table name -> irrelevant right now
addHeader are the column names all in one string => "Column1 , Column 2"
addValue is one string for all the values  => "@value1 , @value2"
Now of course when I do =>

    cmdAddRow.Parameters.AddWithValue("@addValue", addValue);

then I only have 1 value added but 2 columns and it won't work.
I'm looking for the right format to AddWithValue all values of the addValue string no matter how many there are but I haven't found the right format yet. I tried to weave in an array and add it like that but with no success.
I'm trying to do this without Bulkadding the whole thing - any ideas?


text:
Q: Powershell Script to deploy multiple software using variables I am building a deployment script to install software on a new device using a ppkg file.
The script looks at which drive is the USB drive and copies the software over to the local temp folder and runs them according to a set of variables as shown below.
What I am struggling to do is simplify the script so I am not repeating code 7 times down the page, I want to just run a loop 7 times to pull in the needed software. I tried an array but I think I am not quite understanding it completely.
This is my script so far with the repeating code:
#SOE application Variables

#applcation1 CM_client
$app1name = "Config Manager Client 1706"
$app1skip = "no"
$app1path = "$env:SystemDrive\temp\soe\application_installs\app1\CM_client_inst_1706\"
$app1runcommand = "clientx64.bat"
$app1arguments = ""
#applcation2
$app2name = "Office 2016 Pro Plus"
$app2skip = "no"
$app2path = "$env:SystemDrive\temp\soe\application_installs\app2\O2016\"
$app2runcommand = "setup.exe"
$app2arguments = "/configure configuration.xml"
#log Folder
$datetime = Get-Date -format "yyyy.MM.dd-HH.mm.ss"
$logpath = "$env:ALLUSERSPROFILE\SOEInst_ppkg\$datetime"
New-Item -Path $logpath -ItemType Directory -ErrorAction SilentlyContinue

#Transcript Start
Start-Transcript -Path $logpath\SOE-app-installer-ppkg-$datetime.log

#Timer Function
$pkgremovetime = Get-Date -format "HH:mm:ss"
write-host "Script Start Time - $pkgremovetime"

#Find USB Drive
Write-host Discovering USB Drive

$drives = (GET-WMIOBJECT –query "SELECT * from win32_logicaldisk").DeviceID

foreach ($drive in $drives) {

            $usbdrive = (dir $drive USBIMG.FILE | Select-Object -Unique "USBIMG.FILE")
            if ($usbdrive -match "USBIMG.FILE*") {
                    $datadrive = $drive
                    }
            }

Write-host Found $datadrive is the USB drive

#Copy Applications to Local Drive
Write-Host Creating Installer Folder
New-Item -Path $env:SystemDrive\temp\SOE -ItemType Directory
Copy-Item $datadrive\application_installs $env:SystemDrive\temp\soe -Recurse -Verbose

#Install Applications
#Application 1
    if ($app1skip -eq "no") {
    if ($app1arguments) { #Arguments Variable Populated
        Write-Host Installing Applcation 1 `($app1name`)
        $app1 = Start-Process -Wait -FilePath $app1path$app1runcommand -ErrorAction Continue -ArgumentList $app1arguments -WindowStyle Normal
            if ($app1.ExitCode -eq "0") {
                Write-Host $app1name Installed ok
                } Else {
                    Write-host $app1name install exited with code $app1.ExitCode
                    }
                }
            }Else { #Argurments Variable Empty
                Write-Host Installing Applcation 1 `($app1name`)
                $app1 = Start-Process -Wait -FilePath $app1path$app1runcommand -ErrorAction Continue -WindowStyle Normal
                if ($app1.ExitCode -eq "0") {
                    Write-Host $app1name Installed ok
                    } Else {
                        Write-host $app1name install exited with code $app1.ExitCode
                }
            }

#Application 2
if ($app2skip -eq "no") {
    if ($app2arguments) { #Arguments Variable Populated
        Write-Host Installing Applcation 2 `($app2name`)
        $app2 = Start-Process -Wait -FilePath $app2path$app2runcommand -ErrorAction Continue -ArgumentList $app2arguments -WindowStyle Normal
            if ($app2.ExitCode -eq "0") {
                Write-Host $app2name Installed ok
                } Else {
                    Write-host $app2name install exited with code $app2.ExitCode
                    }
                }
            }Else { #Argurments Variable Empty
                Write-Host Installing Applcation 2 `($app2name`)
                $app2 = Start-Process -Wait -FilePath $app2path$app2runcommand -ErrorAction Continue -WindowStyle Normal
                if ($app2.ExitCode -eq "0") {
                    Write-Host $app2name Installed ok
                    } Else {
                        Write-host $app2name install exited with code $app2.ExitCode
                }
            }
#cleanup

Remove-Item $env:SystemDrive\temp\soe -Recurse -Force -Verbose

#get end time
$pkgremovetime_end = Get-Date -format "HH:mm:ss"

#calculate time difference
$timetaken = New-TimeSpan $pkgremovetime $pkgremovetime_end
    if ($timetaken.Seconds -lt 0) {
$Hrs = ($timetaken.Hours) + 23
$Mins = ($timetaken.Minutes) + 59
$Secs = ($timetaken.Seconds) + 59 }
    else {
$Hrs = $timetaken.Hours
$Mins = $timetaken.Minutes
$Secs = $timetaken.Seconds }
$Difference = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs

#log time difference
write-host "Script End Time - $pkgremovetime_end"
Write-Host "Total time taken $difference"

#Transcript End
Stop-Transcript

A: I suggest you make a function which takes in the variables. I did a quick comparison of your installation codes and something like this should work
function installApplication{
    Param($skip, $arguments, $name, $path, $runcommand)
    if ($skip -eq "no"){
        if ($arguments){
            write-host "Installing Application $appname"
            $app = Start-Process -Wait -FilePath $path$runcommand -ErrorAction....
            if($app.ExitCode -eq "0"){
            ....
            ....
}

and so on, You can then call the function using
installApplication $app1skip $app1arguments $app1name $app1path $app1runcommand
installApplication $app2skip $app2arguments $app2name $app2path $app1runcommand

Your input arguments will replace the function parameters in the order you pass them in, or you can use -skip $app1skip to assign the parameters.
If your repeating the same code too many times, I suggest throwing it into something like diffchecker, put the code into a function and replace all the differences with variables.
You can see your code here https://www.diffchecker.com/FxAIdD6g (1 Day only)


text:
Q: Retrieve bounds of an augmented object I'm attempting to anchor a ViewRenderable to a ModelRenderable so that it appears on the top right corner of the Renderable & I use the following snippet to place it.
    //Sets the button north east of the node that it is attached to
    viewRenderable.localPosition = Vector3(
            parent.right.x,
            parent.up.y,
            parent.right.z
    )

However, the viewRenderable doesn't really show up as intended. It rather shows up a few floats away from the top right corner of the ModelRenderable. Is there a way I can get the actual bounds of the ModelRenderable so that I can place it better? I want the end result something similar to the below picture.

What I have right now is this image:

My code:
//Creation of ViewRenderable
val shareButton = ViewRenderable.builder()
    .setVerticalAlignment(ViewRenderable.VerticalAlignment.TOP)
    .setHorizontalAlignment(ViewRenderable.HorizontalAlignment.RIGHT)
    .setView(view.getARFragment().context, R.layout.share)
    .build()

//Creation of ModelRenderable
val video = ModelRenderable.builder()
    .setSource(view.getARFragment().context,
        Uri.parse("chroma_key_video.sfb")).build()

//Adding Model to the scene | Extension method called on ParentNode
private fun Node.attachVideoNode(videoRenderable: ModelRenderable?) {
    //Show another anchor object
    val videoNode = Node()
    //Attach the new node with the node that this method was called on
    videoNode.setParent(this@attachVideoNode)
    //Set local position
    videoNode.localPosition = this.right //This works fine. The video is rendered next to another ModelRenderable.

    // Set the scale of the node so that the aspect ratio of the video is correct.
    val videoWidth = mediaPlayer?.videoWidth?.toFloat()
    val videoHeight = mediaPlayer?.videoHeight?.toFloat()
    videoHeight?.let {
        videoWidth?.apply {
            videoNode.localScale = Vector3(
                    (this@apply / it), 1.0f, 1.0f)
        }
    }

    // Start playing the video when the first node is placed.
    mediaPlayer?.apply {
        if (!isPlaying) {
            start()
            // Wait to set the renderable until the first frame of the  video becomes available.
            // This prevents the renderable from briefly appearing as a black quad before the video
            // plays.
            texture?.surfaceTexture
                    ?.setOnFrameAvailableListener { surfaceTexture ->
                        videoNode.renderable = videoRenderable
                        surfaceTexture.setOnFrameAvailableListener(null)
                        //Attach a share button
                        videoNode.attachShareButton()
                        ARApplication.log("The local rotation of this videoRenderable is ${videoNode.localRotation}")
                    }
        } else
            videoNode.renderable = videoRenderable
    }
}

//Attaches a share button to any node that it is called on. | Extension method called on VideoNode
private fun Node.attachShareButton() {
    //Create a new node to display the close button
    var closeButton = Node()
    closeButton.setParent(this)
    ARApplication.log("The close button has been added to the scene at world coordinates: ${closeButton.worldPosition}")

    //Set the close button as a renderable
    closeButton.renderable = view.getViewRenderable()
}

A: I don't know exactly what you already got, but this is a solution for put a text on the ViewRenderable on the top and on the right
x x V
x O x
x x x
V - ViewRenderable
O - ModelRenderable
ViewRenderable.builder()
                .setView(context, R.layout.VIEW_LAYOUT_XXXXX)
                .setHorizontalAlignment(ViewRenderable.HorizontalAlignment.RIGHT) //Here is where the magic happens
                .build()
                .thenAccept(
                        (renderable) -> {
                            YOUR_NODE_XXXXX.setRenderable(renderable);
                            TextView textView = (TextView) renderable.getView();
                            textView.setText(YOUR_TEXT_XXXXX);
                        })
                .exceptionally(
                        (throwable) -> {
                            throw new AssertionError(R.string.ERROR_MSG_XXXXX, throwable);
                        });

I let a _XXXXXin everything that you should change with your code.
Result should be like this

EDIT. Ok looking your code now this is what you should do:
Firs you need to inicialize your view (I think your "close button" should be your share button)
private fun Node.attachShareButton() {
if(shareButton == null){ //Create a new node to display the share button
    var shareButton = Node()
    shareButton.setParent(this)
    shareButton.renderable = view.getViewRenderable()
    shareButton.setLocalPosition(new Vector3(SIZE_OF_BUTTON, SIZE_OF_BUTTON, SIZE_OF_BUTTON));
}

if (infoCard == null) {
  infoCard = new Node();
  infoCard.setParent(this);
  infoCard.setEnabled(false);
  infoCard.setLocalPosition(new Vector3(0.0f, SIZE_OF_BUTTON*0.55f, 0.0f));

  ViewRenderable.builder()
      .setView(context,  R.layout.share)
      .setHorizontalAlignment(ViewRenderable.HorizontalAlignment.RIGHT)
      .build()
      .thenAccept(
          (renderable) -> {
            infoCard.setRenderable(renderable);
          })
      .exceptionally(
          (throwable) -> {
            throw new AssertionError(R.string.ERROR_MSG_XXXXX, throwable);
          });
}

shareButton.onTap(HitTestResult hitTestResult, MotionEvent motionEvent){
    if (infoCard == null) {
        return;
    }

    infoCard.setEnabled(!infoCard.isEnabled()); //This show your card when the button is click/tap
}
}


text:
Q: the request failed with http status 401 unauthorized ssrs I am developing a web application using Asp.net & c#. To generate a reports i am using SQL Server Business Intelligence Development Studio(ssrs).I get a error like "the request failed with http status 401 unauthorized" please help me
thanks in advance
The actual error is as follows
ex = {"The request failed with HTTP status 401: Unauthorized."}
{System.Net.WebException: The request failed with HTTP status 401: Unauthorized.
   at Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.GetSecureMethods()
   at Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.IsSecureMethod(String methodname)
   at Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.SetConnectionSSLForMethod(String methodname)
   at Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.ProxyMethodInvocation.Execute[TReturn](RSExecutionConnection connection, ProxyMethod1 initialMethod, ProxyMethod1 retryMethod)
   at Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.LoadReport(String Report, String HistoryID)
   at Microsoft.Reporting.WebForms.ServerReport.EnsureExecutionSession()
   at Microsoft.Reporting.WebForms.ServerReport.SetParameters(IEnumerable`1 parameters)
   at Microsoft.Reporting.WebForms.Report.SetParameters(ReportParameter parameter)
   at Reports_CustomerWtrEff.GetReports(String SampleCodes, String lstSampleCode) in CustomerWtrEff.aspx.cs:line 98}

A: Check out this link below, as it could lend an answer to your problem.
REF: http://www.taznetworks.com/rss/2006/03/crm-30-sbe-sql-reporting-error.html
EDIT:

In doing some work with CRM recently on some test installs we kept coming up with the error that "Setup failed to validate specified Reporting Services Report Server https://server.xxx.com/ReportServer. Error: The request failed with HTTP status 401: Unauthorized.
This seems to be a pretty common problem out there but not a lot of response to the issues. One thing I can say is that CRM is a good product but man is it complex in the guts of it. Not for the faint of heart that's for sure, especially when it comes to SQL and SQL reporting services.
Anyway back to the problem. In most cases with CRM 3 and SBS the documentation at such sites as Anne Stanton's show a problem with ISA. This box we were building didn't have ISA (as of yet).
The problem we were experiencing seems to be more with SP1 of Windows Server 2003 than anything else. The KB article 896861 seems to be spot on. We did the following according to the article:

*

*Click Start, click Run, type regedit, and then click OK.

*In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa

*Right-click Lsa, point to New, and then click DWORD Value.

*Type DisableLoopbackCheck, and then press ENTER.

*Right-click DisableLoopbackCheck, and then click Modify.

*In the Value data box, type 1, and then click OK.

*Quit Registry Editor, and then restart your computer.

  Doing this allowed us to get to https://servername/reports and show the full SQL Reporting Services web site. CRM Reports now work as they were meant to.

A: I faced this issue and tried more and more and finally found that

*

*open the reporting service configuration and connect to server then open web service url you will find the url copy it (URL)

*open your SQL server data tools project and in the project properties
target server URL is the mentioned URL in the reporting service configuration and target report folder is the name of the project

*in your asp.net project you will write the following code:
.
ReportViewer1.ProcessingMode =
Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri(**URL**);
ReportViewer1.ServerReport.ReportPath = String.Concat(**target report folder**, "name of the report ");
ReportViewer1.ServerReport.Refresh();


text:
Q: Boot loader problem After Installation of Ubuntu to my new HDD, I putted my existing Win 7 HDD to my motherboard.
Now when I tried to boot windows by default Ubuntu is opening.
Plz do let me know how to fix the boot loader of Ubuntu?

A: You need to define in your BIOS settings that the HDD that you want to boot is your Windows HDD, if you cannot find that option in your BIOS (99.9% will have it) you need to swap the cables between your Ubuntu HDD and your Windows HDD.
There should not be an issue here since you apparently installed Ubuntu and Windows in to 2 different disks: both have different MBR and boot loaders installed.
Either select which disk you want to boot from in your BIOS or swap the cables from one disk to the other.


text:
Q: eps figure fitting not exactly inside the \textwidth There is a *.eps figure of size exactly 6.5inch by 6.5inch (no white borders). This figure needs to be placed exactly inside the document, which has a \textwidth = 6.5".
Logically the *.eps should completely occupy the \textwidth space (which is exactly 6.5in) but due to some unknown reasons there remains a room left (few pt) in output *.pdf as shown below.
(The *.eps figure is not to be scaled, as its physical dimensions (inches) need to be preserved in final publishing.)
LuaTex with TexLive is used.

minimal example:
\RequirePackage[l2tabu, orthodox]{nag}
\RequirePackage{fix-cm}
\overfullrule=1mm
\documentclass[11pt,draftclsnofoot,onecolumn,conference]{IEEEtran}

\usepackage[showframe,pass]{geometry}
%\usepackage[pass]{geometry}
\usepackage[]{layout}

\usepackage{graphicx}
\usepackage[cmex10]{amsmath}
\interdisplaylinepenalty=2500

\usepackage{amssymb}
\usepackage{amsfonts}

%\usepackage{caption}
\usepackage{subcaption}
%\usepackage[labelformat=simple]{subcaption}
%\usepackage{subfig}
%\usepackage[caption=false]{subfig}

\usepackage[noadjust]{cite}
\usepackage{epstopdf}

%\usepackage[outdir=./]{epstopdf}

\usepackage[x11names]{xcolor}
\usepackage{setspace}

%\usepackage{showkeys}
%\usepackage[disable,colorinlistoftodos]{todonotes}
\usepackage[obeyDraft,colorinlistoftodos]{todonotes}

\usepackage[T1]{fontenc}
%\usepackage[utf8]{inputenc}
\usepackage{charter}
\usepackage{environ}
\usepackage{tikz}
\usetikzlibrary{calc,matrix}

\usepackage[section]{placeins} % it keeps the figures in the respective section
\usepackage{stackengine}

\usepackage{microtype}

\usepackage[colorlinks]{hyperref}
\hypersetup{%
    colorlinks = true,
    citecolor=Green4,
    linkcolor  = blue
}

\pagebreak

% *** GRAPHICS RELATED PACKAGES ***
%
\ifCLASSINFOpdf
  % \usepackage[pdftex]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../pdf/}{../jpeg/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.pdf,.jpeg,.png}
\else
  % or other class option (dvipsone, dvipdf, if not using dvips). graphicx
  % will default to the driver specified in the system graphics.cfg if no
  % driver is specified.
  % \usepackage[dvips]{graphicx}
  % declare the path(s) where your graphic files are
  % \graphicspath{{../eps/}}
  % and their extensions so you won't have to specify these with
  % every instance of \includegraphics
  % \DeclareGraphicsExtensions{.eps}
\fi
% graphicx was written by David Carlisle and Sebastian Rahtz. It is
% required if you want graphics, photos, etc. graphicx.sty is already
% installed on most LaTeX systems. The latest version and documentation can
% be obtained at:

% correct bad hyphenation here
\hyphenation{}

\begin{document}
 \begin{figure}[h]
%   \centering
%   \captionsetup{justification=centering}
    \includegraphics[width=6.5in,height=6.5in,keepaspectratio]{out.eps}
    \caption{My caption}
    \label{f02}
 \end{figure}

\layout
\end{document}


text:
Q: Array of Javascript Objects To Php Array How to decode this array of object to Php array,
I used json_decode() but that returned Null
$a = "[
{
    id:1,
    name:'rajan',
    class:10
},{
    id:2,
    name:'amrit',
    class:12
},{
    id:3,
    name:'arun',
    class:11
}
]";

A: Your JSON is not valid, which is why json_decode is returning null.
SyntaxError: Unexpected token i
http://json.parser.online.fr/
http://php.net/manual/en/function.json-decode.php

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

I have also fixed your JSON:
[
{
    "id": 1,
    "name":"rajan",
    "class":10
},{
    "id":2,
    "name":"amrit",
    "class":12
},{
    "id":3,
    "name":"arun",
    "class":11
}
]

Fixing your broken JSON with code:
$replace_keys = preg_replace("/(\w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'(\w*)'/i", ':"$1"', $replace_keys);

You can then use $replace_keys in json_decode. I am not sure if this is the best method, as small variations in your json could break it, but it fixes it with the example provided.

Full code to fix JSON:
$a = "[
{
    id:1,
    name:'rajan',
    class:10
},{
    id:2,
    name:'amrit',
    class:12
},{
    id:3,
    name:'arun',
    class:11
}
]";

$replace_keys = preg_replace("/(\w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'(\w*)'/i", ':"$1"', $replace_keys);

die($fix_values);


text:
Q: OpAmp comparator circuit having unexpected behavior I'm working with the following circuit. It integrates a constant current, and when the output reachs a threshold, another circuit activates the switch, discharging the capacitor. The switch is simplemented with a transmission gate, and it is on long enough for the capacitor to discarge through the transmission's gate resistance.

What I'm expecting, is that when the switch is on, the capacitor is discharged to 0V, thus taking the output to Vref1 (1,3V). This is what happens when I simulate with an ideal opamp

In red is the control signal, when it turns on, the capacitor voltage (cyan signal) goes to zero, making the output signal equal the voltage of the non inverting terminal, 1.3V.
However, when I replace the ideal opamp by another one designed by me (a simple two stage opamp), the signals behave unexpectedly, as shown in the following figures

The capacitor indeed discharges completley to zero, but the output signal does not change to 1.3V as expected. After the control signal goes to zero, all signals start to grow, until the ouput reachs almost Vdd (1.8V), as seen in the following figure

I suspect this is being caused by one of the parameters of the custom opamp not being ideal, but I don't know which one. I thought of the gain not being enough, but a simulation with another opamp with less gain resulted in an overshoot not so big, as it can be seen in this figure

With an opamp with less gain, the output is not settling at 1.3V as expected, but it settling at a much closer value than the opamp with higher gain. So, apparently, less gain gives a better result.
Any help is appreciated.
EDIT:
Here is the opamp implementation

A: Your system is unstable because you have a pole in the right half plane, and the result is that the output grows unbounded.
Any non-ideal op-amp has a finite DC gain \$\ A_0 \$ and a finite bandwith (crossover frequency \$\ \omega_c\$ below infinity) such a non ideal op-amp can be approximated as a single pole low pass filter, with the following transfer function;
$$ G(s)=\frac{A_0}{1+\frac{s}{\omega_c}}$$
Any non-ideal op-amp also has a finite input impedance \$\ Z_{in}\$, which can be approximated by a parallel RC circuit;
$$ Z_{in}=\frac{1}{C_{in}\cdot s+\frac{1}{R_{in}}} $$
Where \$\ C_{in} \$ is the input capacitance, and \$\ R_{in} \$ is the input resistance of your op-amp. Your feedback path is not just a capacitor, but a voltage divider consisting of \$\ C_1\$, \$\ C_{in}\$ and \$\ R_{in}\$. This means that the feedback transfer function of your circuit is;
$$ H(s)=\frac{C_{1}s}{(C_{1}+C_{in})s+\frac{1}{R_{in}}} $$
And the input transfer function is;
$$ I(s)=\frac{-1}{(C_{1}+C_{in})\cdot s+\frac{1}{R_{in}}} $$
Now let's combine it all to get the closed loop transfer function of the system;
$$ T(s)=I(s)\frac{G(s)}{1+H(s)G(s)}=\frac{-1}{(C_{1}+C_{in})\cdot s+\frac{1}{R_{in}}}\frac{\frac{A_0}{1+\frac{s}{\omega_c}}}{1+\frac{C_{1}s}{(C_{1}+C_{in})s+\frac{1}{R_{in}}}\frac{A_0}{1+\frac{s}{\omega_c}}}=\frac{-A_0}{\frac{(C_{in}+C_{1})}{\omega_c}s^2+((1+A_0)C_{1}+C_{in}+\frac{1}{R_{in}\omega_c})s+\frac{1}{R_{in}}} $$
Solving for the poles of the closed loop transfer function you will find that at least one situation where you have a pole in the right half plane (your system is unstable) is if;
$$0<4\cdot \frac{(C_{in}+C_{1})}{\omega_c R_{in}}<((1+A_0)C_{1}+C_{in}+\frac{1}{R_{in}\omega_c})^2<1$$
(Which will be true at least as long as \$\ 0<C_1<<1\$, \$\ 0<C_{in}<<1\$, \$\ R_{in}>>1\$, \$\ A_{0}>>1\$ and \$\ \omega_{c}>1\$)
This is easy to prove using simple (but painstaking) algebra, so I want bother with it here..
To sum it up; Your system is unstable because you have a pole in the right half plane.
The most simple solution would be to add a resistor in parallel with \$\ C_1\$ which is sufficiently small to make the system stable, while being sufficiently large to not cause an unacceptable error in your system. In general in order to be able to rely on the assumptions/simplifications we use when we design op-amp circuit, such as your integrator circuit, one of the things we require is that \$\ Z_{feedback}<<Z_{in}\$ which is not true for your circuit.


text:
Q: How to compute a threshold for a given vector/array of float numbers Say I have the following example distribution (vector) of numbers in c++:
vector 1    vector 2   vector 3
11          4          65
128         6          66
12          4          64
13          4          62
12          5          65
14          5          63
16          7          190
60          3          210
120         4          220
126         5          242
77          6          231
14          4          210
12          7          222
13          6          260
11          8          300
14          6          233
99                     80
15                     66
13

I need to find a threshold for each vector. I'll eliminate the larger ("bad") numbers in each if they are above that vector's threshold. I want to re-use this method to find a threshold on other similar vectors in the future. The numbers aren't necessarily mostly smaller "good" numbers.
The threshold would ideally be just a hair larger than most of the smaller "good" numbers. For example, the first vetor's ideal threshold value would be around 17 or 18, the second's would be about 8, and the third's would be around 68-70.
I realize this is probably simple math but since I'm horrible at math in general, I would really appreciate a code example on how to find this magical threshold, in either C++ or Objective-C specifically, which is why I'm posting this in SO and not on the Math site.
Some things I've tried
float threshold = mean_of_vector;
float threshold = mean_of_vector / 1.5f;
float threshold = ((max_of_vector - min_of_vector) / 2.0f) + mean_of_vector;

Each of these seem to have their own issues, eg: some include too many of the "good" average numbers (so the threshold was too low), some not enough good numbers (threshold too high), or not enough of the "bad" numbers. Sometimes they'll work with specific vectors of numbers, for example, if the standard deviation is high, but not others where the standard deviation is low.
I'm thinking the method would involve standard deviation and/or some sort of gaussian distribution, but I don't know how to piece them together to get the desired result.
Edit: I am able to re-sort the vectors.

A: You could just eliminate the values above 90% or 95%.
Technicaly you calculate the p =  0.9 (or 0.95) percentile of the array distribution.
Just sort the array ascending:
int[] data;

Arrays.sort(data); // or use ArrayList<Integer> which has Collections.sort(dataArrayList),

Then calculate position of percentile p:
float p = data.length * p; // e.g p = 0.9 for 90% percentile.
// cut of fractional part.
int posInt = (int) p;

// this is the threshold value
int threshold = data[posInt]

Now filter array by keeping all value < or <= threshold.
This keeps the 90% of smallest values.
int i = 0;
while (i < data.length && data[i] <= threshold) {
  // output data[i];
}

For mathematically "perfect" results you could search for "calculate percentile of discrete array / values).
As i remeber there are two valid algorithms, describeing whether one has to round down or round up the posInt. I my example above I just truncated.

A: An idea would be to compute both the mean mu and the standard deviation sigma (e.g. using the algorithm described at "Accurately computing running variance" ) and use both of them for the definition of your threshold.
If your data are assumed to be Gaussian, you know that 97.5% of your data should be below mu + 2*sigma, so that can be a good threshold.
Remark: you might want to recompute your threshold once you have rejected the extreme values since these values can have a significant impact on the mean and the standard deviation.
EDIT:
I just computed the thresholds using the method I proposed and it does not look satisfactory for you: for the first case, threshold is around 130 (so maybe taking 1.5 sigma could help getting rid of the largest entries), for the second case, threshold is around 8 and for the third case, threshold is around 262.
Actually, I'm not that surprised with these results: for your last example, you want to get rid of more than the half of the data! Assuming that the data are Gaussian with just a few extrem values is far from what you have at hand...


text:
Q: Read dict values one by one from dictionary in python I am new to python. I want to read dict values one by one from dictionary in python and print the output.
I am using below code and the issue is it is returning only the last query output.
def pk_record_count_check(localdf):

    try:
        sql = 'select count(distinct ' + localdf["business_key_name"] + ') as PK_CNT from ' + localdf["schema_table"]
        sql = sql.to_dict()
        pd.set_option("display.max_colwidth", None)
        for new_sql in sql.values():
            df = new_sql
            print(df)
        loging(datetime.datetime.now(), '-', df)
        df3 = pd.read_sql_query(df, db_connection)
        print (df3)
        return df3.PK_CNT[0]

Current output
"df"
select count(distinct PersonID) as PK_CNT from testdb.DimCurrency
select count(distinct `index`) as PK_CNT from testdb.banking_fraud
select count(distinct S_No) as PK_CNT from testdb.banking_fraud
   PK_CNT
0    1000

Expected output: it should return every query output.
   PK_CNT
0    0
   PK_CNT
0    1000
   PK_CNT
0    1000


text:
Q: Force-call a specific constructor in a parent's class I'm facing for the first time the following case:
I have the following java class:
public class Values extends ArrayList<Object>{
    public Values() {

    }

    public Values(Object... vals) {
        super(vals.length);
        for(Object o: vals) {
            add(o);
        }
    }
}

I would like to call the following parent's constructor:
public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
}

Is this possible ? I'm sending an int but it's caught by the Values's constructor.
Edit
What i'd like to do in the end is :
Map<String,Object> document = getDocument();
List<String> indexFields = getIndexFields();
Values values = new Values(indexFields.size());
for (String field : indexFields) {
    values.add(document.get(field));
}

A: If you want to call new Values(initialCapacity) where initialCapacity is an int, then you should have such a constructor in the Values class:
public Values(int initialCapacity) {
    super(initialCapacity);
}

Note that it's generally not a good idea to extend collection classes. Use them (delegation, composition) instead of extending them.


text:
Q: coding drag drop images on web page About a month ago, I got some wonderful help from Idle_Mind in developing a visual basic desktop application whereby children could drag & drop images (pictureboxes) in the correct order.  I've displayed the code that Idle_Mind provided below.  It works beautifully and is enjoyed by the students.
Now, I'm trying to recreate the application on a web site.  I'm using Visual Web Developer 2008 Express.   Using the same code in the "Code Behind" creates lots of errors.  It appears that Image controls don't have the same drag/drop properties.
Should I be trying to create these drag/drop behaviors from Visual Basic in the "code behind" or should I be trying to accomplish this with html?  The Visual Web Developer uses Visual Basic.net and XHTML 1.0 Transitional (I believe)
As always, Thanks!
Public Class Form1

    Private Source As PictureBox = Nothing

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each PB As PictureBox In Me.Controls.OfType(Of PictureBox)()
            PB.AllowDrop = True
            AddHandler PB.MouseMove, AddressOf PBs_MouseMove
            AddHandler PB.DragEnter, AddressOf PBs_DragEnter
            AddHandler PB.DragDrop, AddressOf PBs_DragDrop
            AddHandler PB.DragOver, AddressOf PBs_DragOver
        Next
    End Sub

    Private Sub PBs_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim PB As PictureBox = DirectCast(sender, PictureBox)
        If Not IsNothing(PB.Image) AndAlso e.Button = Windows.Forms.MouseButtons.Left Then
            Source = PB
            PB.DoDragDrop(PB.Image, DragDropEffects.Copy Or DragDropEffects.Move)
        End If
    End Sub

    Private Sub PBs_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.Bitmap) Then
            If My.Computer.Keyboard.CtrlKeyDown Then
                e.Effect = DragDropEffects.Copy
            Else
                e.Effect = DragDropEffects.Move
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub PBs_DragOver(sender As Object, e As DragEventArgs)
        If e.Data.GetDataPresent(DataFormats.Bitmap) Then
            If My.Computer.Keyboard.CtrlKeyDown Then
                e.Effect = DragDropEffects.Copy
            Else
                e.Effect = DragDropEffects.Move
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub PBs_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs)
        Dim PB As PictureBox = DirectCast(sender, PictureBox)
        PB.Image = e.Data.GetData(DataFormats.Bitmap)
        If e.Effect = DragDropEffects.Move Then
            If Not (PB Is Source) Then
                Source.Image = Nothing
            End If
        End If
    End Sub

End Class

A: A web application isn't a desktop application, it's a completely different technology stack.
The code-behind in this case is running entirely server-side and can't interact with the user interface in realtime.  You'd want to look into implementing this functionality in JavaScript.
Fortunately, things like drag and drop functionality have widely used plugins to help.  Take a look at the jQuery UI plugins, for example.  Or interact.js.  (See the demos on their website for what kind of functionality you'd be looking for.)  Or even just the MDN documentation.
It's not going to be as simple as copying and pasting code.  But there are a lot of resources to be found online to help you implement the functionality.


text:
Q: Save preferences I'm a beginner at Android programming, unfortunately I have a problem :)
I have method writeSettings() in my game in which I'm trying to save some variables to use it when want to load last game by readSettings() method. There are parameters such as first(second)PlayerName, first(second)PlayerScore and so on. I'm trying to use SharedPreferences to save them, but I get "Force Close" dialog, when starting program.
SharedPreferences preferences = getPreferences(MODE_PRIVATE); //Global variable

    private void writeSettings() {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putInt("timeSave", time);
                editor.putString("firstPlayerNameSave", firstPlayerNameTextView.getText().toString());
                editor.putString("secondPlayerNameSave", secondPlayerNameTextView.getText().toString());
                editor.putString("firstPlayerScoreSave", firstPlayerScoreTextView.getText().toString());
                editor.putString("secondPlayerScoreSave", secondPlayerScoreTextView.getText().toString());
                editor.putInt("nowPlayerSave", nowPlayer);
                editor.commit();

        }

       private void readSettings() {
    //"time" parameter program reads in another method
                    firstPlayerNameTextView.setText(preferences.getString("firstPlayerNameSave", ""));
                    secondPlayerNameTextView.setText(preferences.getString("secondPlayerNameSave", ""));
                    firstPlayerScoreTextView.setText(preferences.getString("firstPlayerScoreSave", ""));
                    secondPlayerScoreTextView.setText(preferences.getString("secondPlayerScoreSave", ""));
                    nowPlayer = preferences.getInt("nowPlayerSave", -1);

            }

How I could know, problem appears in first entry of writeSettings().
But I don't know what I'm doing wrong?
Sorry for my English.
upd.
12-23 16:23:31.334: ERROR/AndroidRuntime(410): Uncaught handler: thread main exiting due to uncaught exception
12-23 16:23:31.520: ERROR/AndroidRuntime(410): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.game/com.game.Game}: java.lang.NullPointerException
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.os.Looper.loop(Looper.java:123)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.ActivityThread.main(ActivityThread.java:4363)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at java.lang.reflect.Method.invokeNative(Native Method)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at java.lang.reflect.Method.invoke(Method.java:521)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at dalvik.system.NativeStart.main(Native Method)
12-23 16:23:31.520: ERROR/AndroidRuntime(410): Caused by: java.lang.NullPointerException
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.Activity.getLocalClassName(Activity.java:3410)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.Activity.getPreferences(Activity.java:3444)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at com.game.Game.<init>(Game.java:69)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at java.lang.Class.newInstanceImpl(Native Method)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at java.lang.Class.newInstance(Class.java:1479)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
12-23 16:23:31.520: ERROR/AndroidRuntime(410):     ... 11 more

Game.java:69 is a SharedPreferences preferences = getPreferences(MODE_PRIVATE);

A: This is how I do it:
Editor editor = PreferenceManager.getDefaultSharedPreferences(Context).edit();
                editor.putString("firstPlayerNameSave", firstPlayerNameTextView.getText().toString());
                editor.commit();

And to read:
firstPlayerNameTextView.setText(PreferenceManager.getDefaultSharedPreferences(Context).getString("firstPlayerNameSave", ""));

A: What I do is almost identical to what martipelant suggested.
Getting the editor:
Editor preferenceEditor = getSharedPreferences("com.mycompany.android.myapp",MODE_PRIVATE).edit();

And reading:
       mSharedPreferences = getSharedPreferences("com.mycompany.android.myapp",Context.MODE_PRIVATE);

A: AFAIK Activity.getPreferences() is a wrapper for Context.getSharedPreferences(String, int) where String is the name of the activity.
It should be used only for accessing preferences that are private to this activity.
Try to change the code
SharedPreferences preferences = getPreferences(MODE_PRIVATE);

to
SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(context);

A: Save preferences in android shared preferences
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getContext()).edit(); editor.putString("firstPlayerNameSave", firstPlayerNameTextView.getText().toString()); editor.apply();


text:
Q: Perl Print regex matches from an array to a html  I have the following code in perl which is outputting each value of an array to a new HTML table cell and table row
print "
$_

\n" for @fruitArray;

The contents of the array are as follows:
APPLE|0
ORANGE|0
PEAR|1
GRAPE|0
TOMATO|1

I want to print everything before the | in the first table cell and then everything after the | in a second table cell on that row
I presume I need to use regex something like:
/([|])\w+/

Just unsure on the exact syntax of printing this in one line

A: This is really very simple
use strict;
use warnings 'all';

my @data = qw/
    APPLE|0
    ORANGE|0
    PEAR|1
    GRAPE|0
    TOMATO|1
/;

print "
\n";
printf "
%s	%s
\n", split /\|/ for @data;
print "
\n";

output

APPLE	0

ORANGE	0

PEAR	1

GRAPE	0

TOMATO	1

A: You may need something like:
#!/usr/bin/perl
use strict;
use warnings;

my @names = ("APPLE|0", "ORANGE|0", "PEAR|1", "GRAPE|0", "TOMATO|1");

foreach my $n (@names) {
while ($n =~ m/(.*?)\|(\d+)/g) {
        print "
$1

\n";
        print "
$2

\n";
    }
}

Output:

APPLE

0

ORANGE

0

PEAR

1

GRAPE

0

TOMATO

1

DEMO:
http://ideone.com/QPOvzd


text:
Q: How do you left pad a hexadecimal number? If i have a set of data such as the following, how do I set it so that all numbers are 8 nibbles long?
A1: FF4C6EFF
A2: 286EFF
A3: 1156EFF
A4: 2806EF7

The TEXT command doesn't work.
=TEXT(A2, "00000000")
B2: 286EFF

A: You need to use the DEC2HEX with the places command to do this:
DEC2HEX(number, [places])

=DEC2HEX(HEX2DEC(A2), 8)

B2: 00286EFF


text:
Q: I used a webpack, but why isn't the request reduce? I used a webpack, but why wouldn't I get fewer requests?
Executed script command "npm run dev".
I was Access localhost:9000
But why aren't the http requests decreasing?
As far as I know, a webpack binds files.
I checked the Network tab, but the bundle doesn't work.
enter image description here
Please, Check my setting...
package.json file
{
  "name": "dev-server-test1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.0.1",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  }
}

webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'none',
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devServer: {
    port: 9000,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'index.html',
    }),
  ],
};

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>DevServer</title>
  </head>
  <body>
    <div class="container">
      TEST..
    </div>
  </body>
</html>

index.js
var div = document.querySelector('.container');
div.innerText = 'load Webpack!!';

A: module.exports = {
  mode: 'none',
  entry: './index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  }

your webpack.config.js takes an index.js as an entry and outputs a bundle.js file.
Now if your index.js looks like this:
console.log("Script loaded");

this will be outputed on the bundle.js file. There is no binding or module bundling even if you use webpack.
However if your index.js was:
import './script1.js'
import './script2.js'

when you run webpack it will bundle these scripts into one script bundle.js which actually reducing server requests as you will have 1 script instead of loading them separately.


text:
Q: Properly use .ui with pyQt5 my goal is to bring a .ui interface in a python program.
It barely works but I would like to improve it since I can't obtain exactly what I want.
class MainWindow(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.ui = uic.loadUi('sss.ui')
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.ui)
        self.setLayout(mainLayout)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    sys.exit(app.exec_())

For now I have to create a layout to paste my sss.ui to.
The QVboxLayout dosen't respect the stylesheet I setup in Qt Designer.
How can I use my sss.ui directly ?
Do I need to convert it ? I unable to find the pyuic5 in my Qt install ...

A: First, obtain the pyuic5 executable. Try to reinstall PyQt, search for it in bin directories (system-wide, virtualenv, etc.).
Once you have it, you should compile your .ui file using it:
pyuic5 sss.ui > ui_sss.py

Then use it in your code:
import sys

from PyQt5.QtWidgets import QWidget, QApplication

from ui_sss import Ui_sss  # if toplevel widget in .ui file is also called "sss"

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(self, parent)
        self.ui = Ui_sss()
        self.ui.setupUi(self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


text:
Q: which is the correct way to use in Use Case Diagram

I just create this diagram  can anyone tell me if these 2 pictures are correct or wrong and which one should I use?,  can anyone tell  which is correct in these 2 pictures.

A: Both diagrams are ok, except:

*

*the association between an actor and a use case should be straight lines and not directed arrows.  These arrows are an obsolete practice.

*the subject rectangle should be closed

*actors not related to anything are useless and should be removed

The question of whether add and edit should be in the same use case or in distinct ones is up to you to decide:

*

*grouping them has the benefit of simplifying the model.  Manage students could be even more generic and is quite common.

*keeping them separate may appear more granular but makes sense if there are different actors or if the business needs are very different.

You may read more to make up your mind, googling for CRUD Use case.


text:
Q: In flickity, how can I use arrowkeys without leftclick or tab? this is Flickity
I cannot express in English clearly, so if possible please help editing my question.
This is my web page
https://codepen.io/haozun/pen/ywNjvQ

When I open this page, I cannot use arrowkey to navigate different carousel-cell.
I can only use arrowkey after I have mouse clicking on that page.
How can I edit the code so that I can use arrowkey at the very beginning without click on it? i.e. I open this page in my browser, and then I can use arrowkey(37,39) to rotate it immediately. I want to use the keyboardHandlers once I open the page
Flickity.keyboardHandlers = {
// left arrow
37: function() {
  var leftMethod = this.options.rightToLeft ? 'next' : 'previous';
  this.uiChange();
  this[ leftMethod ]();
},
// right arrow
39: function() {
  var rightMethod = this.options.rightToLeft ? 'previous' : 'next';
  this.uiChange();
  this[ rightMethod ]();
},

};
I can edit all source code, including flickity.pkgd.min.js. And my page only contains one flickity.

The official site tells we must use tab (or leftclick) first, then we can really use arrowkeys to change cells.

A: It almost impossible someone-else will answer this question, And the former answerer has rejected my edit, so I have to answer myself.
Adding this to JS
document.addEventListener("DOMContentLoaded", function() {
  init();
});

function init() {
  let flkty = new Flickity(".carousel");
  flkty.focus()
}

A: You need to create a new Flickity instance when your app initializes, then call next() on it. You can see in the demo below that as soon as you load your app, it will scroll to the next item in the carousel:

let flkty;
const delayMs = 1000;

document.addEventListener("DOMContentLoaded", function() {
  init(true);
});

function init(shouldAutoScroll) {
  flkty = new Flickity(".carousel");

  if (shouldAutoScroll) {
    //Start an carousel auto scroll
    autoScroll();
  } else {
    //Just flip to next item and that's it..
    flkty.next();
  }
}

function autoScroll() {
  if (flkty) {
    setInterval(function() {
      flkty.next();
    }, delayMs);
  }
}
.carousel-cell {
  min-height: 30em;
  padding: 1em;
  margin: 0 3em 0 3em;
  width: calc( 100vw - 9em);
  max-width: 40em;
  box-shadow: 0px 16px 20px 5px #7777;
}

  <link rel="stylesheet" href="https://unpkg.com/flickity@2/dist/flickity.min.css">

1LONGLONGLONGLONG

2LONGLONGLONGLONG

3LONGLONGLONGLONG


text:
Q: Sudden double space in ShareLatex I'm writing a book and sometimes I just have some double space between paragraphs. I don't know how to fix it.
My book code concerning the chapter format is:
\makeatletter
\renewcommand{\@chapapp}{}% Not necessary...
\newenvironment{chapquote}[2][2em]
  {\setlength{\@tempdima}{#1}%
   \def\chapquote@author{#2}%
   \parshape 1 \@tempdima \dimexpr\textwidth-2\@tempdima\relax%
   \itshape}
  {\par\normalfont\hfill--\ \chapquote@author\hspace*{\@tempdima}\par\bigskip}
\makeatother

Thanks for the help!


text:
Q: Virtual memory allocation in cluster - line command I`m running a code on a computer cluster with 24 nodes, 12 processors each one and something about 64Gb memory each node. The commands I'm using to launch it are the following
#!/bin/sh
#PBS -N cclit
#PBS -l walltime=288:00:00
#PBS -l nodes=1:ppn=1
#PBS -j oe
#PBS -m n
#PBS -l mem=60000mb

Unfortunately I realized that my code need at least a virtual memory which is 120000mb. What I tried to do has been to modify the above commands as
#!/bin/sh
#PBS -N cclit
#PBS -l walltime=288:00:00
#PBS -l nodes=2:ppn=2
#PBS -j oe
#PBS -m n
#PBS -l mem=120000mb

But it doesn't seem to work... It stops again at the same point telling me that virtual memory is not sufficient.
My code is not parallelized, meaning that only 1 processor is needed. What happens when the memory of a node is totally used?? I guess Im doing something wrong with '#PBS -l mem=120000mb', or probably I need some other command... I tried to look for a solution on the web but I didn t find anything..
Can you help me?
Thanks Mirko.


text:
Q: Djange reverse() to an admin URL not working in management command I have a project (myproj) with several applications in it. One application (myapp) has a management command I'm struggling with. I want this command to send out an email that contains URLs to model instances on the admin site. But I keep getting this error ImproperlyConfigured: The included urlconf XXX doesn't have any patterns in it (where XXX is some number).
Everything else seems to work. When I visit the '/admin/myapp' page all my models come up and I can perform every action in them. So it doesn't seem to be an error in general with my url patterns. I have a feeling that the management command isn't loading the url patterns and that's why it's failing, but I can't figure out how to get it to do that.
Some abbreviated code. All on python 2.7.6. Django 1.5.5
myproj/myproj/urls.py
from __future__ import absolute_import, unicode_literals
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^auth/', include('django.contrib.auth.urls')),
    url(r'^admin/', include(admin.site.urls)),

    # Other app includes, but none for myapp as it is strictly admin
)

myproj/myapp/urls.py
from __future__ import absolute_import, unicode_literals
from django.conf.urls import patterns, url

urlpatterns = patterns('',

)

myproj/myapp/management/commands/my_command.py
from __future__ import absolute_import, unicode_literals
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    def handle(self, *args, **options):
        from ... import do_stuff
        do_stuff()

myproj/myapp/__init__.py
from __future__ import absolute_import, unicode_literals
# Tried: also reverse_lazy, just delays the exception
from django.core.urlresolvers import reverse

def do_stuff():
    # Tried here: import myproj.urls

    # Work...
    # Exception here
    a_url = reverse('admin:myapp_mymodel_change', a_model.pk)
    # Work...

    # Send email here
    # Exception here if using reverse_lazy

A: Arg. I'm an idiot. Should be:
reverse('admin:myapp_mymodel_change', args=(a_model.pk,))


text:
Q: What is the difference between "number" and "Number" in TypeScript? In TypeScript, there are two distinct "number" types. The first one is called lowercase number, and the second is uppercase Number. If you try printing number, there is compiler error:
console.log(number); //-> error TS2693: 'number' only refers to a type

On the other hand, printing Number will give the standard function description:
console.log(Number); //-> [Function: Number]

This is unsurprising as Number is just a built-in JS constructor documented here. However, it is unclear, what number is supposed to be.
Judging by the error message, it seems that number isn't actually a discrete value(?!) like Number. But despite this, it is used in variable and function declarations as if it is a value, like:
var two: number = 2;
function sqr(x: number) { return x; }

On the other hand, user-defined types like classes appear to be discrete values (as they also print the standard function description). And, to further complicate matters, Number can be used in annotations similar to number:
var two: Number = 2;

There is similar cases with string and String, any and Object, etc.
So, my question is: What are number, string, etc in TypeScript, and how are they different then built-in constructors?

A: number is only a TypeScript thing - it's a primitive type referring to, well, a number.

But, judging by the error message, it seems that number isn't actually a discrete value like Number.

Indeed - it's a type, so it doesn't exist in emitted code.

a discrete value like Number. On the other hand, user-defined types like classes appear to be discrete values (as they also print the standard function description).

Yes. Classes, of which Number is one, are special. They do two things, somewhat unintuitively:

*

*They create a JavaScript class (usable in emitted code)

*They also create an interface for the class (only used by TypeScript)

If you use Number in a place where a type is expected, TypeScript will not complain, because Number is an interface.
If you use Number in a place where a value (something that exists in emitted code) is expected, TypeScript will not complain, because Number is also a global constructor.
In other words, the two Numbers below refer to completely different things:
// refer to the TypeScript Number interface
let foo: Number;

// refer to the JavaScript global.Number constructor
const someNum = Number(someString);

Using Number in TypeScript is very odd, since it'd, strictly, speaking, refer to a number created via new:
const theNum = new Number(6);

Which there's almost never a reason to do. Use a plain primitive number instead, without an object wrapper.
const theNum = 6;
// theNum is typed as `number`

A: From https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean:

JavaScript has three very commonly used
primitives:
string, number, and boolean. Each has a corresponding type in
TypeScript. As you might expect, these are the same names you'd see if
you used the JavaScript typeof operator on a value of those types:

*

*string represents string values like "Hello, world"

*number is for numbers like 42. JavaScript does not have a special runtime value for integers, so there's no equivalent to int
or float - everything is simply number

*boolean is for the two values true and false

The type names String, Number, and Boolean (starting with capital letters) are legal, but refer to some special built-in types
that will very rarely appear in your code. Always use string,
number, or boolean for types.

(There are also typs for null and undefined)


text:
Q: Ruby analog Java TimeUnit So in java we have TimeUnit enum with awesome methods.
Any analog in Ruby language?
I need converters seconds to milliseconds, milliseconds to days and so one

A: I'm not sure if this has 1 to 1 correspondence with TimeUnit but it can be pretty handy sometimes: https://github.com/kachick/time-unit


text:
Q: What do the type parameters to Source mean? I'm trying to understand the Source type for Akka streams, specified here.
Unfortunately, the documentation and examples I've found don't explain what each of the type parameters actually mean. I'm guessing that Out is the type that the source emits when materialized. Is that correct? What is the other type parameter Mat ?

A: Out
You are correct, this is the type of the elements which are emitted by the Source.
Mat
It is the type of the Source's materialisation. Note that every stage (Flows, Sinks, etc.) will materialise to a value as well.
This is essentially a byproduct of the stage itself after it is run.
You can picture it as a mean of interacting with the stage while it's running. Looking at examples of ready-made Sources offered by Akka is a good way of getting the gist of it.

*

*Source.single will materialise to NotUsed. You got no mean of interacting with the source, as it will produce only one element straightaway and then complete.

*Source.queue will materialise to a SourceQueue. This is a more interesting case, as you can interact with the source by offering messages to it. The messages you offer will be emitted by the source.

*Source.maybe will materialise to a Promise. You can use the Promise to control the source and make it emit one element, or None.
When you concatenate different stages, note that every stage can potentially have a useful materialized value. You get to choose which ones to keep by using viaMat/toMat and Keep DSL.
One or more materialized values will be returned when run() is called on the composed graph.
Taking a look at the types in the examples below is the best way to get the gist of the API:
  val source: Source[Int, MatSrc]
  val sink: Sink[Int, MatSnk]

  val matSrc: MatSrc = source.toMat(sink)(Keep.left).run()
  val matSnk: MatSnk = source.toMat(sink)(Keep.right).run()
  val (m1: MatSrc, m2: MatSnk) = source.toMat(sink)(Keep.both).run()
  val n: NotUsed = source.toMat(sink)(Keep.none).run()

Note that the more succinct DSL which you can find in many example is actually a shortcut for the above, where only the materialized value of the last stage (e.g. the sink) is kept.
  val mat3: Mat3 = source.viaMat(flow)(Keep.right).toMat(sink)(Keep.right).run()

is the same as
  val mat3: Mat3 = source.via(flow).runWith(sink)

See the docs below for further reading.
http://doc.akka.io/docs/akka/2.4/java/stream/stream-quickstart.html#Materialized_values


text:
Q: What do we call a song or music we perform during a funeral or for a dead person? What do we call a song or music we perform during a funeral or for a dead person? I was thinking for "funeral song", but there has to be some kind of more specific term for this. I don't mind if the answer doesn't cover all of the cases mentioned as long as it is meant to be performed during a funeral, or for a dead person.

A: The first word that springs to my mind is dirge. From Macmillan:

*dirge** (n.) a slow sad song often sung at a funeral

Collins says:

A dirge is a slow, sad song or piece of music. Dirges are sometimes performed at funerals.


text:
Q: Call multilookuplist by title and verify content in SharePoint Site I have this multilookuplist where user double click to movevalues to the right side. I need to make a method to check if the multilookuplist is empty.
I need to call it by the name as it is a sharepoint site.
The code looks like the following:

    <input id="ctl00_MultiLookupPicker"
    name="ctl04$ctl00$ctl00$MultiLookupPicker"
    type="hidden"></input>
    <input id="ctl04_ctl00_ctl00_MultiLookupPicker_data"
    name="$ctl00$MultiLookupPicker$data"
    type="hidden"
    value="272|tAS (blaba)|t |t |t235|tAP (blalbla)|t |t |t224|tAR (blalbla)|t |t "></input>
    <input id="ctl00_MultiLookupPicker_initial"
    name="ctl04$ctl00$ctl00$MultiLookupPicker$initial"
    type="hidden" value=""></input>

                <select name="ctl00$m$g_ctl00$SelectCandidate"
                id="ctl00_ctl00_SelectCandidate"
                multiple="multiple" title="Employees possible values"
                onchange="GipSelectCandidateItems(ctl00_ctl00_MultiLookupPicker_m);"
                ondblclick="GipAddSelectedItems(ctl00_ctl00_MultiLookupPicker_m); return false"
                style="width:143px;height:125px;overflow:scroll;">
            </select>

            <button
            id="ctl04_ctl00_ctl00_AddButton"
            class="ms-ButtonHeightWidth"
            onclick="GipAddSelectedItems(ctl00_ctl00_MultiLookupPicker_m); return false"> Add > </button>

<button id="cctl04_ctl00_ctl00_RemoveButton"
                class="ms-ButtonHeightWidth"
                onclick="GipRemoveSelectedItems(ctl04_ctl00_ctl00_MultiLookupPicker_m); return false"> < Remove </button>

                <select name="ctl04$ctl00$ctl00$SelectResult"
                id="ctl00_ctl04_ctl00_ctl00_SelectResult"
                multiple="multiple"
                title="Employees selected values"
                onchange="GipSelectResultItems(ctl00_MultiLookupPicker_m);"
                ondblclick="GipRemoveSelectedItems(_ctl00_ctl00_MultiLookupPicker_m); return false"
                style="width:143px;height:125px;overflow:scroll;">
            </select>

The following is the method that I try to make it validate that some lines are selected and moved from "Employees possible values" to "Employees selected values"

A: The code below for your reference.

If you want to do the validation when save item form, we need override the PreSaveAction() method.
References: SharePoint 2010 Validation using Javascript