text:
Q: Big O time complexity of a while loop with a random Object public class Question2 {
          //running time of function is N!!!!!!
    public static boolean isThere(int[] array, int num, int index){
        boolean isItThere = false;   //running time of 1
        for(int i =0; i <= index; i++){      //running time i
            if(array[i] == num){   //running time of 1
                isItThere = true;   //running time of 1
            }
        }
        return isItThere;
    }

    public static int[] firstAlgo(int N){
            Random random = new Random();  //running time of 1(initilizing)k
          int[] arr = new int[N];
          for (int i = 0; i < N; i++){
              int temp = random.nextInt(N+1);  //running time of random is O(1)
              while (isThere(arr, temp, i)){
                  temp = random.nextInt(N+1);
              }
              arr[i] = temp;
          }
         return arr;
    }

}

I want to figure out the time complexity of the while loop, I know the running time of the isThere function is N and So is the main for loop in firstAlgo

A: The short version:

*

*The expected runtime is Θ(N2 log N).

*I have the math to back this up, as well as empirical data.

Here's a plot comparing the empirical amount of work done to the best-fit approximation I got for a function of the form N2 log N, which was (N2 ln N) / 1.06:

Curious? Keep reading. :-)
Let's take a step back from the code here and see what the actual logic is doing. The code works as follows: for each prefix of the array 0, 1, 2, 3, ..., N, the code continuously generates random numbers between 0 and N until it generates one that hasn't been seen before. It then writes down that number in the current array slot and moves on to the next one.
A few observations that we'll need in this analysis. Imagine that we're about to enter the kth iteration of the loop in firstAlgo. What can we say about the elements of the first k slots of the array? Well, we know the following:

*

*The elements at positions 0, 1, 2, 3, ..., k-1 are all different from one another. The reason for this is that each loop iteration only stops once it's found something that doesn't otherwise appear in the array up to that point.

*None of those values are equal to 0, because the array is initially populated with 0s and if 0 is generated in a previous step it won't be allowed.

*As a consequence of (1) and (2), the elements in slots 0, 1, 2, ..., k-1, and k are all different.

Now, we can get down to some math. Let's look at iteration k of the loop in firstAlgo. Each time we generate a random number, we look at (k+1) array slots to make sure the number doesn't appear there. (I'm going to use this quantity, by the way, as a proxy for the total work done, since most of the energy will be spent scanning that array.) So then we need to ask - on expectation, how many numbers are we going to generate before we find a unique one?
Fact (3) from the above list is helpful here. It says that on iteration k, the first k+1 slots in the array are different from one another, and we need to generate a number different from all of those. There are N+1 options of random numbers we can pick, so there are (N+1) - (k+1) = N - k options for numbers we could pick that won't have been used. This means that the probability that we pick a number that hasn't yet come up is (N - k) / (N + 1).
A quick check to make sure this formula is right: when k = 0, we are okay generating any random number other than 0. There are N+1 choices, so the probability we do this is N / (N+1). That matches our formula from above. When k = N-1, then all previous array elements are different and there's only one number we can pick that will work. That means we have a success probability of 1 / (N+1), again matching our formula. Cool!
There's a useful fact from probability theory that if you keep flipping a biased coin that has probability p of coming up heads, the expected number of flips before you flip heads is 1 / p. (More formally, that's the mean of a geometric random variable with success probability p, and you can prove this using the formal definition of expected values and some Taylor series.) This means that on the kth iteration of that loop, the expected number of random numbers we'll need to generate before we get a unique one is (N + 1) / (N - k).
Overall, this means that the expected amount of work done on iteration k of the loop in firstAlgo is given by (N + 1)(k + 1) / (N - k). That's because

*

*there are, on expectation, (N + 1)/(N - k) numbers generated, and

*each generated number requires (k + 1) array slots to be checked.

We can then get our total amount of work done by summing this up from k = 0 to N - 1. That gives us
      0+1          1+1          2+1                 N
(N+1)----- + (N+1)----- + (N+1)----- + ... + (N+1)-----
      N-0          N-1          N-2                 1

Now, "all" we have to do is simplify this summation to see what we get back. :-)
Let's begin by factoring out the common (N + 1) term here, giving back
       /  1     2     3           N  \
 (N+1)|  --- + --- + --- + ... + --- |
       \  N    N-1   N-2          1  /

Ignoring that (N + 1) term, we're left with the task of simplifying the sum
 1     2     3           N
--- + --- + --- + ... + ---
 N    N-1   N-2          1

Now, how do we evaluate this sum? Here's a helpful fact. The sum
 1     1     1           1
--- + --- + --- + ... + ---
 N    N-1   N-2          1

gives back the Nth harmonic number (denoted HN) and is Θ(log N). More than just being Θ(log N), it's very, very close to ln N.
With that in mind, we can do this rewrite:
      1     2     3           N
     --- + --- + --- + ... + ---
      N    N-1   N-2          1

      1     1     1           1
=    --- + --- + --- + ... + ---
      N    N-1   N-2          1

            1     1           1
+          --- + --- + ... + ---
           N-1   N-2          1

                  1           1
+                --- + ... + ---
                 N-2          1

+                      ...

                              1
+                            ---
                              1

The basic idea here is to treat (k + 1) / N as (k + 1) copies of the fraction 1 / N, and then to regroup them into separate rows like this.
Once we've done this, notice that the top row is the Nth harmonic number Hn, and the item below that is the (N - 1)st harmonic number Hn-1, and the item below that is the (N - 2)nd harmonic number Hn - 2, etc. So this means that our fraction sum works out to

H1 + H2 + H3 + ... + HN
= Θ(log 1 + log 2 + log 3 + ... + log N)
= Θ(log N!)  (properties of logs)
= Θ(N log N)   (Stirling's approximation).

Multiplying this in by the original factor of N that we pulled out earlier, we get that the overall runtime is Θ(N2 log N).
So, does that hold up in practice? To find out, I ran the code over a range of inputs and counted the average number of iterations of the loop in isThere. I then divided each term by log N and did a polynomial-fit regression to see how closely the remainder matched Θ(N2). The regression found that the best polynomial plot had a polynomial term of N2.01, strongly supporting that (after multiplying back in the log N term) we're looking at N2 log N. (Note that running the same regression but without first dividing out the log N term shows a fit of N2.15, which clearly indicates something other than N2 is going on here.)
Using the the equation Predicted(N) = (N2 ln N) / 1.06, with that last constant determined empirically, we get the plot up above, which is almost a perfect match.

Now, a quick coda to this problem. In retrospect, I should have predicted that the runtime would be Θ(N2 log N) almost immediately. The reason why is that this problem is closely connected to the coupon collector's problem, a classic probability puzzle. In that puzzle, there are N different coupons to collect, and you keep collecting coupons at random. The question is then - on expectation, how many coupons do you need to collect before you'll have one copy of each of them?
That closely matches the problem we have here, where at each step we're picking from a bag of N+1 options and trying to eventually pick all of them. That would imply we need Θ(N log N) random draws across all iterations. However, the cost of each draw depends on which loop iteration we're in, with later draws costing more than earlier ones. Based on the assumption that most of the draws would be in the back half, I should have been able to guess that we'd do an average of Θ(N) work per draw, then multiplied that to get Θ(N2 log N). But instead, I just rederived things from scratch. Oops.
Phew, that was a trip! Hope this helps!

A: You can do it empirically.  Just run the code, and time it, with different values of N. I did so, and the complexity seems to be O(N^2).  I ran a bunch of tests, doubling N each time, and the times never seemed to back off from roughly quadrupling.  I got tired of waiting at N = 256000, which took about 200K millis.
If you wanted to go this way, you'd want to do a more careful analysis with more runs.  You could set up an outer loop to keep doing batches of tests, say 10 at each level, timing them, and then doubling N and doing it all again...recording all the times.  You could run the test overnight and get a pretty clear idea of the behavior empirically.
If this isn't the way you want to go about this, it could at least be a way to double-check your answer.

A: Remember that Big-O is worst case behavior. As mentioned in one of the comments, this has a chance to never terminate leading to Big-O of infinite because this code is non-deterministic.
For an average case where random does what's expected. You are looking at O(N) for the isThere function. For that last iteration to find a value, you will average N operations. At this point you are up to O(N^2). Finally you need to repeat this operation N times to fill the array, which brings you to O(N^3).


text:
Q: How to send new and old value when any field is changed? I have the form with a number of input fields, text areas, radio buttons, check boxes. Once value is changed in any field, I should send ajax to my server with field name, old and new values. How can I do it?
Upd. Here is the current approach:
oldValueHolder = null;
$('input[type="text"]').focus(function() {
  oldValueHolder = this.value;
});

$('input[type="text"]').focusout(function() {
  if (this.value != oldValueHolder) alert(this.name + ': ' + oldValueHolder + ' -> ' + this.value);
});

$('input[type="checkbox"]').click(function(event) {
  alert(this.name + ': ' + !$(event.target).is(":checked") + ' -> ' + $(event.target).is(":checked"));
});

But I am still not clear how to do the same with radio buttons.
Upd2. Here is the solution for radio buttons:
$('input[type="radio"]').change(function() {
  alert(this.name + ': ' + $(this).parents("div.control-group").attr('data-original-value') + ' -> ' + this.value);
  $(this).parents("div.control-group").attr('data-original-value', this.value);
});

A: As soon as your form is loaded, loop through all input elements and save their values in an array.
Then, when one of them is changed, look up the old value in the array and send it to the server. When done, update the "old" value with the new value.

A: You'll need to capture the old value before it's changed. One way to do that is:

*

*When a object gets focus, get its value in a temporary variable.

*If the object value is changed, send the new value and old value in ajax.

The advantage to this is you're not loading a whole array with all values, you've just got a rolling temporary variable that has the value of the last object that received focus. Less memory usage.
UPDATE:
Using jQuery to bind a function to the focus event on all inputs of class "myClass", E.g.:
HTML:
<input class="myClass" type="text" />

JS:
myUniversalOldValueHolder = null; // notice this is globally scoped.

$(".myClass").focus(function() {
    myUniversalOldValueHolder = this.value; // "this" is the <input> element, in this context
});

...and use $(".myClass").change() to define what to do when an element has been changed.
jQuery focus(): http://api.jquery.com/focus/
jQuery change(): http://api.jquery.com/change/

A: There are several ways to do this, but why not using a data-original-value attribute on all input fields that you want to know this?
<input type="text" id="txtName"
       data-original-value="Bruno Alexandre"
       value="Bruno Alexandre" />

Then upon submit you can send all original values as well with a simple line instead creating on DOM ready for a new array...

a Live Example based on previous answer: http://jsbin.com/atinel/10/edit
Live example uses this method to attach the current value of an input text and show it on the page
function saveCurrentValues() {

  $('input[type="text"]')                   // grab all input's that are text
      .each(function() {                    // loop through all of them
        var e = $(this).val();              // get the current value
        $(this)                             // apply everything to the current element
          .attr('data-original-value', e)   // set attribute to the value
          .closest('.row')                  // navigate to the closest element that has a class of 'row'
          .find('span')                     // from there find the 'span' element
          .text(e);                         // set the 'span' element text property to the value
      });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: Cannot read property 'guild' of undefined My bot has stopped working, here is my code. I want the bot to listen for @snoop across multiple discord servers and respond with snoop when it is gets hears the ping snoop. Its a basic listen and respond
const Discord = require('discord.js');
const client = new Discord.Client();
const start = new Date();
let snoop = 0;

client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); });

client.on('ready', msg => {
    if (msg.guild === null || !msg.guild.hasOwnProperty('members') || msg.guild.members === null) { return }

    const role = msg.mentions.roles.first();

    if (typeof role === "undefined") {
        return;
    }

    const member = msg.guild.members.get(client.user.id);
    const channel = msg.channel;

    // user is not role member of channel
    if (!member.roles.has("" + role.id)) {
        return;
    }

    if (msg.content.match(/(snoop)/i)) {
        console.log("snoop detected", role.name, channel.name, channel.id)

        const t = Math.floor(Math.random() * (3000 - 2500)) + 2500;
        console.debug(`sending snoop to ${channel.name} (${channel.id}) in ${t}ms`)
        channel.startTyping();

        setTimeout(() => {
            channel.send("snoop").then(() => {
                setTimeout(() => {
                    channel.stopTyping();
                }, 100);
            });
        }, t);

        boxes++
        const s = parseInt((new Date()).getTime() - start.getTime()) / (60 * 1000)
        console.info(``)
    }
    });
    client.login('apikeyhere')

This is the error I am getting:

typeError: Cannot read property 'id' of undefined
at ClientDataManager.newChannel (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/client/ClientDataManager.js:81:36)
at Guild.setup (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/structures/Guild.js:307:68)
at new Guild (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/structures/Guild.js:74:12)
at ClientDataManager.newGuild (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/client/ClientDataManager.js:26:19)
at ReadyHandler.handle (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/client/websocket/packets/handlers/Ready.js:20:91)
at WebSocketPacketManager.handle (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:108:65)
at WebSocketConnection.onPacket (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:336:35)
at WebSocketConnection.onMessage (/home/stuart/Downloads/discordbot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:299:17)
at WebSocket.onMessage (/home/stuart/Downloads/discordbot/node_modules/ws/lib/event-target.js:120:16)
at WebSocket.emit (events.js:198:13)

When i do node index.js this comes up

A: You are using twice "client.on('ready'".
One are you using to check if the bot started but the other one that you are using shouldn't be 'ready' but 'message'. Your codes are based on a message and not on when the bot started.


text:
Q: An invalid form control with name=' is not focusable in jQuery for Rating I am having one Modal to show form to take Review. Within that, I am using jQuery for ratings. There are 6 different fields in which I am taking ratings using Input type Number.
If I provide common value in all fields then only it is being submitted. If I provide different values in Rating then it prompts error in console:
An invalid form control with name='academic-rating' is not focusable.
An invalid form control with name='accomodation-rating' is not focusable.
An invalid form control with name='faculty-rating' is not focusable.
An invalid form control with name='infrastructure-rating' is not focusable.
An invalid form control with name='social-rating' is not focusable.

What can be issue here?
See this screenshot for better Explanation: Image


text:
Q: The compiler decided to call the function `POW`, instead of evaluating it at compile time. Why? I got the snippet below from this comment by @CaffeineAddict.
#include <iostream>
template<typename base_t, typename expo_t>
constexpr base_t POW(base_t base, expo_t expo)
{
    return (expo != 0) ? base * POW(base, expo - 1) : 1;
}

int main(int argc, char** argv)
{
    std::cout << POW((unsigned __int64)2, 63) << std::endl;
    return 0;
}

with the following disassembly obtained from VS2015:
int main(int argc, char** argv)
{
009418A0  push        ebp
009418A1  mov         ebp,esp
009418A3  sub         esp,0C0h
009418A9  push        ebx
009418AA  push        esi
009418AB  push        edi
009418AC  lea         edi,[ebp-0C0h]
009418B2  mov         ecx,30h
009418B7  mov         eax,0CCCCCCCCh
009418BC  rep stos    dword ptr es:[edi]
    std::cout << POW((unsigned __int64)2, 63) << std::endl;
009418BE  mov         esi,esp
009418C0  push        offset std::endl<char,std::char_traits<char> > (0941064h)
009418C5  push        3Fh
009418C7  push        0
009418C9  push        2
009418CB  call        POW<unsigned __int64,int> (09410FAh)     <<========
009418D0  add         esp,0Ch
009418D3  mov         edi,esp
009418D5  push        edx
009418D6  push        eax
009418D7  mov         ecx,dword ptr [_imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A (094A098h)]
009418DD  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (094A0ACh)]
009418E3  cmp         edi,esp
009418E5  call        __RTC_CheckEsp (0941127h)
009418EA  mov         ecx,eax
009418EC  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (094A0B0h)]
009418F2  cmp         esi,esp
009418F4  call        __RTC_CheckEsp (0941127h)
    return 0;
009418F9  xor         eax,eax
}

which shows (see the characters "<<======" introduced by me in the disassembly) that the compiler didn't evaluate the function POW at compile time. From his comment, @CaffeineAddict seemed to expect this behavior from the compiler. But I still can't understand why was this expected at all?

A: Two reasons.
First, a constexpr function isn't guaranteed to be called at compile time. To force the compiler to call it at compile time, you must store it in a constexpr variable first, i.e.
constexpr auto pow = POW((unsigned __int64)2, 63);
std::cout << pow << std::endl;

Secondly, you must build the project in Release configuration. In VS, you'll find you can break-point through constexpr functions if you have built the project using Debug configuration.


text:
Q: Multi Level Nested JSON Parsing with Apex Salesforce Can I parse Multi-Level nested JSON structure in APEX Salesforce, like we do in Java with GSON and Jackson libraries?
{
   "key1":"value1",
   "key2":{

          "key3":"value3",
          "key4":{
                 "key5":"value5"
           }

    }
}

I have already explored this.
Parsing JSON in Apex Salesforce
But I want a generic solution which will parse any JSON to the required Apex Object.

A: You can using the serialize/deserialize methods of the JSON class in Apex:
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_class_System_Json.htm
You'll need to construct an Apex class based on your input JSON, but there's even a handy tool to do it:
http://json2apex.herokuapp.com/
Unfortunately however, you're limited by the depth of the Apex classes.  I think after key4 in your example, you're back to parsing it manually.
One thing to consider is building a partial model in Apex, then hydrating any deeper nested objects you need using the parser.


text:
Q: Laravel 5.1. cannnot run artisan commands I am using Laravel 5.1 and I cannot run any artisan commands.
I uploaded my project to our live server with PHP5.5.22 CLI version.
everytime I run artisan commands I am getting this error
SQLSTATE[HY000] [2003] Can't connect to MySQL server on '127.0.0.1' (146)
I changed the configuration on my .env and config/database.php files to point to our MySQL server.
.env file
DB_CONNECTION=mysql
DB_HOST=****.sddb0040291787.*****
DB_PORT=3306
DB_DATABASE=sddb0040291787
DB_USERNAME=sddbMTcyNjEy
DB_PASSWORD=**********

config/database.php
'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '****.sddb0040291787.*****'),
        'database'  => env('DB_DATABASE', 'sddb0040291787'),
        'username'  => env('DB_USERNAME', 'sddbMTcyNjEy'),
        'password'  => env('DB_PASSWORD', '**********'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

even php artisan config:cache command doesn't work and returns same error.
Appreciate any help. Thanks guys!

A: This may give you some ideas, https://stackoverflow.com/a/37005818/8825233
Check if MySQL server is running.

A: Try adding --env=production to your artisan command
Please ensure that it is the right DB information which is stored in the env-file. By default it is localhost which is stored in the env.
Or you could simply delete the env() function from your config if you dont want to use enviroment variables. Like :
'mysql' => [
        'driver'    => 'mysql',
        'host'      => '****.sddb0040291787.*****',
        'database'  => 'sddb0040291787',
        'username'  => 'sddbMTcyNjEy',
        'password'  => '**********',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],


text:
Q: Trigger to create a new child record type Opportunity and Opportunity Line Items if the parent record type Opportunity is Closed Won Okay guys, I have now spent 4 days and counting on this trigger and I really feel it shouldn't be this hard but I am having a lot of trouble trying to get it done so help would be greatly appreciated!
This is my trigger so far:
trigger ParentOppToChild on Opportunity(after update)
{
    //Get all Opportunity's with stage name = to closed won
    Set<Id> opportunityIds = new Set<Id>();
    for(Opportunity opp : Trigger.new)
    {
        if(opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed Won')
        {
            opportunityIds.add(opp.Id);
        }
    }

    // Get Opportunity Line Items
    for (Opportunity opp : [SELECT Id, (SELECT Id FROM OpportunityLineItems) FROM Opportunity WHERE Id IN :opportunityIds])
    {
        // Create grouping of opp line items by Dealership
        Map<Id, List<OpportunityLineItem>> mapDealershipItems = new Map<Id, List<OpportunityLineItem>>();
        List<OpportunityLineItem> OppLineItemsList = new List<OpportunityLineItem>();
        for (OpportunityLineItem oppLineItem : opp.OpportunityLineItems)
        {
            mapDealershipItems.put(OppLineItem.Dealership__c, OppLineItemsList);
            If(mapDealershipItems.containsKey(oppLineItem.Dealership__c ))
            {
                // TO-DO Check if Dealership is a key in the map
                // 1. Yes - Add opp line item to the list
                // 2. No - Add dealership (key) and new list with item inside (value)
                //
                OppLineItemsList.add(OppLineItem);

            }
            else
            {
                OppLineItemsList.add(OppLineItem);
               ;
            }
        }
        //mapDealershipItems.put(key, value)

        // Create opportunity and opp line items
        for (Id dealershipId : mapDealershipItems.keySet())
        {
            // TO-DO Create opportunity
            Opportunity opportunity = new Opportunity(AccountId = dealershipId,
                                                        CloseDate = Date.today(),
                                                        StageName = 'Group Contract Signed');
            try {
                insert opportunity;
            } catch (Exception e1) {

            }

            // TO-DO Create opp line items
            //  - Check checkbox in opportunity
            List<OpportunityLineItem> oppLineItems = new List<OpportunityLineItem>();
            for(OpportunityLineItem oli : opportunity.OpportunityLineItems)
            {
                oppLineItems.add(oli);
            }

            try {
                insert oppLineItems;
            } catch (Exception e2) {

            }
        }
    }
}

I basically need to create a new opportunity (child record type) if the parent opportunity is 'closed won'. This new opportunity will have the account name set to the dealership__c(lookup field to account on OpportunityLineItem) and all the opportunity line items in its related list will be the ones related to the dealership (only the items that were associated with the dealer in the related list of the now 'closed won' parent opportunity).
I am having trouble grouping the Line Items with the Dealerships. And then trying to create the new opportunities and the line items related to it.
Again, I would be forever grateful to anyone who can help with this.

A: You will have to do some basic debugging as I did not try and compile the code.
Hopefully with the comments it makes sense and you can add to it
You will have to add a recursion check as you will be inserting new Opportunities.
Disclaimer: this is not a "best practice" code sample but a quick workup.
Recursion Check
public class checkRecursion{

    public static boolean stopOpportunity = false;

}

Trigger
trigger ParentOppToChild on Opportunity(after update)
{
    //Check recursion and do not run if this trigger is alredy running
    if(checkRecursion.stopOpportunity) return;

    //Get all Opportunity's with stage name = to closed won
    Set<Id> opportunityIds = new Set<Id>();
    for(Opportunity opp : Trigger.new)
    {
        if(opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName != 'Closed Won')
        {
            opportunityIds.add(opp.Id);
        }
    }

    Opportunity[] toProcess = [SELECT Id, (SELECT Id, Dealership__c FROM OpportunityLineItems Where Dealership__c != null) FROM Opportunity WHERE Id IN :opportunityIds];

    //Create a map of the Dealerships to ALL Opps with Line Items having a Dealership__c value
    Map<ID, Opportunity> mapOppDealership = New Map<ID,Opportunity>();

for(Opportunity opp : toProcess){
    for (OpportunityLineItem oppLineItem : opp.OpportunityLineItems){
        //dealership__c is the Key since we are aggregating by Dealership
        Opportunity tmp = mapOppDealership.get(oppLineItem.Dealership__c);

        if(tmp == null){ //No Opp created yet so create it by cloning the opp
            //Create a Opp for that dealership
            Opportunity new_opp = new Opportunity(
                                                    AccountId = oppLineItem.dealership__c,
                                                    CloseDate = Date.today(),
                                                    StageName = 'Group Contract Signed'
                                                );
            mapOppDealership.put(oppLineItem.Dealership__c,new_Opp);
        }
    }
}

    checkRecursion.stopOpportunity = true; //ensure this trigger does not run again due to WFR or RUS
    insert mapOppDealership.values();

    //List of Opp Line Items to insert
    List<OpportunityLineItem> mapDealershipItems = new List<OpportunityLineItem>();

    // Create Opportunity Line Items
    for (Opportunity opp : toProcess)
    {
        //For each Opportunity line item in the original trigger
        //Clone it and attach it to the Opportunity created eairlier using the Dealership__c as the Key
        //if no opp was created ignore the OLI

        for (OpportunityLineItem oppLineItem : opp.OpportunityLineItems)
        {
            if(mapOppDealership.containsKey(OppLineItem.Dealership__c)){
                OpportunityLineItem tmp = OppLineItem.clone(false,true); //Clone the line item
                tmp.OpportunityID = mapOppDealership.get(OppLineItem.Dealership__c); //reparent

                mapDealershipItems.add(tmp); //add to list
            }
        }
    }

    insert mapDealershipItems;

}

This trigger will go through the Opp Line Items and create an opportunity for each dealership (Across ALL Opportunity Line Items in the trigger)
Then it will go through them again and create new line items, attaching them to the Opportunities created above.
Basically it aggregates all records in the trigger by dealership.

A: below code is to create the Map of DealershipID with OpportunityLineItems. Thanks.
// Code to create the map of Dealership__c ( Account) and OpportunityLineitems.

Map<Id, List<OpportunityLineItem>> mapDealershipItems = new Map<Id, List<OpportunityLineItem>>();
for (OpportunityLineItem oppLineItem : opp.OpportunityLineItems){
             if ( ! mapDealershipItems.Containskey(oppLineItem.Dealership__c))
                     mapDealershipItems.put(oppLineItem.Dealership__c,new list <OpportunityLineItem>)
                mapDealershipItems.get(oppLineItem.Dealership__c).add(oppLineItem);

        }

  system.debug('Map of Dealership with OpportunityLineitems ' + mapDealershipItems) ;     // it will map of Dealership Id with the OpportunitylineItems


text:
Q: PL/SQL INSERT INTO & Partitions I would like to start with saying that I am still learning PL/SQL. I was wondering if you could share your opinion on the following topic/questions.  Basically, I want to insert data from Table X into Table Y via a package. I have already read about the inserting part, so this is clear, however I was wondering what will happen with existing partitions. Lets say that Table Y has partitions. What will happen when we insert new data from Table X? Will it be divided into the partitions or not? Or what if i have interval partitions, will they grow based on the incomming data from Table X? Do I need to "trigger"/ call the partitions inside the package?
Thank you in advance for your help! I am just looking for tips and advises so that I can figure out how to setup my tables and the package (in case i need to call the partitions there). Like for example should I have interval partitions or not.
Thank you for your time!

A: If the data you're inserting fits the definition of the existing partitions then the new data will be added to the existing partitions. If the new data does not fit the definition of any existing partition, then either

*

*a new partition will be created for the new data, if the table is set up to do so, or

*the insert will fail and you will have to manually create a new partition capable of holding the new data.
Which of the above situations will happen in your case depends entirely on how your table was created, on what partitions already exist, on what the partitioning method and key is/are, and on the data you're trying to insert.
You don't have to "do" anything in your code to tell it which partition to use. A partitioned table behaves no differently than a non-partitioned table.
Best of luck.


text:
Q: MIPS program: check if number is prime .data
    userInput: .asciiz "give an integer to check if prime: "
    prime: .asciiz "Prime"
    notPrime: .asciiz "No prime"
.text
    main:
        li $v0, 4
        la $a0, userInput
        syscall

    li $v0, 5
    syscall
    move $t0, $v0

    addi $t1, $t1, 1
    addi $t2, $t2, 2
    ble $t0, $t1, no
    beq $t0, $t2, yes
    div $t0, $t2
    mflo $s0
    mfhi $s1
    bgt $s1, $zero, yes
yes:
    li $v0, 4
    la $a0, prime
    syscall
    j exit
no:
    li $v0, 4
    la $a0, notPrime
    syscall
    j exit
exit:
    li $v0, 10
    syscall

For some reason, the program always jumps to the "yes" even when there's a remainder (mfhi) and I can't seem to find the problem on why it does it. When I give input 4 it should jump to the "no" label since the remainder is 0 so it isn't greater than the constant 0.

A: What are you trying to accomplish with this part of your code:
    bgt $s1, $zero, yes
yes:

Play the computer and decide where to go if the gt is true vs. if the gt is false.


text:
Q: Using exported variables from required module with use strict I had previously had use Foo; to use a module I had written, and was using methods and variables from it which were exported using Exporter.pm.
I replaced the use with require to allow some flexibility on when the module was imported.  I now get dozens of errors all saying that the symbols "require explicit package name."
I know I could add the explicit method name for each, but there are quite a few.
Is there a way to alias these once so that afterwards I can use the symbol without explicit packages each time?

A: " I'm loading a module from a location specified in a config file, so it has to be done at run time"
Okay, but it doesn't have to be done at run time so you're asking the wrong question
Do this
use strict;
use warnings 'all';

use constant CONFIG_FILE => '/path/to/config_file';

my $libs;

BEGIN {
    open my $fh, '<', CONFIG_FILE or die $!;
    chomp($libs = <$fh>);
}

use lib $libs;

use MyLib;    #  MyLib.pm is in the directory specified in config_file

A: You need to import the symbols before they are encountered in the code by the compiler.
You can load the the symbols sooner.
use Foo;

sub moo { ... $SymbolImportedFromFoo ... }

You can compile the mention later.
eval(<<'__EOI__') or die $@;

    use Foo;

    sub moo { ... $SymbolImportedFromFoo ... }

    1;

__EOI__


text:
Q: when i click canceled butten then user can login why? public function approved($id)
{
    $users = User::find($id);
    $users->status = 'approved';
    $users->save();
    return redirect()->back()->with('status','status is approved');
}
public function canceled($id)
{
    $users = User::find($id);
    $users->status='canceled';
    $users->save();
    return redirect()->back()->with('status','status is canceled');
}

Route::get('/approved/{id}', [App\Http\Controllers\HomeController::class, 'approved']);
Route::get('/canceled/{id}', [App\Http\Controllers\HomeController::class, 'canceled']);


text:
Q: prove if $E_{1},E_{2},...,E_{n}$ are independent events then $p(\cup_{i=1}^{n}E_{i})=1-\prod_{i=1}^{n}[1-p(E_{i})]$ prove if $E_{1},E_{2},...,E_{n}$ are independent events then:
$p(\cup_{i=1}^{n}E_{i})=1-\prod_{i=1}^{n}[1-p(E_{i})]$
my try:
$$
p(\cup_{i=1}^{n}E_{i})=1-p((\cup_{i=1}^{n}E_{i})^{c})=1-p(\cap_{i=1}^{n}E_{i}^{c})
=1-\prod_{i=1}^{n}p(E_{i}^{c})=1-\prod_{i=1}^{n}[1-p(E_{i})]
$$
$E_{1},E_{2},...,E_{n}$ are independent,
so i guess $E_{1}^c,E_{2}^c,...,E_{n}^c$ are also independent
(I need to prove it but got little confused with all the Inclusion-Exclusion principle)
Would appreciate any help :)


text:
Q: SAP_UI component 7.52 minimum SAPUI5 version since I cant find anything on the internet regarding this question, I thought to try it here.
When I update my sap_ui component from 7.51 sp05 to 7.52 sp00, do I have to update all my apps to sapui5 version 1.52 aswell? (currently they're on 1.44)
And additionally, if my gateway(gw_fnd) is still on 7.51 could it cause problems when i update the sap_ui component to a newer release?

A: Please have a look at the published SAPUI5 version history here:
https://sapui5.hana.ondemand.com/versionoverview.html
We recommend you to upgrade SAPUI5 from 1.44 to 1.52 via the Front-end-server upgrade. (see SAP Note 2484979), in which case you need Fiori Front-end-server 4.0 SP01.
The standard apps with SAPUI5 1.44 delivered by SAP should be compatible with the new SAPUI5 1.52 – in the exceptional case it is necessary to upgrade the Fiori app with the newest SP patch.
If you experience compatibility issue with the 1.52, please raise an incident ticket.

A: I would suggest to restrict all your current apps to the version in which they were developed and upgrade slowly after going through appropriate testing cycle when you have time and budget. This will not stop the upgrade as well as your application will keep on working and you do not have to spend testing efforts right away.


text:
Q: Lightsail Bitnami reboot resets the machine_hostname setting I have a running AWS Lightsail instance, with bitname and Wordpress running on it.
I have assigned it a static IP address.
After setting it up I have opened the console and configured the machine_hostname like this:
sudo ./bnconfig --machine_hostname <domain>
After this, the domain now works, and everything operates as expected..... Until the instance reboots. At that time the domain is lost, and I have to perform this again.
Not sure how to prevent this from happening on a reboot?

A: Bitnami Engineer here,
If you run the bnconfig tool to configure the domain name in the application, you need to rename the tool so it's not run again when the instance is started/rebooted.
sudo ./bnconfig --machine_hostname <domain>
sudo mv ./bnconfig ./bnconfig.disabled

https://docs.bitnami.com/aws/faq/configuration/configure-custom-domain/
You can also update the WordPress' configuration with your domain (/opt/bitnami/apps/wordpress/htdocs/wp-config.php)
define('WP_SITEURL', 'http://DOMAIN/');
define('WP_HOME', 'http://DOMAIN/');

You can learn more about that here
https://docs.bitnami.com/aws/apps/wordpress/administration/configure-domain/

A: This worked for me:
sudo hostnamectl set-hostname <domain>


text:
Q: Updating only the changed values in an object when long polling entire list of objects in knockout I'm constantly long polling a list of servers:
var servers = ko.observableArray();
$.getJSON('/Home/GetServers', function (data) {
    servers.removeAll();
    $.each(data, function (xxx) {
        servers.push(new Server(xxx);
    });
});
function Server(xxx) {
   var self = this;
   ko.mapping.fromJS(xxx, {}, self);
}

and I have a list of objects as an observableArray and I only want to change the values of the objects that have changed, rather than removing all and re-pushing every element.


text:
Q: How do I ignore a line when using the pdb? For some quick Python debugging I'll occasionally throw in a import pdb;pdb.set_trace() line that will drop me into the debugger.  Very handy.  However, if I want to debug a loop, that may run many, many, many times, it loses its effectiveness somewhat.  I could mash on continue  many, many, many times, but is there a way to remove/ignore that hard-coded breakpoint so I can let it finish?
I could set a global flag and run it conditionally, but then I'd lose the 'standalone-ness' of the one-line breakpoint, also requiring another flag for each pdb.set_trace().

A: My other answer is sort of a quick hack, and is not perfect (will disable all calls to set_trace).  Here's a better solution.
We define a module wrapping pdb. In it, set_trace is a callable object, maintaining a list of disabled callers (identified by filename/line-number).
# mypdb.py
import inspect
import sys
try:
    import ipdb as PDB
except ImportError:
    import pdb as PDB

class SetTraceWrapper(object):
    def __init__(self):
        self.callers_disabled = set()
        self.cur_caller = None
    def __call__(self):
        self.cur_caller = self.get_caller_id()
        if self.cur_caller in self.callers_disabled:
            # already disabled for caller
            #print 'set_trace SKIPPED for %s' % ( self.cur_caller, )
            return
        #print 'set_trace BREAKING for %s' % ( self.cur_caller, )
        try:
            PDB.set_trace(sys._getframe().f_back)
        except TypeError:
            PDB.set_trace()
    def disable_current(self):
        #print 'set_trace DISABLING %s' % ( self.cur_caller, )
        self.callers_disabled.add(self.cur_caller)
    def get_caller_id(self, levels_up = 1):
        f = inspect.stack()[levels_up + 1]
        return ( f[1], f[2] )  # filename and line number

set_trace = SetTraceWrapper()

In your code, make sure you use the wrapper:
import mypdb as pdb; pdb.set_trace()

When you want to disable the current set_trace-calling-line, do:
pdb.set_trace.disable_current()

Notes:

*

*I personally prefer ipdb over pdb

*When using pdb, since the function actually calling pdb.set_trace is in the wrapper, the current frame when breaking will be in it.  the up command gets you the to frame you want.  This will not happen if using ipdb (the implementation in the wrapper makes sure to break in the right place).

*When using ipdb, I find it to report caller-frame line-numbers inconsistently.  This means the first time you do pdb.set_trace.disable_current(), it might not hold.  Just do it again if it breaks the next time -- the second time holds.

*In general, having your own pdb wrapper is useful for other things as well.  I have my own set_trace wrapper which avoids breaking if not sys.stdout.isatty (you never want to break if the process is not connected to a terminal, nor when you redirect the stdout to a file/pipe).  That is to say, having your own pdb wrapper and calling its set_trace instead of pdb's is a good practice.

A: The following hack will disable all other calls to set_trace in current run (i.e., from anywhere in your code).
Create this noop_pdb drop-in:
# noop_pdb.py
def set_trace(*args, **kwargs):
    pass

Then, once your code breaks in the real pdb.set_trace, and you want to disable the rest of the calls to set_trace, do:
sys.modules['pdb'] = __import__('noop_pdb')

Next time the interpreter encounters a line like:
import pdb;pdb.set_trace()

It avoids re-importing the built-in pdb, picking up the drop-in.
EDIT: another way to implement this hack, which does not require noop_pdb, is by replacing set_trace with noop, instead of the whole pdb module: pdb.set_trace = lambda: None

A: Did you look at condition bpnumber ? You could disable the breakpoint and then make it conditional. Alternatively you could just use break or tbreak to make the breakpoint conditional in the first place. Details can be found here.

A: Have you tried using the "until" command that's provided by pdb?
From http://docs.python.org/2/library/pdb.html#debugger-commands:

unt(il)
Continue execution until the line with the line number greater
  than the current one is reached or when returning from current frame.

A: Using 'return' in pdb can pass pdb.set_trace() in the loop and jump to the last line of the current function.


text:
Q: How to run Java programs by clicking on their icon on Windows? I have written a Java program that uses Java swing library. Now I would like to execute this program by double clicking on the executable file on Windows just like any other program with a GUI. How do I do that?

A: Since it is Java based and has a GUI, the obvious answer is to deploy it using Java Web Start.

Java Web Start (JWS) is the Oracle Corporation technology used to launch rich client (Swing, AWT, SWT) desktop applications directly from a network or internet link. It offers 'one click' installation for platforms that support Java.
JWS provides many appealing features including, but not limited to, splash screens, desktop integration, file associations, automatic update (including lazy downloads and programmatic control of updates), partitioning of natives & other resource downloads by platform, architecture or Java version, configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.), easy management of common resources using extensions..

By 'desktop integration' read desktop shortcuts and menu items on supported platforms.

The 2 icons on the right (JotPad & Star Zoom Animation) are both Java based apps., installed using Java Web Start.  Since JotPad is sand-boxed, the user will be prompted as to whether to create the shortcut.  That choice is not offered for apps. with higher permission levels, so it would make more sense to install/remove the shortcuts and menu items using the IntegrationService - which allows an app. (after prompting the user) to create/remove them at run-time.

A: There are number of options:

*

*Create an executable jar of your project. for this jar to work you have to have javaw as default application to open it.

*Create an exe of your project.

*Create a bat file which runs your jar file.

Take a look at this: How can I convert my Java program to an .exe file?

A: While the others mention excellent choices like creating a native executable, there is another useful method: creating a shortcut.

*

*Right click your desktop, expand the "New" option, and click on "Shortcut".

*Type "javaw.exe". Click next.

*Name it whatever you want. Click done.

*You'll notice the newly created shortcut on your desktop. Right click it and choose "Properties"

*In the "Target" textfield, append "-jar path-to-your-jar.jar" where you replace "path-to-your-jar.jar" with the actual path to your jar

*You can also now optionally change the icon to whatever icon you want

This shortcut can be pinned to the taskbar and be used from anywhere (considering you provided an absolute path to your JAR).

A: you need to create exe from the java program.
Creating executable jar files

*

*First, make sure you have installed Java 1.2 or above. This facility is not available in previous versions of Java.

*Next, create your working java system. In general, you will want to put it into a package. For this example, I created a trivial HelloWorld application that prints out "Hello World" plus the first command line argument, and placed it into the package "psae". Therefore, the HelloWorld files (HelloWorld.class, HelloWorld.java) were located in the directory psae. I tested the system to make sure it worked before going on to the next step.

*In the directory in which the psae is located, created a file called "mainClass". This file contains a single line specifying where the main Class is to be found in the jar file. Note that I use the package specification. Here is the single line:
Main-Class: psae.HelloWorld
Note: make sure you type a carriage return after this line; some windows systems need it and will report a "Failed to load Main-Class manifest attribute" error.

*Next, I create a jar file called psae.jar using the "jar" command in Java2. I use the "m" command line argument to specify the manifest file mainClass, which adds information to the jar file on where the main class will be found. Here is the jar command:
bertha:~ > jar cmf mainClass psae.jar psae

*Just for fun, and to check what's happened, I print the table of contents for the jar file I just created. Here's the command and its result:
bertha:~ > jar tf psae.jar
META-INF/
META-INF/MANIFEST.MF
psae/
psae/HelloWorld.java
psae/HelloWorld.class

*Having successfully created the jar file, I can now invoke java2 on it with the command line argument:
bertha:~ > java -jar psae.jar Philip
Hello World Philip

A: There are a few projects, like http://jsmooth.sourceforge.net/ and http://launch4j.sourceforge.net/

A: you can use something like Launch4j.
also look at JSMooth.
Hope it helps

A: There are two ways. Both involve packaging your code in a .jar.
The first way is to build an actual .exe file using a tool like Launch4j. It will require you to set up things like tell it which class to execute, which icon to use, which JRE is OK, what JRE parameters to use, etc.
The second option is to make the .jar itself executable. You do this by adding a manifest to the .jar. The manifest is a small configuration file that describes the jar. One of the attributes is Main-Class which defines the entry point. In other words, it says which class has the main function that should be called when the user double-clicks the file.
Here's a basic tutorial about manifests: http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
The 2nd option is easier to get going, but users will know what to do with a .exe far more often.
Note that if either approach complains that it can't find the class, make sure to set the classpath manifest attribute to match your project.

A: If you have an executable jar file, just shift-right click on your file and set it to be opened by javaw. The other option (in case you want to pass in parameters to your application) is to create a .bat file where you spin off your application via java or javaw

A: Right click to your "project" in eclipse and select "export" then choose "Java->Runnable Jar File" select your project name and finish.

A: Seems you want to deploy and run the standalone application of swings. Being a java developer you should understand the power of jar files. Those are executable in themselves {so no need to create .exe files :)} .
The below code will help you to create a jar file.
Creating a jar File in Command Prompt
Start Command Prompt.
Navigate to the folder that holds your class files:
C:\>cd \mywork
Set path to include JDK's bin.  For example:
C:\mywork> path c:\Program Files\Java\jdk1.5.0_09\bin;%path%
Compile your class(es):
C:\mywork> javac *.java
Create a manifest file:
C:\mywork> echo Main-Class: NameOfProject >manifest.txt
Create a jar file:
C:\mywork> jar cvfm NameOfProject.jar manifest.txt *.class
Test your jar:
C:\mywork> DanceStudio.jar

After creating a jar just double click on it and you are done.

A: You have to create an executable jar file. For that you just simply add a META-INF folder to the jar, then add a MANIFEST.MF text file with two lines:
Manifest-Version: 1.0
Main-Class: your.package.YourMainClass

A: Here's how to run a Java program by RIGHT-CLICKING on it (in other words, from the Windows Explorer context menu). This handy trick is great for beginners who need to test their simple programs on the fly. Works on both Win7 and XP rigs.
[ATTN: Depending on the situation, you may need to remove the package directive from the top of your Java file.]
Step 1. Create a batch file (e.g., RWJ.bat) inside a folder of your choice (say, in C:\Program Files\Java.)
Step 2. Fill RWJ.bat with the following commands (they will work just fine as is with simple classes but you can, of course, tweak them according to your particular needs by specifying compiler / interpreter switches, passing args, adding echo off, removing pause or whatever):
javac %1
java %~n1
pause

The first command passes the full name of your right-clicked file to the Java compiler; the second one strips the file extension and feeds JVM with the class name only.
Step 3. Add the following key to your Registry: HKEY_CLASSES_ROOT\*\shell\Run With Java and then create its command (default value):
C:\Program Files\Java\RWJ.bat %1.

Step 4. Run your Java class by right-clicking it and selecting Run with Java option.

That's all there is to it.
Another way to run Java programs by pointing and clicking is to use AOT compilers. For example, GCC has an entry point named GCJ, which can be used to compile the source code into both byte codes and standard executable file for your particular OS.
And finally, instead ot batch files one can run WSH, etc.


text:
Q: How ovoid duplicate code in sql query subQuery I'm new in SQL. Need some help to improve my query to ovoid duplicate code.
SELECT customers.name, orders.price
FROM customers
JOIN orders ON orders.id = customers.order_id
WHERE customers.order_id IN (
SELECT orders.id
FROM orders

WHERE orders.price = (
    SELECT orders.price
    FROM orders
    WHERE orders.order_date BETWEEN
        (SELECT MIN(orders.order_date) FROM orders)
        AND
        (SELECT DATE_ADD(MIN(orders.order_date), INTERVAL 10 year)FROM orders)
    ORDER BY orders.price DESC LIMIT 1
    )
    AND orders.order_date BETWEEN
    (SELECT MIN(orders.order_date) FROM orders)
    AND
    (SELECT DATE_ADD(MIN(orders.order_date), INTERVAL 10 year)FROM orders)
)

I would like ovoid duplicate code here
SELECT MIN(orders.order_date) FROM orders

and
SELECT DATE_ADD(MIN(orders.order_date), INTERVAL 10 year)FROM orders

A: You can use WITH to get first 10 years orders. By defitinion there exists no orders with the date < min(date), so you needn't between, just <= .
firstOrders as (
  SELECT *
  FROM orders
  WHERE order_date <=
        (SELECT DATE_ADD(MIN(o.order_date), INTERVAL 10 year)
         FROM orders o)
)
SELECT customers.name, orders.price
FROM customers
JOIN FirsrOrders orders ON orders.id = customers.order_id
AND orders.price = (
   select price
   from firstOrders
   order py price desc
   limit 1
)

A: You want orders from the first ten years where the price was equal to the maximum price among those orders. So rank by price and grab those holding the #1 spot.
with data as (
    select *,
        date_add(min(order_date) over (), interval 10 year) as max_date,
        rank() over (order by price desc) as price_rank
    from orders
)
select *
from data
where order_date <= max_date and price_rank = 1;


text:
Q: UISearchBar remove background on iOS 4.1 I'm trying to remove the background of UISearchBar to make it transparent. I tried these solutions:
1.
for (UIView *subview in searchBar.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
    [subview removeFromSuperview];
    break;
}
}

2.
[[searchBar.subviews objectAtIndex:0] removeFromSuperview];

These two methods both work on iOS 4.3, but not on 4.1. it shows black. How can I make it work on iOS 4.1? I'm using SDK 4.3. Thanks.

A: This should work:
[[searchBar.subviews objectAtIndex:0] removeFromSuperview];
[searchBar setBackgroundColor:[UIColor clearColor]];


text:
Q: Invalid object name dbo.TableName I am getting the following error here: http://mvcbense.azurewebsites.net/

Invalid object name 'dbo.BlogPosts'.

This is an MVC3 application using Entity Framework Code First. I have looked elsewhere and have only found something about changing the schema which I assume is what dbo. is.
I am fairly new to EF, but it would look as if EF creates these for me, so I am unsure of what to do. Looking in my local SQL Server Express, all the tables have the dbo. schema on them. Why would I be able to run them locally but not published to Azure?
Thanks

A: The problem is that you haven't configured SQL Azure correctly to migrate your SQL Express based schema first. When you create an ASP.NET Windows Azure Website which is based on local SQL Server, you would have to manually migrate the on-premise DB configured to SQL Azure first and then publish your ASP.NET application to Windows Azure Website. IF you will not do it, your ASP.NET website will not work.
Based on the exception the initial DB tables are missing so what is needed for you is to select any of the suitable database migration method from the list below to migrate your DB first and then run your Windows Azure Website:
Migrating Databases to Windows Azure SQL Database (formerly SQL Azure)

A: A much simpler solution suggested by Stan over here works:
http://social.msdn.microsoft.com/Forums/windowsazure/en-US/9c20a99c-80c9-4b1d-afa4-26b9b418f435/connect-to-sql-azure-via-sql-server-management-studio-failed
Excerpt:

*

*cancel out of the first connection dialog that pops up.

*click on the New Query button from the toolbar (upper left)

*entered
     Server name: full servername
     Login: just the username (no @...)

*Under Options, Connect to Database, I typed TestDb1

*Hit connect.

A: I also experienced the same issue but while using Database first approach. Connection string in my service's/service's host web.config was incorrect. I changed the connection string and it worked.


text:
Q: Passing half of a text file to one node of a linked list and the second part to another using C I have created a linked list of just two nodes in the following way for testing purposes:
void implement (int size)
{
    for (int i = 0; i < size; i++)
    {
        node* new = malloc(sizeof(node));

        if (new == NULL)
        {
            printf("Out of memory!\n");
            return;
        }

        new->i = i;
        new->link = head;
        head = new;
    }
}

where size is 2 for now and the node is of the following type:
typedef struct node
{
    int i;
    char array[100];
    struct node* link;
}node;

node* head = NULL;

My aim is from the following text file:
A, B

to pass A, to one node and then B to the other, using the following code:
char* data;
data = malloc(sizeof(char) * 100);

fgets(data, 30, inptr);

node* cur = head;
int n = 0;

for (int i = 0, j = 6; i < j; i++)
{

   cur->array[n] = data[i];
   n++;
   printf("%s", cur->array);

   if(data[i] == ',')
   {

        cur = cur->link;

   }

}

for (node* ptr = head; ptr != NULL; ptr = ptr->link)
{
    printf("%s\n", ptr->array);
}

However, my output is the following for the first printf statement:
AA,
and then for the second printf statement iterating through the linked list, nothing. I have been through the program using gdb and it seems to work fine, so I cannot see quite what the problem is here. Any advice/tips would be much appreciated. Thanks in advance

A: You are missing n=0 after cur = cur->link;


text:
Q: Notepad++ merging different lines with duplicate words I have some tough work to do let me explain as best as i can. Merge the duplicate words on different lines.
Example:
i like 33 big black cars122
cars122 notfree
The result i want:
i like 33 big black cars122 cars122 notfree
there is like 200k lines and some don't even have duplicate words, i want only duplicates to merge. I've been thinking about it for a week now and my brain is not powerful enough to come with solution

A: If you literally want to replace cars122 repeated then here you go:

If you want to do something more complicated with all repeated words you would need to use the Regular Expression option and I would have to see the file to test before I would be comfortable suggesting a solution.
This would be much tougher on the non-repeating words. Regardless of your approach (and there are many) You basically need some angle that you can make rules that cover all your cases.


text:
Q: Есть ли какие-либо ограничения при построении http запросов в yandex-tank-е? При тесте танком, вижу одни ошибки 71 Protocol error, curl на подобных запросах получает 200 Ok.
Есть ли какие-либо ограничения при построении http запросов в yandex-tank-е?
конфиг танка:
tester@tank:~/test$ cat load.ini
[phantom]
rps_schedule=line(1,10,10)
address = ...
[monitoring]
config=none
tester@tank:~/test$

Кусок консольного вывода танка:
NET for 5 RPS:
5 100.00%: 71 Protocol error

В логе phout-а все http коды ответов нулевые, есть только 71е ошибки (формат лога нашел в этой доке):
tester@tank:~/test$ cat logs/757372/phout_efwfw9.log | awk '{print $11, $12}' | uniq -c
55 71 0
tester@tank:~/test$

в логе фантома есть записи 413 Entity too big
tester@tank:~/test$ head logs/757372/phantom_COS85f.log
2015-12-04 17:28:42.279 +0300 [info] [] Start
2015-12-04 17:28:42.281 +0300 [error] [benchmark_io 055] format error
2015-12-04 17:28:42.529 +0300 [error] [benchmark_io 001] 413 Entity too big
2015-12-04 17:28:42.529 +0300 [error] [benchmark_io 001] Entity too big
2015-12-04 17:28:43.273 +0300 [error] [benchmark_io 007] 413 Entity too big
2015-12-04 17:28:43.273 +0300 [error] [benchmark_io 007] Entity too big
2015-12-04 17:28:43.794 +0300 [error] [benchmark_io 008] 413 Entity too big
2015-12-04 17:28:43.794 +0300 [error] [benchmark_io 008] Entity too big
2015-12-04 17:28:44.223 +0300 [error] [benchmark_io 006] 413 Entity too big
2015-12-04 17:28:44.223 +0300 [error] [benchmark_io 006] Entity too big
tester@tank:~/test$

Запрос curl-ом возвращает 200:
tester@tank:~/test$ curl -v  http://...  > /dev/null
...
> GET ... HTTP/1.1
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: ...
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx
< Date: Fri, 04 Dec 2015 15:38:59 GMT
< Content-Type: image/jpeg
< Content-Length: 16141533
< Connection: keep-alive
< Keep-Alive: timeout=60
< Last-Modified: Sat, 28 Nov 2015 13:14:21 GMT
<
{ [data not shown]
100 15.3M  100 15.3M    0     0  23.7M      0 --:--:-- --:--:-- --:--:-- 23.8M
* Connection #0 to host ... left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):
} [data not shown]
r2d2@t34:~/test$

A: Судя по выводу curl-а, размер запрашиваемого ресурса больше дефолтных 8 Мбайт.
Попробуйте выставить в конфиге танка в секции [phantom] большее значение, например
phantom_http_entity = 30M

Также стоит обратить внимание на следующий кусок документации:

phantom_http_line - First line length. Default - 1K
phantom_http_field_num - Headers amount. Default - 128
phantom_http_field - Header size. Default - 8K
phantom_http_entity - Answer size. Default - 8M.
  Please, keep in mind, especially if your service has large answers, that phantom doesn't read more than defined in phantom_http_entity.


text:
Q: If input value is blank, assign a value of "null" when form is submitted I'm fairly new to the form validation process. How do I return a value of null if input value is an empty string, when a form is submitted?
As you can see from the example below I have three options for verifying a user's identity. Based on the radio button selected, a user can then proceed to enter the relevant details. Upon submission of the form, I want the empty fields (the other 2 options not selected) to return a value of "null" or "empty" rather than ",,,". Can you please assist in resolving this issue.
See code example below:

            <TABLE width="100%" cellpadding="5" style="background-color:<%=colourblock%>; color:#FFFFFF; font-size:16px; display:block; margin-bottom:10px;">
Step 10 - Provide identification

Please confirm your identity using one of the below Government issued identification.

<input type="radio" name="IdentityType" id="IdentityType" value="**Australian driver's licence number**">
                Australian driver's licence number:
  <input name="IdentityValue" type="text"  id="IdentityValue"  value="" />

<input type="radio" name="IdentityType" id="IdentityType" value="**Australian passport number**">Australian passport number:
                   <input name="IdentityValue" type="text"  id="IdentityValue"  value="" />

<input type="radio" name="IdentityType" id="IdentityType" value="**Immicard number**">Immicard number:
                <input name="IdentityValue" type="text"  id="IdentityValue"  value="" />

If you don't hold any of these identification, you will need to attach certified copies of relevant proof of identity documents as outlined on the proof of identity guide on plum.com.au

A: when processing the code, it'll always post as an empty string (when using classic asp vbscript). if you the value to be null, just assign it to null like so:
dim IdentityValue : IdentityValue = Request.Form("IdentityValue")
if IdentityValue = "" then IdentityValue = null

now IdentityValue will be null


text:
Q: How to use regex in sed? I need to revoke the sudo access to the user using sed in scripts.
I want to comment the user only if the line contains /bin/su - root
Let us consider the file as below, in which I have to comment only the first line.
mindadmin  ALL = NOPASSWD: /bin/su - root
mindadmin  ALL = NOPASSWD: /bin/ifconfig

I have used sed commands as below:
sed -e 's/minadmin[\s]+ALL[\s]+=[\s]+NOPASSWD:[\s]+/bin/su - root/#mindadmin  ALL = NOPASSWD: /bin/su - root/g' /etc/sudoers

But it is not working. Is there any syntax error in it?

A: There are two problems, the first is that your sudoers has mindadmin and your pattern minadmin (without the d).
The second problem is in the /s of /bin/su, you have to escape these within the regex:
sed -e 's/mindadmin[\s]+ALL[\s]+=[\s]+NOPASSWD:[\s]+\/bin\/su - root/#mindadmin  ALL = NOPASSWD: \/bin\/su - root/g' /etc/sudoers

otherwise they end the pattern.
You can also shoose another delimiter instead of /, as long as that doesn't occur in the file, you don't have to escape it.

A: If you want to comment out all lines which contain /bin/su - root at the end of the line, then you can simplify your sed expression:
sed 's/.*\/bin\/su - root$/#&/'

Or, even simpler
sed 's,.*/bin/su - root$,#&,'

To comment out all lines which contain /bin/su - root anywhere in the line:
sed 's,.*/bin/su - root,#&,'

A:  sed  '/\/bin\/su - root/ s/^/#/'  filename

It locates the lines, in the filename, containing /bin/su - root, and add the comment(#) at the beginning of the line (^).
Add -i option in sed to effecting to file.

A: As & is replaced with the whole matching pattern, here another solution:
sed -i 's,.*/bin/su\s\+-\s+root,#&,' /etc/sudoers

/ is replaced by a different separator so you do not need to escape it. The pattern is also more flexible if the spacing after the su command is different.
If it should only change the mindadmin user:
sed -i 's,^mindadmin\s.*/bin/su\s+-\+root,#&,' /etc/sudoers

The flag -i applies directly the change to the file.


text:
Q: How does Java represent an image using a byte[] array? I'm just curious how java manipulate images and image processing. In matlab, image is saved as a 3D array of RGB values. But in Java we use byte[] arrays to store an image. But that array is a 1D array.
I'm wondering how this array can represent RGB values and position of voxels?

A: It's not only java. Low level screen memory use byte[] (linux frame buffer for example)
Depending on bpp (bits per pixels) size.
For 32 bpp you have 4 bytes for r,g,b,a values.
A color value goes from 0 to 255.
Each image line following the precedent in a one byte array.
Then width x 3 give you the 3rd row first pixel position.
Total size is width x height x bpp / 8
32bpp is the simplest to understand.
24bpp is 3 bytes for r,g,b
16bpp is 2 bytes for r,g,b then g is between to bytes...
depending on the encoding it can be r,g,b,a or b,g,r,a or a,r,g,b...


text:
Q: Is there an OCR API for Google glass? I just had an amazing idea for an app, but it requires transcribing written text to computer recognised text.
I know that with Google Translate for Android you can take a picture and select text and it make that into computer words, is that available for free use?

A: No, there is no such API for Google Glass.  Perhaps Google will release something in the future, but as of now no such thing.
You can of course use any web api to send a picture to a web server where processing is done and results sent back to Glass.  Likewise native android code runs on Glass, so any existing android libs should work with Glass.


text:
Q: how to show another image until the gif is fully loaded? in the first block of the site I have a large gif image that takes a very long time to load.

<picture>
            <source srcset="https://media.githubusercontent.com/media/javascripteaser88/fintech-
            remake/main/media/vapor.gif" type="image/gif" media="(min-width:501px)">
            <source srcset="https://media.githubusercontent.com/media/javascripteaser88/fintech-remake/main/media/mobile.gif" type="image/gif" media="(max-width:501px)">
            <img src="https://media.githubusercontent.com/media/javascripteaser88/fintech-remake/main/media/vapor.gif"alt="outrun gif" class="outrun">
</picture>

it looks very bad when the user has to wait a few tens of seconds before seeing the content (and someone's gif won't even load completely).
So I need to show some kind of lightweight image until my gif animation is fully loaded, or just show the first frame of this animation, but i don't know how to do it. Or you can advise some other ways to reduce the waiting time that I did not expect.
P.S. here is a link to the site hosted on github pages https://javascripteaser88.github.io/fintech-remake/


text:
Q: How to ensure jacoco's -javaagent comes before other javaagents on the command line (e.g. spring + aspectj)...? How can you ensure the -javaagent JVM arg implicitly added by jacoco comes BEFORE all other -javaagent JVM arguments on the command line?
We are using spring + aspectj and require the following JVM args to be present for our tests:
 -javaagent:/path-to/aspectjweaver-1.9.2.jar -javaagent:/path-to/spring-instrument-5.1.5.RELEASE.jar

Our tests run fine, but when we try to use jacoco, we get warnings like this during jacocoTestReport for some classes:
05:49:27  > Task :core-service:jacocoTestReport
05:49:27  [ant:jacocoReport] Classes in bundle 'core-service' do no match with execution data. For report generation the same class files must be used as at runtime.
05:49:27  [ant:jacocoReport] Execution data for class com/acme/FooService does not match.
05:49:27  [ant:jacocoReport] Execution data for class com/acme/BarService does not match.

After researching this, it seems like the jacoco recommendation is to make sure that the -javaagent argument for the jacoco agent is the FIRST javaagent on the command line.
See this answer, key excerpt:

"If you use another Java agent make sure the JaCoCo agent is specified at FIRST in the command line. This way the JaCoCo agent should see the original class files."

NOTE: the jacoco task will implicitly add its own -javaagent JVM arg, but it always ends up later on the command line in my case.
This is also complicted somewhat by the fact that the jacoco -javaagent argument is not static (it has a myriad of options concatenated after the jar reference, that are a function of the specific use case).
Here is an example java invocation for our tests, as generated by gradle (abbreviated & reformatted for readability):
/usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/bin/java \
   -Dorg.gradle.native=false \
   -javaagent:/path/to/spring-instrument-5.1.5.RELEASE.jar \
   -javaagent:/path/to/aspectjweaver-1.9.2.jar \
   -javaagent:build/tmp/expandedArchives/org.jacoco.agent-0.8.5.jar_6a2df60c47de373ea127d14406367999/jacocoagent.jar=destfile=build/jacoco/test.exec,append=true,excludes=**/xyz/**:**/com/someother/**:**/*.zip,inclnolocationclasses=false,dumponexit=true,output=file,jmx=false \
   @/tmp/gradle-worker-classpath12976595675824598txt \
   -Xmx512m \
   -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant -ea \
    worker.org.gradle.process.internal.worker.GradleWorkerMain

We are inserting our other JVM -javaagent arguments like this:
test {
   jacoco {
      enabled = true
   }

   // NOTE: have also tried moving this to other points in the lifecycle (still always end up before jacoco's)
   doFirst {
      configurations.javaAgent.files.each {
         jvmArgs "-javaagent:${it}"
      }
   }
}

Tool versions:

*

*Java 11

*Gradle 6.7.1


text:
Q: jQuery on click with namespace function How come this is illegal in jQuery?
$('#someElm').on('click', customNamespace.namespaceFunction);

jQuery throws this error: Uncaught TypeError: undefined is not a function
Note: The functions do not matter... but for illustration purposes:
function customNamespace(){};

customNamespace.namespaceFunction = function(){ alert('do something'); };

The example above works... but how come when we bind to the document it does not
http://jsfiddle.net/2acrL/

A: This is how you would want to do it:
$(function() {
    function customNamespace() {};
    customNamespace.namespaceFunction = function() { alert('do something'); };
    $('#someElm').on('click', customNamespace.namespaceFunction);
});

Did you forget to include jQuery? See Updated JS FIDDLE DEMO
EDIT
Edited to initialize customNamespace as a function.
EDIT TWO
The following code and demo shows the code working with event delegation and the same scoping as above:
$(function() {
    function customNamespace(){};

    customNamespace.namespaceFunction = function(){ alert('do something'); };

    $(document).on('click.blah', '[test-attr]' , customNamespace.namespaceFunction);
});

NEW JS FIDDLE DEMO

A: Turns out I was an idiot...
namespaceFunction was spelled incorrectly (namespaceFunciton) in my code.
I wish jQuery would tell you 'namespaceFunciton' is not a function of 'customNamespace' instead of just saying "Uncaught TypeError: undefined is not a function"


text:
Q: problems with bufferedRead and while loop I have some problems with Android Java programming.
This is my situation:

*

*I am trying to load text lines from a text file.

*I will make every line as a separate string variable which will be
saved in an ArrayList.

*I have no problems with running the application, but it fails when I
press the button that will send a variable to method where the
application will use to make every line as separate questions.

*The whole screen freezes after pressing the button on my phone.

I do not know how to fix this.
I am newbie in programming but I try my best, so any help is appreciated. Please ask if you did not understand or want more information, peace.
Here is the code:
public void levelOne(View v)throws IOException{
    Intent intent = new Intent(this, pageBeforeAction.class);
    Button buttond = (Button) findViewById(R.id.buttonOne);
    createQuestions("hogskoleprovet.txt");
    startActivity(intent);
}

public void levelTwo(View v) throws IOException{
    Intent intent = new Intent(this, pageBeforeAction.class);
    Button buttonC = (Button) findViewById(R.id.buttonTwo);
    createQuestions("hogskoleprovet.txt");
    startActivity(intent);
}

public void createQuestions(String hogskoleprovet) throws IOException{
    InputStream iS = getResources().getAssets().open(hogskoleprovet);
    BufferedReader reader = new BufferedReader(new InputStreamReader(iS));

    while(reader != null){
        String question = reader.readLine();
        String answer = reader.readLine();
        String answerOne = reader.readLine();
        String answerTwo = reader.readLine();
        String answerThree = reader.readLine();
        String answerFour = reader.readLine();
        Question q = new Question (question, answer, answerOne, answerTwo, answerThree, answerFour);
        mQuestions.add(q);
        break;
    }
    reader.close();
}

This is the output of my logcat:
 26837-26837/com.example.arnpet.ultimatehogskoleprovet E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.arnpet.ultimatehogskoleprovet, PID: 26837
java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:3969)
        at android.view.View.performClick(View.java:4637)
        at android.view.View$PerformClick.run(View.java:19422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5479)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at android.view.View$1.onClick(View.java:3964) at android.view.View.performClick(View.java:4637)

Here is the xml-file (activity):

android:weightSum="1"
android:background="@drawable/weather">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Var vänlig att tryck på den knappen för att välja vilket högskoleprov som du önskar spela. Tryck sedan Starta högskoleprovet, eller återvänd till menyn"
    android:id="@+id/textView3"
    android:layout_gravity="right"
    android:layout_weight="1"
    android:textColor="#ff171c45"
    android:textSize="@dimen/abc_text_size_headline_material" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_weight="2"
    android:id="@+id/line">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Nivå 1"
        android:id="@+id/buttonOne"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/buttonbg_knas"
        android:onClick="levelOne" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Nivå 2"
        android:id="@+id/buttonTwo"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/buttonbg_knas"
        android:onClick="levelTwo" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="STARTA HÖGSKOLEPROVET"
        android:id="@id/buttonThree"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/blue_button"
        android:onClick="startGame" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ÅTERVÄND TILL MENYN"
        android:id="@+id/buttonFour"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/redbutton_knas"
        android:onClick="returnMenu" />
</LinearLayout>


text:
Q: Conditional Vlookup 3 search terms one table Is there a way  I  can do  a Vlookup  with 3 different search terms  on one  table ?
Per example, I  want to  lookup by SamAcctName or UserLogonName or TestName  on  one  big pool of data
Search terms

SamAcctName    |      UserLogonName     |   TestName  |      result      |
---------------|------------------------|-------------|------------------|
test.user      | testuser@test.com      | testus      | Result 1 <<<<<<  |
---------------|------------------------|-------------|------------------|
estuser        |   other@test.com       | testuseer   | Result 2 <<<<<<  |
---------------|------------------------|-------------|------------------|

Table with all data records

Name          |        Description      |     moredata       |
--------------|-------------------------|--------------------|
Test.User     |  Result 1 <<<<<<<       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|
other@test.com|  user ..Blah Blah       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|
other.user    |  user ..Blah Blah       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|
TestUser2     |  user ..Blah Blah       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|
other.user    |  user ..Blah Blah       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|
other@test.com|  Result 2 <<<<<<<       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|
other.user    |  user ..Blah Blah       |    Blah  Blah BLah |
--------------|-------------------------|--------------------|

A: A simple sledgehammer approach would be to write nested IFERROR(VLOOKUP... like below formula.
=IFERROR(VLOOKUP(A2,F:G,2,0),IFERROR(VLOOKUP(B2,F:G,2,0),IFERROR(VLOOKUP(C2,F:G,2,0),"")))
where columns F&G house all data table and the first table is in A2:D3 range.

A: =INDEX(D1:D3,MATCH(1,MMULT(--(A1:C3=E1),TRANSPOSE(COLUMN(A1:C3)^0)),0))
This is an array function to be entered with ctrl + shift + enter
An array is created from A1:C3=E1 as 1 or 2 (TRUE or FALSE). The array is 3 columns and the length of your range.
A second array is created with TRANSPOSE(COLUMN(A1:C3)^0) resulting in {1, 2, 3} and that to the power 0 is {1, 1, 1}.
MMULT multiplies these arrays and the result is the row number of your matching value.
INDEX shows the result value in your index column of that row.
Edit:  I just realised I used E1 as the lookup value, but in your situation change this to the cell applicable to you. Also the ranges of data are an assumption and may need to be modified.
To reflect your data as posted below:
Search terms are from H2 to I500 and data pool is from A2 to F1465 where my assumption is that the result data to be displayed is to come from column B:
=INDEX(B2:B1465,MATCH(1,MMULT(--(H2:I500=A1),TRANSPOSE(COLUMN(H2:I500)^0)),0))


text:
Q: findout when all setimeouts finish Checkout this demo/game i am building http://awebdeveloper.github.io/runners/
I wish to know when will all the players finish running. The Game class needs to know when all the player stop and who came first.
My question is is there a way to inform back the calling class when each of the animate finish  after all the settimeout
Player Class
function Players(ele, ptimeout)
{
    this.movePositions  = [0, 40, 80, 120],
    this.moveBy         = 5
    this.el = ele;
    this.i = 0;
    this.stop = 1;
    this.timeout = ptimeout;
    this.position = 0;

    this.animate = function(){
        /* Stop if stopped */
        playerPosition = this.el.getBoundingClientRect();
        if(this.stop || playerPosition.left > (racetrack.offsetWidth - 30)){
            this.el.style.backgroundPosition = '120px 0px';
            return ;
        }

        playerPosition = this.el.getBoundingClientRect();
        if(this.stop || playerPosition.left > (racetrack.offsetWidth - 30)){
            this.el.style.backgroundPosition = '120px 0px';
            return ;
        }

    /* Prepare Next Move */
        setTimeout(function(_this){
            if(_this.i < _this.movePositions.length ){
                _this.i ++;
            }
            else{
                _this.i = 0;
            }
            _this.move();
            _this.animate();
        },this.timeout,this);
    };

    this.play = function(){
        if(this.stop === 1){
            this.stop = 0;
            this.animate();
        }
    };

    this.move = function(to,positionIndex){
        this.position = to;
        this.el.style.backgroundPosition = '-'+this.movePositions[positionIndex]+'px 0px';
        this.el.style[getSupportedPropertyName('transform')] = 'translate('+to+'px)';
    }
}

Game Class
function Game(noOfPlayers){

    var track_tmpl      = '

';
    this.noOfPlayers = noOfPlayers;

    this.players = new Array();

    for (var i = 0; i < this.noOfPlayers ; i++){
        var timeout = 120 + getRandomInt(1, (this.noOfPlayers*2));
        racetrack.appendChild(createNode(track_tmpl.replace('{{ x }}', i)));
        this.players.push(new Players(document.getElementById('player' + i), timeout));
    }

    this.play = function(){
        for (var i = 0; i < this.noOfPlayers; i++){
            this.players[i].play();
        }
    };
}

A: on Player.play pass the this argument, to call from Person a function from Game.
So you will have a code like this
this.play = function(){
    for (var i = 0; i < this.noOfPlayers; i++){
        this.players[i].play(this);
    }
};

then on Player modify the code like this
this.play = function(game){
    if(this.stop === 1){
        this.stop = 0;
        this.animate(game);
    }
};

after on method animate call the game.playerFinished(Player)
on Game class write a method
var i = 0;
this.playerFinished = function(player) {
    console.log(player.name + " finished on position " + (i++));
}

where player.name a name you give on players class


text:
Q: How do I add borders between rows in css as in the picture below (red line- I need, gey line is now) enter image description here
How do I add borders in css as in the picture below (red line- I need, gey line is now)

A: first of all create an unordered list and apply display flex and you can insert content in html. And you might need to add display:flex;in the list items if you have more than one element inside.
.menu_ul{
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
}
.menu_list_items{
    padding: 30px;
    border: 2px solid rgb(128, 128, 128);
    border-right: none;
}
.menu_list_items:last-child{
    border-right: 2px solid rgb(128, 128, 128);
}

for the html,

Txt1

Txt2

Txt3

Txt4

That will be the basic structure you want.


text:
Q: In Ada generic packages In Ada Generic packages if I have a package that deals with any element you put in, if I would want to demonstrate that the package is working, would I have to run two separate client programs to show Integer and then Float, or could I do all that in the same program?

A: The generic parameters should include a generic procedure parameter for printing the generic data type passed to the package. This will allow the data type to be anything and the writer of the generic package need not be concerned with how it is output.
generic
   type element_type is private;
   with procedure Print(Item : element_type);
package gen_pack is
   ...
end gen_pack;

A: IIUC, the "inner" package is the one that, too, depends on the generic formal type of the outer package, at least as far as testing goes. Then there are two cases.

*

*If the inner package is a plain package, such as Integer_Text_IO, it can only handle singed integer types, and that's a compile time thing.

*The inner package is of a kind that can be got from instantiating, using the generic formal type of the outer generic package.
In the first case, there is nothing the compiler can do but reject, since Integer_Text_IO is not made for floating point operands. So you'd have to set up separate test cases.
In the second case, the outcome depends on the "inner instance". Since the compiler cannot create a generic package when given a type, it can only instantiate a generic package that exists. The latter one must have matching formal requirements. That is, the generic formal types of the outer generic and of the to-be-instantiated inner generic must match: they must not be from a mutually exclusive category, like range <> and digits <>.
Sometimes, it is worth considering that one can specify requirements for the "inner generic" by making it a formal parameter of the outer generic:
generic
    type X (<>) is limited private;
package Taking_Any is
    -- ... operations for both FPT and integer types
end Taking_Any;

generic
    type T is private;
    with package Works_With_Any is new Taking_Any (<>);
package Outer is
    package Any_Instance is new Taking_Any (T);
end Outer;


text:
Q: How to add three Shortcut keys ( Ctrl + Shift + C) in Java Swing Menubar? I want to add shortcut keys in Java Swing Menubar. Below is what I have tried.
jMenuItem1.setText("Create");
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK));

Here I want three KeyEvent.VK_C, KeyEvent.CTRL_MASK, and KeyEvent.SHIFT_MASK.

A: jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK+ALT_MASK)

A: jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));

A: KeyStroke.getKeyStroke(KeyEvent.VK_C, 21);
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/KeyStroke.html#getKeyStroke(int, int)
Read about the modifiers and you'll know what the 21 (or 2 and the 1) is for...

A: From the Java Menu Tutorial:

To specify an accelerator you must use a KeyStroke object, which combines a key (specified by a KeyEvent constant) and a modifier-key mask (specified by an ActionEvent constant).

The referenced "modifier-key mask" is created from multiple ActionEvents via bitwise operations, so the bitwise OR specifying multiple events in the setAccelerator() method does the same thing.
On Windows Only:
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
                         java.awt.Event.CTRL_MASK | java.awt.Event.SHIFT_MASK));

Cross-platform:
To enable this cross-platform (i.e. to use the Command button on a Mac instead of Control), simply replace the java.awt.Event.CTRL_MASK with:
@SuppressWarnings("deprecation")
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); // Java 9 or older

or
Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); // Java 10 or newer

for a final setAccelerator that looks like
jMenuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
                         Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() |
                         java.awt.Event.SHIFT_MASK));

On a Mac you'll also notice that the Accelerator text in the menu itself shows the CMD symbol, too, while on Windows it'll still show CTRL (e.g. CMD+S vs. CTRL+S).


text:
Q: Angular TypeError: Cannot read property 'users' of null I have a component that receives data via @Input() decorator about the group. My goal is to create a new array of objects during component initialization based on data from group array. Here is my TS component part:
import { Component, OnInit, Input } from '@angular/core';

import {Group} from "@models/group.model";

@Component({
  selector: 'app-group-admins',
  templateUrl: './group-admins.component.html',
  styleUrls: ['./group-admins.component.css']
})
export class GroupAdminsComponent implements OnInit {
  @Input() group: any = new Group();
  users: Array<object> = [];
  constructor() { }

  ngOnInit() {
    this.users = this.group.users.map((a: { user: number; permissions: number; }) => ({id: a.user, permissions: a.permissions}));
  }

  getUsers() {
    this.users = this.group.users.map((a: { user: number; permissions: number; }) => ({id: a.user, permissions: a.permissions}));
  }
}

And here is my Group and GroupUser models (if needed):
import {GroupUser} from "@models/group-user.model";

export class Group {
  group_name: string;
  type: string;
  avatar?: string;
  header?: string;
  address?: string;
  date?: string;
  city?: string;
  about?: string;
  verify_status?: string;
  site?: string;
  phone?: string;
  email?: string;
  web_site?: string;
  industry?: true;
  directions_list?: string;
  users: Array<GroupUser>
}

export class GroupUser {
  id?: number;
  user: number;
  permissions: string;
  confirmed?: boolean;
}

Here is my parent TS component part:
group = [];
ngOnInit() {
this.route.paramMap.subscribe(() => {
  this.id = this.route.snapshot.paramMap.get("id");
  this.groupService.getSpecGroup(this.id).subscribe(
    ((info) => {
      this.group = info;
    })
  );
});
}

And HTML part:
 <app-group-admins [group]="group"></app-group-admins>

So basically I'm trying to create users array via ngOnInit, but it throws an error TypeError: Cannot read property 'users' of null although everything works fine if I use getUsers() function. Any help woul be appreciated.

A: why not use a setter in he input? -if you needn't group you needn't store in a auxiliar variable
  @Input() set group(value:Group){
    this.users=value && value.users?value.users..map((a: { user: number; permissions: number; }) =>
          ({id: a.user, permissions: a.permissions}));
        :[];
  }
  users: Array<object> = [];
  constructor() { }

A: @Input() group: any = new Group();
that line doesn't look right to me. you use @Input if you are passing something from a parent component to a child component, and shouldn't be re-initialized.
try this:
@Input('group') group: Group;
ngOnInit() {
  console.log(this.group);
}


text:
Q: Use \overarc to represent an arc I  can not understand why the following tex file does not compile.
\documentclass{elsarticle}
\usepackage[hmargin=1in,vmargin=1in]{geometry}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage{arcs}

\usepackage{tikz}

\begin{document}
$\overarc{POQ}$ $+ \widehat{QOR} + \widehat{ROP}= 2\pi r$
\end{document}

A: Discussed for other oversymbols here Really wide hat symbol.  Using scalerel, a variant of that solution is used here:
\documentclass{article}
\usepackage{scalerel}

\newcommand\reallywidehat[1]{%
\begin{array}{c}
\stretchto{
  \scaleto{
    \scalerel*[\widthof{#1}]{\bigwedge}
    {\rule[-\textheight/2]{1ex}{\textheight}} %WIDTH-LIMITED BIG WEDGE
  }{1.25\textheight} % THIS STRETCHES THE WEDGE A LITTLE EXTRA WIDE
}{0.5ex}\\           % THIS SQUEEZES THE WEDGE TO 0.5ex HEIGHT
#1\\                   % THIS STACKS THE WEDGE ATOP THE ARGUMENT
\rule{0ex}{.01ex}
\end{array}
}

\newcommand\reallywideparen[1]{%
\begin{array}{c}
\stretchto{
  \scaleto{
    \scalerel*[\widthof{#1}]{\frown}
    {\rule[-\textheight/2]{1ex}{\textheight}} %WIDTH-LIMITED BIG WEDGE
  }{1.25\textheight} % THIS STRETCHES THE WEDGE A LITTLE EXTRA WIDE
}{0.5ex}\\           % THIS SQUEEZES THE WEDGE TO 0.5ex HEIGHT
#1\\                   % THIS STACKS THE WEDGE ATOP THE ARGUMENT
\rule{0ex}{.01ex}
\end{array}
}

\begin{document}
$\reallywideparen{POQ}$ $+ \reallywidehat{QOR} + \reallywidehat{ROP}= 2\pi r$
\end{document}


text:
Q: Resource ID #0x0 React Native I'm trying to set an icon in Android with react-native. My code looks like this:
<ToolbarAndroid
  actions={[]}
  navIcon={require('image!test')}
  onIconClicked={navigationOperations.pop}
  style={styles.toolbar}
  titleColor="white"
  title={route.event.title} />

I've got a non-corrupt test.png file under app/src/main/res/mipmap-hdpi/test.png (after adding the image I've run react-native run-android) and I'm getting a Resource ID #0x0 :

However, if I change the image name to something bogus, the error

"Requiring unknown module "image!testttt". If you are sure the module is there, try restarting the packager"

I don't know what's going on, I've seen an exact example of this in react-native Movies example, that actually works in my computer.

A: I found what was happening. When I created my project react-native created mipmap directories: mipmap-hdpi, mipmap-mdpi, etc.
These directories in Android are for icons only. I deleted these directories and created drawable ones and put my icon application inside drawable. I adjusted my AndroidManifest to point to @drawable/icon. After this a rebuild the android application and relaunch the packager. It started working right after that with react-native 0.11.0


text:
Q: Approving edits without the required 5000 rep
Possible Duplicate:
How do suggested edits work?

It seems that I was able to vote/approve a suggested edit without having the required 5000 rep. Is this a feature I wasn't aware of?
I came across this post and in the middle of refreshing and commenting on it, I noticed the edit link under the post change to:
edit(1)

Or something of that sort, I don't remember the details exactly. Then being the curious person that I am, I of course clicked on it and up came this dialog asking me to approve/reject/etc. I couldn't resist approving it just to see if it would work, and low and behold, I got credit for approving it.

I unfortunately don't have screenshots of the edit link changing or the approve/reject dialog. Are users below 5000 rep allowed to approve/reject edits?

A: You only need 2,000 rep to make/approve edits to regular posts, 5,000 is for tag wiki edits.


text:
Q: Gold Edition or Golden Edition? Gold Edition or Golden Edition? Which is correct?If both are correct then what's the difference?Is there any changes in the adjective here? Plz explain in a grammatical way.Thanx all.

A: Technically, when 'gold' is used as an adjective, it should mean that the item it is describing is made of gold, or at least made of an alloy that contains gold, eg On his retirement he received a gold watch. 'Golden', which is always used as an adjective, can mean exactly the same thing as 'gold', but it can also mean 'something with the same colour or sheen as gold', eg 'the golden light falling on the lake'.
In reality, 'gold' is frequently used in a figurative sense to describe something that has no gold content, e.g. 'She had green eyes, with gold flecks that lit up when she was angry'. The word 'gold' is also frequently used to indicate that something is of a higher quality, or more desirable for some reason, than another similar item, e.g. credit cards from the same provider are often distinguished as being silver or gold cards. Similarly, video games, DVDs, Blue Ray Discs, etc, are often sold as Gold Editions (or sometimes Platinum Editions), if they contain extra content that is not available in the standard editions.
Whether special editions are called 'Gold Editions', or 'Golden Editions' (or even 'Platinum Editions'), is totally of no consequence. The name is just marketing hype to attract the notice of potential buyers, and inform them that this edition contains something extra (and possibly costs a few dollars more).

A: Gold Edition is essentially regular edition with some behind the scenes stuff like a normal edition e.g. Get Gold Edition which includes the game, Season Pass and the Deluxe Pack.
Whereas Golden Edition might refer to the yellowish or brownish-yellow metallic color of gold e.g. The Golden Edition of the watch has been released for limited time period.