Q: Money format output and also in the textbox i have here a sample computation, what i want to know is how can it be a money format output.
for example 1000+ 1000 =2000
i want to output it as 2,000.
also , when typing the value , i want it automatically look a money format.
<html>

<head>
</head>

<body>

<form name="haha" method="post" >

1:<input type="text" name="num1">

2:<input type="text" name="num2">

Total:<input type="label" name="total">
<input type="submit" value="add" name="submit">

</html>
</form>
<?

if (isset($_POST['submit']))
{

$num1=$_POST['num1'];
$num2=$_POST['num2'];
$total=$_POST['total'];

$total= $num1 + $num2;

echo $total;
}
?>

A: I'm assuming you're looking for number_format or its more advanced brother money_format. This will take care of the server-side for you.
As for the client-side, I would advise against making things change while the user's typing. Just let them type in the number how they want. Bonus points if you allow them to type in thousand separators (since you can just strip them out easily in PHP to get the number itself).

A: Try number_format
$english_format_number = number_format(floatval($total));
echo $english_format_number;

A: You need to use javascript for that, when user change the input value you need to call the function to format the value.
You have to something like this:
$("[name^='num']").change(function(){
     var value = $(this).val();
      $(this).val(money_format(format, value));
});

Here is the function for monet format :
Ref: https://github.com/kvz/phpjs/blob/master/functions/strings/money_format.js
function money_format (format, number) {
  // http://kevin.vanzonneveld.net
  // + original by: Brett Zamir (http://brett-zamir.me)
  // + input by: daniel airton wermann (http://wermann.com.br)
  // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  // - depends on: setlocale
  // % note 1: This depends on setlocale having the appropriate locale (these examples use 'en_US')
  // * example 1: money_format('%i', 1234.56);
  // * returns 1: 'USD 1,234.56'
  // * example 2: money_format('%14#8.2n', 1234.5678);
  // * returns 2: ' $ 1,234.57'
  // * example 3: money_format('%14#8.2n', -1234.5678);
  // * returns 3: '-$ 1,234.57'
  // * example 4: money_format('%(14#8.2n', 1234.5678);
  // * returns 4: ' $ 1,234.57 '
  // * example 5: money_format('%(14#8.2n', -1234.5678);
  // * returns 5: '($ 1,234.57)'
  // * example 6: money_format('%=014#8.2n', 1234.5678);
  // * returns 6: ' $000001,234.57'
  // * example 7: money_format('%=014#8.2n', -1234.5678);
  // * returns 7: '-$000001,234.57'
  // * example 8: money_format('%=*14#8.2n', 1234.5678);
  // * returns 8: ' $*****1,234.57'
  // * example 9: money_format('%=*14#8.2n', -1234.5678);
  // * returns 9: '-$*****1,234.57'
  // * example 10: money_format('%=*^14#8.2n', 1234.5678);
  // * returns 10: ' $****1234.57'
  // * example 11: money_format('%=*^14#8.2n', -1234.5678);
  // * returns 11: ' -$****1234.57'
  // * example 12: money_format('%=*!14#8.2n', 1234.5678);
  // * returns 12: ' *****1,234.57'
  // * example 13: money_format('%=*!14#8.2n', -1234.5678);
  // * returns 13: '-*****1,234.57'
  // * example 14: money_format('%i', 3590);
  // * returns 14: ' USD 3,590.00'

  // Per PHP behavior, there seems to be no extra padding for sign when there is a positive number, though my
  // understanding of the description is that there should be padding; need to revisit examples

  // Helpful info at http://ftp.gnu.org/pub/pub/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_7.html and http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/strfmp.htm

  if (typeof number !== 'number') {
    return null;
  }
  var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g; // 1: flags, 3: width, 5: left, 7: right, 8: conversion

  this.setlocale('LC_ALL', 0); // Ensure the locale data we need is set up
  var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY'];

  var doReplace = function (n0, flags, n2, width, n4, left, n6, right, conversion) {
    var value = '',
      repl = '';
    if (conversion === '%') { // Percent does not seem to be allowed with intervening content
      return '%';
    }
    var fill = flags && (/=./).test(flags) ? flags.match(/=(.)/)[1] : ' '; // flag: =f (numeric fill)
    var showCurrSymbol = !flags || flags.indexOf('!') === -1; // flag: ! (suppress currency symbol)
    width = parseInt(width, 10) || 0; // field width: w (minimum field width)

    var neg = number < 0;
    number = number + ''; // Convert to string
    number = neg ? number.slice(1) : number; // We don't want negative symbol represented here yet

    var decpos = number.indexOf('.');
    var integer = decpos !== -1 ? number.slice(0, decpos) : number; // Get integer portion
    var fraction = decpos !== -1 ? number.slice(decpos + 1) : ''; // Get decimal portion

    var _str_splice = function (integerStr, idx, thous_sep) {
      var integerArr = integerStr.split('');
      integerArr.splice(idx, 0, thous_sep);
      return integerArr.join('');
    };

    var init_lgth = integer.length;
    left = parseInt(left, 10);
    var filler = init_lgth < left;
    if (filler) {
      var fillnum = left - init_lgth;
      integer = new Array(fillnum + 1).join(fill) + integer;
    }
    if (flags.indexOf('^') === -1) { // flag: ^ (disable grouping characters (of locale))
      // use grouping characters
      var thous_sep = monetary.mon_thousands_sep; // ','
      var mon_grouping = monetary.mon_grouping; // [3] (every 3 digits in U.S.A. locale)

      if (mon_grouping[0] < integer.length) {
        for (var i = 0, idx = integer.length; i < mon_grouping.length; i++) {
          idx -= mon_grouping[i]; // e.g., 3
          if (idx <= 0) {
            break;
          }
          if (filler && idx < fillnum) {
            thous_sep = fill;
          }
          integer = _str_splice(integer, idx, thous_sep);
        }
      }
      if (mon_grouping[i - 1] > 0) { // Repeating last grouping (may only be one) until highest portion of integer reached
        while (idx > mon_grouping[i - 1]) {
          idx -= mon_grouping[i - 1];
          if (filler && idx < fillnum) {
            thous_sep = fill;
          }
          integer = _str_splice(integer, idx, thous_sep);
        }
      }
    }

    // left, right
    if (right === '0') { // No decimal or fractional digits
      value = integer;
    } else {
      var dec_pt = monetary.mon_decimal_point; // '.'
      if (right === '' || right === undefined) {
        right = conversion === 'i' ? monetary.int_frac_digits : monetary.frac_digits;
      }
      right = parseInt(right, 10);

      if (right === 0) { // Only remove fractional portion if explicitly set to zero digits
        fraction = '';
        dec_pt = '';
      } else if (right < fraction.length) {
        fraction = Math.round(parseFloat(fraction.slice(0, right) + '.' + fraction.substr(right, 1))) + '';
        if (right > fraction.length) {
          fraction = new Array(right - fraction.length + 1).join('0') + fraction; // prepend with 0's
        }
      } else if (right > fraction.length) {
        fraction += new Array(right - fraction.length + 1).join('0'); // pad with 0's
      }
      value = integer + dec_pt + fraction;
    }

    var symbol = '';
    if (showCurrSymbol) {
      symbol = conversion === 'i' ? monetary.int_curr_symbol : monetary.currency_symbol; // 'i' vs. 'n' ('USD' vs. '$')
    }
    var sign_posn = neg ? monetary.n_sign_posn : monetary.p_sign_posn;

    // 0: no space between curr. symbol and value
    // 1: space sep. them unless symb. and sign are adjacent then space sep. them from value
    // 2: space sep. sign and value unless symb. and sign are adjacent then space separates
    var sep_by_space = neg ? monetary.n_sep_by_space : monetary.p_sep_by_space;

    // p_cs_precedes, n_cs_precedes // positive currency symbol follows value = 0; precedes value = 1
    var cs_precedes = neg ? monetary.n_cs_precedes : monetary.p_cs_precedes;

    // Assemble symbol/value/sign and possible space as appropriate
    if (flags.indexOf('(') !== -1) { // flag: parenth. for negative
      // Fix: unclear on whether and how sep_by_space, sign_posn, or cs_precedes have
      // an impact here (as they do below), but assuming for now behaves as sign_posn 0 as
      // far as localized sep_by_space and sign_posn behavior
      repl = (cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') : '') + value + (!cs_precedes ? (sep_by_space === 1 ? ' ' : '') + symbol : '');
      if (neg) {
        repl = '(' + repl + ')';
      } else {
        repl = ' ' + repl + ' ';
      }
    } else { // '+' is default
      var pos_sign = monetary.positive_sign; // ''
      var neg_sign = monetary.negative_sign; // '-'
      var sign = neg ? (neg_sign) : (pos_sign);
      var otherSign = neg ? (pos_sign) : (neg_sign);
      var signPadding = '';
      if (sign_posn) { // has a sign
        signPadding = new Array(otherSign.length - sign.length + 1).join(' ');
      }

      var valueAndCS = '';
      switch (sign_posn) {
        // 0: parentheses surround value and curr. symbol;
        // 1: sign precedes them;
        // 2: sign follows them;
        // 3: sign immed. precedes curr. symbol; (but may be space between)
        // 4: sign immed. succeeds curr. symbol; (but may be space between)
      case 0:
        valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
        repl = '(' + valueAndCS + ')';
        break;
      case 1:
        valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
        repl = signPadding + sign + (sep_by_space === 2 ? ' ' : '') + valueAndCS;
        break;
      case 2:
        valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol;
        repl = valueAndCS + (sep_by_space === 2 ? ' ' : '') + sign + signPadding;
        break;
      case 3:
        repl = cs_precedes ? signPadding + sign + (sep_by_space === 2 ? ' ' : '') + symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + sign + signPadding + (sep_by_space === 2 ? ' ' : '') + symbol;
        break;
      case 4:
        repl = cs_precedes ? symbol + (sep_by_space === 2 ? ' ' : '') + signPadding + sign + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol + (sep_by_space === 2 ? ' ' : '') + sign + signPadding;
        break;
      }
    }

    var padding = width - repl.length;
    if (padding > 0) {
      padding = new Array(padding + 1).join(' ');
      // Fix: How does p_sep_by_space affect the count if there is a space? Included in count presumably?
      if (flags.indexOf('-') !== -1) { // left-justified (pad to right)
        repl += padding;
      } else { // right-justified (pad to left)
        repl = padding + repl;
      }
    }
    return repl;
  };

  return format.replace(regex, doReplace);
}


Q: Can't boot Ubuntu 18.04 with encrypted boot I've been using Ubuntu 18.04 with full disk encryption, lvm partitions and encrypted boot for months without any problem and now all of a sudden I am not able to boot using grub.
When I power on my computer the minimal grub bash is shown and I am able to boot with this manual procedure:
set prefix=/efi/ubuntu/
insmod luks
cryptomount (hdx,gpty)
set root=(lvm/system-root)/
linux (lvm/system-boot)/vmlinuz-[...]
initrd (lvm/system-boot)/initrd-[...]
insmod normal
normal
boot

Once booted I tried to reinstall grub with this command, after setting GRUB_ENABLE_CRYPTODISK=y in /etc/default/grub:
sudo grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=ubuntu

After rebooting, the minimal bash prompt appears again and I have to repeat this procedure from scratch... What am I doing wrong?

A: I managed to solve this problem by booting using the above mentioned procedure and running Boot Repair a couple of times. Black magic is always the solution!


Q: Caliburn.Micro No target found for method I'm using Caliburn.Micro for my WP7 project and I keep getting this strange error for some of my pages. I can't reproduce it myself but it very often appears in Bugsense logs. This is how I use it.
XAML:
cal:Message.Attach="[Event Loaded] = [Action Init()]"

And in my ViewModel:
public async Task Init() {...}

Or on other pages just
public void Init() {...}

This is stacktrace from Bugsense:
0 System.Exception: No target found for method Init.
1 at Caliburn.Micro.ActionMessage.Invoke(Object eventArgs)
2 at System.Windows.Interactivity.TriggerAction.CallInvoke(Object parameter)
3 at System.Windows.Interactivity.TriggerBase.InvokeActions(Object parameter)
4 at System.Windows.Interactivity.EventTriggerBase.OnEvent(EventArgs eventArgs)
5 at System.Windows.Interactivity.EventTriggerBase.OnEventImpl(Object sender, EventArgs eventArgs)
6 at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
7 at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)

Any ideas on how I can determine what's wrong?


Q: Load a Bitmap into VB 6 PictureBox I wrote a library which has a function call that returns a System.Drawing.Bitmap. Everything works great and I can access it just fine from a C# WPF application. However, now I need to make it work with a VB 6 application and for the life of me I can`t get it to work. I have a VB6 picturebox (note: this could be changed to an image control if necessary; we just need the image to display on the screen somehow) Right now I have tried the following unsuccessfully:
Set Form1.PictureBox1.Image = myImage <-- This causes invalid use of property on 'Form1.PictureBox1.Image'

Form1.PictureBox1.Image = myImage <-- This causes invalid use of property on 'Form1.PictureBox1.Image'

Form1.PictureBox1.Picture = myImage <-- This cause 'type mismatch'

Help please! I don`t know VB at all let alone VB 6.


Q: Parsing a HTML file in Java I am currently in the process of developing an application that will request some information from Websites. What I'm looking to do is parse the HTML files through a connection online. I was just wondering, by parsing the Website will it put any strain on the server, will it have to download any excess information or will it simply connect to the site as I would do through my browser and then scan the source?
If this is putting extra strain on the Website then I'm going to have to make a special request to some of the companies I'm scanning. However if not then I have the permission to do this.
I hope this made some sort of sense.
Kind regards,
Jamie.

A: No extra strain on other people servers. The server will get your simple HTML GET request, it won't even be aware that you're then parsing the page/html.
Have you checked this: JSoup?

A: Consider doing the parsing and the crawling/scraping in separate steps. If you do that, you can probably use an existing open-source crawler such as crawler4j that already has support for politeness delays, robots.txt, etc. If you just blindly go grabbing content from somebody's site with a bot, the odds are good that you're going to get banned (or worse, if the admin is feeling particularly vindictive or creative that day).

A: Depends on the website. If you do this to Google then most likely you will be on a hold for a day. If you parse Wikipedia, (which I have done myself) it won't be a problem because its already a huge, huge website.
If you want to do it the right way, first respect robots.txt, then try to scatter your requests. Also try to do it when the traffic is low. Like around midnight and not at 8AM or 6PM when people get to computers.

A: Besides Hank Gay's recommendation, I can only suggest that you can also re-use some open-source HTML parser, such as Jsoup, for parsing/processing the downloaded HTML files.

A: You could use htmlunit. It gives you virtual gui less browser.

A: Your Java program hitting other people's server to download the content of a URL won't put any more strain on the server than a web browser doing so-- essentially they're precisely the same operation. In fact, you probably put less strain on them, because your program probably won't be bothered about downloading images, scripts etc that a web browser would.
BUT:

*

*if you start bombarding a server of a company with moderate resources with downloads or start exhibiting obvious "robot" patterns (e.g. downloading precisely every second), they'll probably block you; so put some sensible constraints on what you do (e.g. every consecutive download to the same server happens at random intervals of between 10 and 20 seconds);

*when you make your request, you probably want to set the "referer" request header either to mimic an actual browser, or to be open about what it is (invent a name for your "robot", create a page explaining what it does and include a URL to that page in the referer header)-- many server owners will let through legitimate, well-behaved robots, but block "suspicious" ones where it's not clear what they're doing;

*on a similar note, if you're doing things "legally", don't fetch pages that the site's "robot.txt" files prohibits you from fetching.

Of course, within some bounds of "non-malicious activity", in general it's perfectly legal for you to make whatever request you want whenever you want to whatever server. But equally, that server has a right to serve or deny you that page. So to prevent yourself from being blocked, one way or another, you need to either get approval from the server owners, or "keep a low profile" in your requests.


Q: Show chaing slider value in console I have a slider and span which display the value of the changing value like this:

var slider = document.getElementById("myRange");
var output = document.getElementById("dynamicSet");
output.innerHTML = slider.value; // Display the default slider value

// Update the current slider value (each time you drag the slider handle)
let update = () => output.innerHTML = slider.value;

slider.addEventListener('input', update);
update();
const setAmount = document.getElementById("dynamicSet").innerHTML;
console.log(setAmount);

Aantal sets:

    <input type="range" min="1" max="10" value="50" class="slider" id="myRange">

The webpage displays the changing value which works great! However when I try to console log it, it just shows the initial value the slider is at. I am trying to push this value to a DB (with a clikc of a submit button) but I noticed the value stayed the same as in the initial when opening the page:

I need the back end value to change as well. How can do this? i thought that the even listener already took care of this..

A: please check this, hope it will work :-)

var slider = document.getElementById("myRange");
var output = document.getElementById("dynamicSet");
var isShow = true
output.innerHTML = slider.value
update=()=>{

output.innerHTML = slider.value;
// Display the default slider value
console.log(slider.value)
}

// Update the current slider value (each time you drag the slider handle)
//let update = () => output.innerHTML = slider.value;

slider.addEventListener('input', update);

Aantal sets:

    <input type="range" min="1" max="10" value="50" class="slider" id="myRange">

A: you can try this
let update = () => {
  output.innerHTML = slider.value;
  console.log(slider.value)
}


Q: Monte-Carlo Simulation for the sum of die I am very new to programming so I apologise in advance for my lack of knowledge.
I want to find the probability of obtaining the sum k when throwing m die. I am not looking for a direct answer, I just want to ask if I am on the right track and what I can improve.
I begin with a function that calculates the sum of an array of m die:
function dicesum(m)
j = rand((1:6), m)
sum(j)
end

Now I am trying specific values to see if I can find a pattern (but without much luck). I have tried m = 2 (two die). What I am trying to do is to write a function which checks whether the sum of the two die is k and if it is, it calculates the probability. My attempt is very naive but I am hoping someone can point me in the right direction:
m = 2
x, y = rand(1:6), rand(1:6)
z = x+y
if z == dicesum(m)
Probability = ??/6^m

I want to somehow find the number of 'elements' in dicesum(2) in order to calculate the probability. For example, consider the case when dicesum(2) = 8. With two die, the possible outcomes are (2,6),(6,2), (5,3), (3,5), (4,4), (4,4). The probability being (2/36)*3.
I understand that the general case is far more complicated but I just want an idea of how to being this problem. Thanks in advance for any help.

A: If I understand correctly, you want to use simulation to approximate the probability of obtaining a sum of k when roll m dice. What I recommend is creating a function that will take k and m as arguments and repeat the simulation a large number of times. The following might help you get started:
function Simulate(m,k,Nsim=10^4)
    #Initialize the counter
    cnt=0
    #Repeat the experiment Nsim times
    for sim in 1:Nsim
        #Simulate roll of m dice
        s = sum(rand(1:6,m))
        #Increment counter if sum matches k
        if s == k
            cnt += 1
        end
    end
    #Return the estimated probability
    return cnt/Nsim
end

prob = Simulate(3,4)

The estimate is approximately .0131.

A: You can also perform your simulation in a vectorized style as shown below. Its less efficient in terms of memory allocation because it creates a vector s of length Nsim, whereas the loop code uses a single integer to count, cnt. Sometimes unnecessary memory allocation can cause performance issues. In this case, it turns out that the vectorized code is about twice as fast. Usually, loops are a bit faster. Someone more familiar with the internals of Julia might be able to offer an explanation.
function Simulate1(m,k,Nsim=10^4)
    #Simulate roll of m dice Nsim times
    s = sum(rand(1:6,Nsim,m),2)
    #Relative frequency of matches
    prob = mean(s .== k)
    return prob
end


Q: How do i add transitions to my current JavaScript code? I am currently working on a website project, and i have put together this code (JavaScript) for a slider using an online YouTube tutorial.
<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="style.css">

    <title></title>

HOME

MENU

ABOUT

GALLERY

REVIEWS

CONTACT

However the tutorial did not show how to add transitions into the slider and that is what i need help on.
There are two transition effects i am looking for which are:

*

*OnLoad the image should fade in.

*The image should swipe left when changing.

A: Take a look at css transitions and/or animations.
You could just update the css in your Javascript code like this:
CSS
#img {
    /* Initialize with 0% opacity (invisible) */
    opacity: 0%;

    /* Use prefix for cross browser compatibility */
    transition: opacity 1s;
    -o-transition: opacity 1s;
    -moz-transition: opacity 1s;
    -webkit-transition: opacity 1s;
}

Javascript
Image.onload = function(){
    this.style.opacity = "100%";
}

You can use the same technique for swiping with the left property with a relative position in CSS.
Adding it to the code
var imagecount = 1;
var total = 2;

function slide (x){
    var Image = document.getElementById('img');
    imagecount = imagecount + x;
    if(imagecount > total){imagecount = 1;}
    if(imagecount < 1){imagecount = total;}
    Image.src = "images/img"+ imagecount +".png";

    Image.style.opacity = "0%"; // Reset the opacity to 0% when reloading the image !
}

window.setInterval(function slideA () {
    var Image = document.getElementById('img');
    imagecount = imagecount + 1;
    if(imagecount > total){ imagecount = 1;}
    if(imagecount < 1){ imagecount = total;}
    Image.src = "images/img"+ imagecount +".png";

    Image.style.opacity = "0%"; // Reset the opacity to 0% when reloading the image !
},5000);

Then simply add it in the html node:


Q: AWS ElasticSearch Service throws 403 forbidden on document insert I am trying to upload data into AWS ElasticSearch using hive query.
The Intermediate table used within Hive query has following structure.
CREATE TABLE uid_taxonomy_1_day_es(
UID String
,VISITS INT
,TAXONOMY_LABEL_1 INT
,TAXONOMY_LABEL_2 INT
,TAXONOMY_LABEL_3 INT
,DAY_OF_YEAR INT)
STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler'
TBLPROPERTIES('es.nodes' = 'https://search-cust-360-view-
6cj2j4mcytbtrpodzffnh3uadi.us-east-1.es.amazonaws.com', 'es.port' = '443',
'es.index.auto.create' = 'false', 'es.batch.size.entries' = '1000',
'es.batch.write.retry.count' = '10000', 'es.batch.write.retry.wait' = '10s',
'es.batch.write.refresh' = 'false','es.nodes.discovery' =
'false','es.nodes.client.only' = 'false', 'es.resource' =
'urltaxonomy/uids', 'es.query' = '?q=*', 'es.nodes.wan.only' = 'true');

The actual load query takes around half hour in loading the data.
And so in between at some random record it will throw 403 forbidden error.
Here is the stacktrace.
Caused by: org.elasticsearch.hadoop.rest.EsHadoopInvalidRequest: [HEAD] on [urltaxonomy] failed; server[https://search-cust-360-view-6cj2j4mcytbtrpodzffnh3uadi.us-east-1.es.amazonaws.com:443] returned [403|Forbidden:]
at org.elasticsearch.hadoop.rest.RestClient.checkResponse(RestClient.java:505)
at org.elasticsearch.hadoop.rest.RestClient.executeNotFoundAllowed(RestClient.java:476)
at org.elasticsearch.hadoop.rest.RestClient.exists(RestClient.java:537)
at org.elasticsearch.hadoop.rest.RestClient.touch(RestClient.java:543)
at org.elasticsearch.hadoop.rest.RestRepository.touch(RestRepository.java:412)
at org.elasticsearch.hadoop.rest.RestService.initSingleIndex(RestService.java:606)
at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:594)
at org.elasticsearch.hadoop.mr.EsOutputFormat$EsRecordWriter.init(EsOutputFormat.java:173)

The error happens only intermittently by which mean if i try to insert that failed record, it works fine.
I am thinking its some thing to do with my intermediate table structure.


Q: Firebase Cohorts in BigQuery I am trying to replicate Firebase Cohorts using BigQuery. I tried the query from this post: Firebase exported to BigQuery: retention cohorts query, but the results I get don't make much sense.
I manage to get the users for period_lag 0 similar to what I can see in Firebase, however, the rest of the numbers don't look right:
Results:

There is one of the period_lag missing (only see 0,1 and 3 -> no 2) and the user counts for each lag period don't look right either! I would expect to see something like that:
Firebase Cohort:

I'm pretty sure that the issue is in how I replaced the parameters in the original query with those from Firebase. Here are the bits that I have updated in the original query:
#standardSQL
WITH activities AS (
  SELECT answers.user_dim.app_info.app_instance_id AS id,
    FORMAT_DATE('%Y-%m', DATE(TIMESTAMP_MICROS(answers.user_dim.first_open_timestamp_micros))) AS period
  FROM `dataset.app_events_*` AS answers
  JOIN `dataset.app_events_*` AS questions
  ON questions.user_dim.app_info.app_instance_id = answers.user_dim.app_info.app_instance_id
 -- WHERE CONCAT('|', questions.tags, '|') LIKE '%|google-bigquery|%'

(...)

WHERE cohorts_size.cohort >= FORMAT_DATE('%Y-%m', DATE('2017-11-01'))
ORDER BY cohort, period_lag, period_label

So I'm using user_dim.first_open_timestamp_micros instead of create_date and user_dim.app_info.app_instance_id instead of id and parent_id. Any idea what I'm doing wrong?

A: I think there is a misunderstanding in the concept of how and which data to retrieve into the activities table. Let me state the differences between the case presented in the other StackOverflow question you linked, and the case you are trying to reproduce:

*

*In the other question, answers.creation_date refers to a date value that is not fix, and can have different values for a single user. I mean, the same user can post two different answers in two different dates, that way, you will end up with two activities entries like: {[ID:user1, date:2018-01],[ID:user1, date:2018-02],[ID:user2, date:2018-01]}.

*In your question, the use of answers.user_dim.first_open_timestamp_micros refers to a date value that is fixed in the past, because as stated in the documentation, that variable refers to The time (in microseconds) at which the user first opened the app. That value is unique, and therefore, for each user you will only have one activities entry, like:{[ID:user1, date:2018-01],[ID:user2, date:2018-02],[ID:user3, date:2018-01]}.

I think that is the reason why you are not getting information about the lagged retention of users, because you are not recording each time a user accesses the application, but only the first time they did.
Instead of using answers.user_dim.first_open_timestamp_micros, you should look for another value from the ones available in the documentation link I shared before, possibly event_dim.date or event_dim.timestamp_micros, although you will have to take into account that these fields refer to an event and not to a user, so you should do some pre-processing first. For testing purposes, you can use some of the publicly available BigQuery exports for Firebase.

Finally, as a side note, it is pointless to JOIN a table with itself, so regarding your edited Standard SQL query, it should better be:
#standardSQL
WITH activities AS (
  SELECT answers.user_dim.app_info.app_instance_id AS id,
    FORMAT_DATE('%Y-%m', DATE(TIMESTAMP_MICROS(answers.user_dim.first_open_timestamp_micros))) AS period
  FROM `dataset.app_events_*` AS answers
  GROUP BY id, period


Q: Json object in post not recognized as object in web api I have an angular client and want to execute a get request to my web api backend to get a list of items from the underlying Dapper Db Wrapper. Dapper allows me to pass in parameters as an anonymous object which would in csharp look like this:
connection.GetList<T>(new {myParam1:"a", myParam2: true});

What I want to achieve is, to create this parameter object in my angular frontend and pass it in a post request to the server which would then pass it on to the GetList function. The problem here is that the web api does not deserialize it as an (anonymous) object, but rather and IEnumerable of JTokens?
My web api signature is this:
public async Task<IHttpActionResult> MyFunction([FromBody]dynamic whereCond)

I have also tried to pass the object as string wrapped in an outer object like so (angular client):
this.migController.MigrationGetMigrationReports({whereCond: JSON.stringify({NotMigrated: true, MissingTargetFiles: 0})})

and then on the server I manually deserialize it as JObject:
string obj = whereCond.whereCond;
dynamic pObj = JObject.Parse(obj);

But this results in the exact same result: pObj is an IEnumerable and therefore I get an error message from the GetList call:

An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context

can anybody help?

A: The answer to my question turned out rather simple:
            dynamic pObj = JObject.Parse(obj).ToObject<ExpandoObject>();

I had to cast it as ExpandoObject not just dynamic.
@Tsahi: this is not a design problem. My intention was to provide the server with parameters (filter) which is a quite common task for a client to reduce the dataset to be transferred. We could debate a standard way how to provide these parameters, however. In my special case the most practical way is the anonymous object.


Q: Call C# function from asp.net Good morning,
I have the following asp Image and would like to add the on mouse over event, as follow:
<asp:Image ID="MapImage" runat="server" Height="601px" Width="469px" OnMouseOver="OnMouseOverMap"/>

I have also added the following method on the C# code:
protected void OnMouseOverMap(object sender, EventArgs e)
    {
        int i = 9;
    }

I also have created the same method without the parameters but I cannot manage to call that C# function.
Can somebody help me with this issue?, How can I do to call the C# function from the ASP code.
Cheers!

A: There is no OnMouseOver server-side event on asp:Image object.
What you can do you can write js function called on client-side onmouseover event and inside that function trigger click on hidden button or you can change Image to ImageButton and trigger click on that image.
    <asp:Image ID="MapImage" runat="server" Height="601px" Width="469px" onmouseover="javascript:foo()"/>
    <asp:Button ID="Button1" runat="server" style="display:none" OnClick="OnMouseOverMap" />

And in js function:
    function foo()
{
document.getElementById('<%= Button1.ClientID %>').click();
}

A: I am pretty sure that you are supposed to insert javascript code there and not a "code behind event handler reference". See ASP NET image onmouseover not working for example.


Q: Does canvas drawing work in Ionic 2? I am currently using a html5 canvas and by using ionic 2 (tap)="markPoint($event)" on the canvas in html, I am getting the position of the tap event. Below is the function which should place the mark:
public markPoint(event) {
    var position = event.center;
    let ctx = this.canvas.getContext('2d');
    ctx.beginPath();
    ctx.arc(position.x, position.y, 20, 0, 2 * Math.PI);
    ctx.fillStyle = '#00DD00';
    ctx.fill();
}

I am setting the canvas like so, where canvas is the id set in the html:
this.canvas = document.getElementById('canvas');

I don't see an issue with this code, however I am also not sure whether or not this is the best way to make marks within an application in ionic 2. Do you know if this should work, and if not why? Also if there are any better ways it would be awesome to here about them.

A: First of all we have to make more typescript<6> friendly. It's not enough just to get the canvas object like another HTML element using the id. In this case we should help a little, so my first change will be:
this.canvas = document.getElementById('canvas');

FOR =>
this.canvas = <HTMLCanvasElement>document.getElementById('canvas');

Then your function will look something like this:
public markPoint(event) {
    var position = event.center;
    let ctx: CanvasRenderingContext2D = this.canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(position.x, position.y, 20, 0, 2 * Math.PI);
    ctx.fillStyle = '#00DD00';
    ctx.fill();
}

Hope this help.


Q: Sequence splits if and only if $\varphi$ has right inverse Let $\varphi:M\rightarrow N$ be an $R$-module homomorphism. Prove that the short exact sequence
$$0 \rightarrow\text{ker}\varphi \rightarrow M \xrightarrow{\varphi}N\rightarrow 0$$
splits if and only if $\varphi$ has a right inverse.
Attempt:($\implies$) Assume the sequence splits. Then it is isomorphic to a sequence of the form
$$0\rightarrow \text{ker}\varphi \xrightarrow{\iota} \text{ker}\varphi \oplus N \xrightarrow{\pi} N \rightarrow0$$
Where $\iota$ and $\pi$ are the inclusion and projection maps. Thus $\iota:N \rightarrow \text{ker} \varphi \oplus N$ is a right inverse map to $\pi$, since
$$\pi \circ \iota(a)=\pi(0,a)=a$$
Since we can identify $\varphi$ with $\pi$, we can identify $\iota$ as the right inverse map to $\varphi$.
Comment: This last sentence seems a little imprecise. How can I be clearer? It doesn't seem right to say the maps $\varphi$ and $\pi$ are isomorphic. So what are they?
($\Longleftarrow$)
This problem is similar from an example in Aluffi's chapter 0, so I will try and adapt the proof. Suppose $\varphi$ has a right inverse $\psi:N \rightarrow M$. To show the sequence splits, I want to show that $M$ is isomorphic to $\text{ker}\varphi \oplus N$. But it seems that it would be easier to show $M \cong \text{coker} \psi\oplus N$(Assuming $\text{coker} \psi \cong \text{ker} \varphi$ which I am unable to verify).I will try to construct such an isomorphism. I was thinking $\alpha:\text{coker}\psi \oplus N \rightarrow M$ given by $(n+\psi(N),p) \mapsto n+\psi(p)$. This map does not seem right to me. Should I even be trying to show $M \cong \text{coker} \psi \oplus N$? However, even if this is the correct map, I am struggling to come up with an inverse. How should I proceed to do this to finish the problem?
In the left inverse case with short exact sequence
$$0 \rightarrow  M\xrightarrow{\varphi}N \rightarrow \text{coker}\varphi \rightarrow 0$$
the author shows $N \cong M \oplus \text{ker} \psi$ where $\psi$ is the right inverse to $\varphi$, by constructing the map $M \oplus \text{ker} \varphi \rightarrow N$ given by $(m,k) \mapsto \varphi(m)+k$ and gives an inverse $n \mapsto (\psi(n),n-\varphi \psi(n))$ to show the isomorphism. However, I have no idea how he constructs the inverse.

A: To address your first comment: you can be less imprecise there by being more explicit about the isomorphism. In particular, if the sequence $$
0 \to \ker \varphi \xrightarrow{i} M \xrightarrow{\varphi} N \to 0
$$
splits you have an isomorphism $f : M \to \ker \varphi \oplus N$ such that $f \circ i = \iota_1$ and $\pi_2 \circ f = \varphi$, where $\iota_1 : \ker \varphi \to \ker \varphi \oplus N$ and $\pi_2 : \ker \varphi \oplus N \to N$ are the corresponding inclusion and projection.
Then you have for $\iota_2 : N \to \ker \varphi \oplus N$ that $\pi_2 \circ i_2 = \mathrm{Id}_N$ and you define $r : N \to M$ by $r = f^{-1} \circ \iota_2$. Then $\varphi \circ r = \varphi \circ f^{-1} \circ \iota_2 = \pi_2 \circ \iota_2 = \mathrm{Id}_N$ so you have a right inverse.
For the converse, assume you have a right inverse $r : N \to M$. Note that a right inverse is injective, since $r(x) = r(y)$ implies $x = \varphi(r(x)) = \varphi(r(y)) = y$. Thus, we can identify $N$ with the submodule $\operatorname{im} r$ of $M$.
Our goal is to show that $M = \ker \varphi \oplus N$.
Now, to see how this can be done, let $m \in M$ . Then $n = \varphi(m)$ is an element of $N$ and since $r$ is a right inverse, for $m' = r(n)$ you have that $$\varphi(m - m') = \varphi(m) - (\varphi \circ r \circ \varphi)(m) = \varphi(m) - \varphi(m) = 0.$$
Thus $m - m' = i(k)$ for some unique $k \in \ker \varphi$ and we can write $m = i(k) + r(n)$.
Define $f : M \to \ker \varphi \oplus N$ by this decomposition, i.e. $$
f(m) = (k, \varphi(m)).
$$
You can verify this is an isomorphism with inverse $g : \ker \varphi \oplus N$ given by $g(k, n) = i(k) + r(n)$
Now, since $\varphi \circ i = 0$ you have $(f \circ i)(k) = (k, 0)$, i.e. is the inclusion $\iota_1 : \ker \varphi \to \ker \varphi \oplus N$. Similarly for $\pi_2 : \ker \varphi \oplus N \to N$ you have $(\pi_2 \circ f)(m) = \varphi(m)$, so $\pi_2 \circ f = \varphi$.
Thus the exact sequence splits, with $f$ giving the required isomorphism between exact sequences.


Q: can't catch adal:loginSuccess when not using popup I have an angularjs SPA with ui.router.
in my module config I have:
    $locationProvider.html5Mode(true).hashPrefix('!');
    $urlRouterProvider.otherwise('/');
    $stateProvider
      .state('welcome', {
          url: '/',
          template: '
<button type=\"button\" class=\"btn btn-primary\" ui-sref=\"login\">  Login</button>
',
      })
        .state('login', {
            url: '/login',
            template: '
 logging in ...
',
            controller: 'LoginController',
            controllerAs: 'vm',
            requireADLogin: true
        })
        .state('loggedin', {
            url: '/loggedin',
            templateUrl: '/app/logged-in.html',
            requireADLogin: true
        })
        .state('logout', {
            url: '/logout',
            template: '
 logging out ...
',
            controller: 'LogoutController'
        }) ;
   adalProvider.init(
   {
       instance: 'https://login.microsoftonline.com/',
       tenant: 'mytenant.onmicrosoft.com',
       clientId: 'myappid',
       extraQueryParameter: 'nux=1',
       popUp: true,
       cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
   },
   $httpProvider
   );

in LoginController:
function loginController($rootScope, $state, adalService) {
    /* jshint validthis:true */
    var vm = this;
    vm.title = 'login';
    vm.activate = activate;
    activate();
    function activate() {
        adalService.login();
    }
    $rootScope.$on('adal:loginSuccess', function (event, token) {
        console.log('loggedin');
        $state.go('loggedin');
    });
}

if I remove the popUp setting, I can't catch the adal:loginSuccess and so I always get back to default state (welcome screen).
Also, I know I can set the redirectUri, but I'm not sure how to do it. I've tried with http://myappurl/loggedin, trying to trigger the loggedin state, but it doesn't work.
Thanks
PS: template for welcome state is inline because for an unknown reason, if I use templateUrl, it throws an error (before introducing adal, it was working fine)

A: I am trying to reproduce the issue, however failed. Here is the script which works well for your reference:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <base href="/">
    <title></title>

Logout

Login

                Home | About

I used the latest version of adal-angular library(v1.0.14). This code sample will go to the about state after login with the popup page. Please let me know if the code works. And if you still have the problem, would you mind sharing with us a demo which could run?


Q: REACT: How to modify styles from another component The page of my site are build with these components:

<Routes />

Obviusly, Header and Footer for all the pages are always the same, but content loaded from Routes is not equal for each page. Ok, I make click over an option of the meny which is in Header component. I go to the page and the name of the option of the menu is correctly underlined.
For example, I'm at home and click over FAQS, I go to FAQS page and FAQS option is underlined.
But, I can go to whatever page from Routes or Footer component. For example, in Footer component I've got an option to go to FAQS page. If I click over this option, I go to FAQS page, but the style of FAQS option in the menu is not updated.
I have checked that in this case are not called methods like componentDidMount or componentDidUpdate.
Therefore, how can I update always the options of the menu which are in Header component?
Edit I:
header.js file
import React, { Component } from "react";
import {Row, Col} from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import { NavLink } from "react-router-dom";
import "../css/header.css";
import logo  from "../images/logo.png";

export class Header extends Component{
    constructor(props){
        super(props);
        this.state = {
            option1: String(window.location).endsWith("/faqs"),
            option2: String(window.location).endsWith("/about"),
            option3: String(window.location).endsWith("/login")
        }
        this.handleClick = this.handleClick.bind(this);
    }

    componentDidMount(){
        window.scrollTo(0, 0);
        console.log("Header.js(ComponentDidMount): Component cargado correctamente!!!");
    }

    componentDidUpdate(){
        window.scrollTo(0, 0);
        console.log("Header.js(componentDidUpdate): Component cargado correctamente!!!");
    }

    removeUnderline(){
        this.setState({
            option1: false,
            option2: false,
            option3: false
        })
    }

    handleClick(event){
        this.removeUnderline();
        if (event.target.id !== "logo"){
            this.setState({
                option1: event.target.id === "option1",
                option2: event.target.id === "option2",
                option3: event.target.id === "option3"
            })
        }
    }

    render(){
        return(

                <Row style = {{margin: 0}}>
                        <Col md = {6} style = {{textAlign: "left"}}>
                            <NavLink to="/" onClick = {this.handleClick}>

                            </NavLink>
                        </Col>
                        <Col md = {6} style = {{textAlign: "right", paddingTop: 25 + "px", paddingRight: 20 + "px"}}>
                            <NavLink to="/faqs" style = {{textDecoration: (this.state.option1) ? "underline" : "none", color: "#000000"}}>
                                FAQS
                            </NavLink> |
                            <NavLink to="/about" style = {{textDecoration: (this.state.option2) ? "underline" : "none", color: "#000000"}}>
                                About us
                            </NavLink> |
                            <NavLink to="/login" style = {{textDecoration: (this.state.option3) ? "underline" : "none", color: "#000000"}}>
                                Login
                            </NavLink>
                        </Col>
                </Row>

        )
    }
}

footer.js file
import React from "react";
import {Row, Col} from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import InstagramIcon from '@material-ui/icons/Instagram';
import FaceboookIcon from '@material-ui/icons/Facebook';
import {NavLink} from "react-router-dom";

export const Footer = () => {
    return(

            <Row style = {{margin: 0, textAlign: "center", marginTop: 75 + "px"}}>
                <Col md = {12}>
                    <InstagramIcon style = {{fontSize: 28 + "px"}} /> <FaceboookIcon style = {{fontSize: 28 + "px"}} />
                </Col>
            </Row>
            <Row style = {{margin: 0, textAlign: "center", marginTop: 15 + "px", fontWeight: "bold"}}>
                <Col md = {2}><NavLink to="/login" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>Login</NavLink></Col>
                <Col md = {2}><NavLink to="/contactus" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>Contact us</NavLink></Col>
                <Col md = {4}><NavLink to="/about" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>About us</NavLink></Col>
                <Col md = {2}><NavLink to="/faqs" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>FAQ</NavLink></Col>
                <Col md = {2}><NavLink to="/privacy" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>Privacy Policy</NavLink></Col>
            </Row>
            <Row style = {{marginTop: 50 + "px", marginBottom: 50 + "px"}}>
                <Col md = {12} style = {{fontSize: 10 + "pt"}}>@Copyright 2020 Breaded</Col>
            </Row>

    )
};

Edit II:
Router are wrapping to each component: Header, Routes and Footer
export const Container = () => {
    return(

            <Router>

                <Routes />

            </Router>

    )

}

routes.js
import React from "react";
import { Home } from "./pages/home/home";
import { About } from "./pages/about";
import  FAQ from "./pages/faq/faq";
import { Plans } from "./pages/plans/plans";
import { P404 } from "./pages/notfound";
import {
    Switch,
    Route,
  } from "react-router-dom";

export const Routes = () => {
    return(
        <Switch>
            <Route exact path="/" component={Home} />
            <Route exact path="/about" component={About} />
            <Route exact path="/faqs" component={FAQ} />
            <Route exact path="/plans" component={Plans} />
            <Route component={P404} />
        </Switch>
    )
}

What am I doing wrong?

A: The way you are applying your css text effects is not ideal.  It works in header, but requires a ton of unnecessary logic that is not present in your Footer.  And copying all that code would be a big violation of DRY.  But even better than abstracting the logic and applying to both components, react router has activeClassName and activeStyle that you can use to style active NavLinks.  Just use them similarly in both Header and Footer.  Using activeClassName and showing only the parts of the code you need here:
// Header.js

<Col md = {6} style = {{textAlign: "left"}}>
  <NavLink to="/" onClick = {this.handleClick}>

  </NavLink>
</Col>
<Col md = {6} style = {...}>
  <NavLink to="/faqs" activeClassName="active-nav-link">
    FAQS
  </NavLink> |
  <NavLink to="/about" activeClassName="active-nav-link">
    About us
  </NavLink> |
  <NavLink to="/login" activeClassName="active-nav-link">
    Login
  </NavLink>
</Col>

You can do the same in Footer:
// Footer.js

<Col md = {2}>
  <NavLink to="/login" activeClassName="active-nav-link">
    Login
  </NavLink>
</Col>
<Col md = {2}>
  <NavLink to="/contactus" activeClassName="active-nav-link">
    Contact us
  </NavLink>
</Col>
<Col md = {4}>
  <NavLink to="/about" activeClassName="active-nav-link">
    About us
  </NavLink>
</Col>
<Col md = {2}>
  <NavLink to="/faqs" activeClassName="active-nav-link">
    FAQ
  </NavLink>
</Col>
<Col md = {2}>
  <NavLink to="/privacy" activeClassName="active-nav-link">
    Privacy Policy
  </NavLink>
</Col>

And then in some associated css file, you can say:
.active-nav-link {
  text-decoration: underline
}

I don't remember if the NavLink returns an  or an
 with a nested , so that might affect how you write your css.  You can also use activeStyle and do inline styles as an object, as you had been doing in your original code.  Either way will work.


Q: boost::asio::async_read texutal stop condition? I'm writing a server with Boost, something pretty simple - accept an XML message, process, reply. But I'm running into trouble at telling it when to stop reading.
This is what I have right now: (_index is the buffer into which the data is read)
std::size_t tcp_connection::completion_condition(const boost::system::error_code& error,
std::size_t bytes_transferred)
{
    int ret = -1;
    std::istream is(&_index);
    std::string s;
    is >> s;

    if (s.find("</end_tag>") != std::string.npos) ret = 0;
    return ret;
}

void tcp_connection::start()
{
    // Get index from server
    boost::asio::async_read(_socket, _index, &(tcp_connection::completion_condition),
        boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));
}

This doesn't compile, since I have to define completion_condition as static to pass it to async_read; and I can't define _index as static since (obviously) I need it to be specific to the class.
Is there some other way to give parameters to completion_condition? How do I get it to recognize the ending tag and call the reading handler?

A: You can pass pointers to member functions. The syntax for doing it with C++ is tricky, but boost::bind hides it and makes it fairly easy to do.
An example would be making completion_condition non-static and passing it to async_read as such:boost::bind(&tcp_connection::completion_condition, this, _1, _2)
&tcp_connection::completion_condition is a pointer to the function. this is the object of type tcp_connection to call the function on. _1 and _2 are placeholders; they will be replaced with the two parameters the function is called with.


Q: Get data and sort from MySQL two tables I have table_1 and table_2 and they are the same structure, but different data. Need to get all the data from that tables in sort of create_date and no matter from which table (it can be 1 row from table_1, 3 rows from table_2 and then again from table_1). Is it possible? How? or shout I get two queries and then sort by date with PHP?
EDIT:
Sorry for first part, I thought I can do it from there, but seems like i can't :/
i have very big query like this
SELECT
    table_1.id,
    table_1.created,
    table_1.qty,
    table_1.comments,
    table_1.last_update,
    table_7.firstname,
    SUBSTRING(table_7.lastname, 1, 1) AS lastname,
    table_8.title country,
    table_3.value AS sim,
    table_1.offer_request,
    table_5.manufacturer AS manufacturer,
    table_4.name AS model,
    table_6.value AS specifications,
    table_9.value as shipping,
    table_1.model AS mid,
    table_1.user_id,
    table_1.callme,
    table_1.phoneprice,
    table_1.phoneprice_eur,
    table_1.currency,
    table_1.sel_buy_show_all,
    table_1.seller_buyer
FROM (`table_1`)

LEFT JOIN `table_3` ON `table_3`.`id` = `table_1`.`sim`
LEFT JOIN `table_4` ON `table_4`.`id` = `table_1`.`model`
LEFT JOIN `table_5` ON `table_5`.`id` = `table_1`.`manufacturer`
LEFT JOIN `table_6` ON `table_6`.`id` = `table_1`.`specifications`
LEFT JOIN `table_7` ON `table_7`.`id` = `table_1`.`user_id`
LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id`
LEFT JOIN `table_9` ON `table_9`.`id` = `table_1`.`types`
WHERE `table_1`.`status` =  '1'
AND `table_1`.`deleted` =  '0'
ORDER BY `last_update` DESC
LIMIT 200

And there is table_1 which structure is the same as table_2, and I need somehow to insert table_2 to the query with all joins like table_1

A: If I got your question right, you can use union like this -
select * from table_1 union select * from table_2 order by create_date desc

EDIT
Create a view like this -
create view table_1And2 as select * from table_1 union select * from table_2

table_1And2 is not a good name, give a meaningful name.
And modify your long query like this -
SELECT
table_1And2.id,
table_1And2.created,
table_1And2.qty,
table_1And2.comments,
table_1And2.last_update,
table_7.firstname,
SUBSTRING(table_7.lastname, 1, 1) AS lastname,
table_8.title country,
table_3.value AS sim,
table_1And2.offer_request,
table_5.manufacturer AS manufacturer,
table_4.name AS model,
table_6.value AS specifications,
table_9.value as shipping,
table_1And2.model AS mid,
table_1And2.user_id,
table_1And2.callme,
table_1And2.phoneprice,
table_1And2.phoneprice_eur,
table_1And2.currency,
table_1And2.sel_buy_show_all,
table_1And2.seller_buyer
FROM (`table_1And2`)

LEFT JOIN `table_3` ON `table_3`.`id` = `table_1And2`.`sim`
LEFT JOIN `table_4` ON `table_4`.`id` = `table_1And2`.`model`
LEFT JOIN `table_5` ON `table_5`.`id` = `table_1And2`.`manufacturer`
LEFT JOIN `table_6` ON `table_6`.`id` = `table_1And2`.`specifications`
LEFT JOIN `table_7` ON `table_7`.`id` = `table_1And2`.`user_id`
LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id`
LEFT JOIN `table_9` ON `table_9`.`id` = `table_1And2`.`types`
WHERE `table_1And2`.`status` =  '1'
AND `table_1And2`.`deleted` =  '0'
ORDER BY `last_update` DESC
LIMIT 200

A: Also I see the answer of @Rehban is a good one for you, I will produce another solution if you do not need view:
SELECT
mainTable.id,
mainTable.created,
mainTable.qty,
mainTable.comments,
mainTable.last_update,
table_7.firstname,
SUBSTRING(table_7.lastname, 1, 1) AS lastname,
table_8.title country,
table_3.value AS sim,
mainTable.offer_request,
table_5.manufacturer AS manufacturer,
table_4.name AS model,
table_6.value AS specifications,
table_9.value as shipping,
mainTable.model AS mid,
mainTable.user_id,
mainTable.callme,
mainTable.phoneprice,
mainTable.phoneprice_eur,
mainTable.currency,
mainTable.sel_buy_show_all,
mainTable.seller_buyer
FROM (Select * From `table_1` union Select * From `table_2`) as mainTable

LEFT JOIN `table_3` ON `table_3`.`id` = `mainTable `.`sim`
LEFT JOIN `table_4` ON `table_4`.`id` = `mainTable `.`model`
LEFT JOIN `table_5` ON `table_5`.`id` = `mainTable `.`manufacturer`
LEFT JOIN `table_6` ON `table_6`.`id` = `mainTable `.`specifications`
LEFT JOIN `table_7` ON `table_7`.`id` = `mainTable `.`user_id`
LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id`
LEFT JOIN `table_9` ON `table_9`.`id` = `mainTable `.`types`
WHERE `mainTable `.`status` =  '1'
AND `mainTable `.`deleted` =  '0'
ORDER BY `last_update` DESC
LIMIT 200


Q: Ordered Asynchronous AJAX Calls I'm creating a script that performs several functions and I want to update the user as the functions are completed.  I have nested $.ajax() calls with each subsequent call in the previous call's success block.
There are a total of 4 calls made for each loop.  Let's call them scan_1 through scan_4.  The success block of scan_1 calls scan_2 and so on down the chain.
For example, let's say I'm looping over 3 objects.  I want the process to go like this:
Loop 1

*

*scan_1

*scan_2

*scan_3

*scan_4

Loop 2

*

*scan_1

*scan_2

*scan_3

*scan_4

Loop 3

*

*scan_1

*scan_2

*scan_3

*scan_4

The problem is that it's running through all the scan_1 calls first.  I must be missing something, but I can't seem to figure it out.  Any advice would be much appreciated.
For reference, here is a snippet of scan_1 (irrelevant stuff snipped):
for(var i = 1; i <= 3; i++)
{
    $.ajax({
        type:       'GET',
        url:        url,
        data:       'do=scan&step=1&' + string,
        dataType:   'json',
        success:    function (result)
        {
            if(result.proceed == 'true')
            {
                $('#scan_progress').append(result.message);
                scan_2();
            }
            else
            {
                $('#scan_progress').append(result.message);
            }
        }
    });
}

Thoughts?
Thanks in advance.

A: Sounds like you need to use jQuery deferred. It basically allows you to chain multiple event handlers to the jQuery Ajax object and gives you finer control over when the callbacks are invoked.
Further reading:

*

*http://msdn.microsoft.com/en-us/scriptjunkie/gg723713

*http://www.erichynds.com/jquery/using-deferreds-in-jquery/

A: It's asynchronous - the "success" fires sometime in the future. The script does not wait for it to respond. Since you're firing off three requests in your loop, they will all be "scan1".
"scan_2" will be called as each request completes.
Change the request to synchronous if you want to control the order of events.

A: You are starting by sending off three ajax calls at once.
Scan1 (loop 1)
Scan1 (loop 2)
Scan1 (loop 3)
When each Scan 1 completes, it's subsequent Scan 2, and then Scan 3 are called.
What did you actually want to happen? Scan 1 2 and 3 of loop 1, then 1 2 and 3 of loop 2, and then 1 2 and 3 of loop 3? That would require more nesting, or possibly deferred objects.

A: Instead of using the success callback for each $.ajax() call, you can store each set of AJAX requests (their jqXHR objects) in an array and wait for all of them to resolve:
function scan_1 () {

    //setup array to store jqXHR objects (deferred objects)
    var jqXHRs = [];
    for(var i = 1; i <= 3; i++)
    {

        //push a new index onto the array, `$.ajax()` returns an object that will resolve when the response is returned
        jqXHRs[jqXHRs.length] = $.ajax({
            type:       'GET',
            url:        url,
            data:       'do=scan&step=1&' + string,
            dataType:   'json'
        });
    }

    //wait for all four of the AJAX requests to resolve before running `scan_2()`
    $.when(jqXHRs).then(function () {
        if(result.proceed == 'true') {
            scan_2();
        }
    });
}

A: I've had similar problems working heavily with SharePoint web services - you often need to pull data from multiple sources to generate input for a single process.
To solve it I embedded this kind of functionality into my AJAX abstraction library. You can easily define a request which will trigger a set of handlers when complete. However each request can be defined with multiple http calls. Here's the component (and detailed documentation):
DPAJAX at DepressedPress.com
This simple example creates one request with three calls and then passes that information, in the call order, to a single handler:
    // The handler function
function AddUp(Nums) { alert(Nums[1] + Nums[2] + Nums[3]) };

    // Create the pool
myPool = DP_AJAX.createPool();

    // Create the request
myRequest = DP_AJAX.createRequest(AddUp);

    // Add the calls to the request
myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [5,10]);
myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [4,6]);
myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [7,13]);

    // Add the request to the pool
myPool.addRequest(myRequest);

Note that unlike many of the other solutions provided this method does not force single threading of the calls being made - each will still run as quickly (or as slowly) as the environment allows but the single handler will only be called when all are complete. It also supports the setting of timeout values and retry attempts if your service is a little flakey.
I've found it insanely useful (and incredibly simple to understand from a code perspective).  No more chaining, no more counting calls and saving output.  Just "set it and forget it".


Q: Replace cells having inf value by 1 Given the following
Columns 1 through 17
    0.3108    0.7273       Inf    0.2878   -0.0947    0.1286   -0.3108    0.5634    0.2822    0.2362   -0.2628    0.0960   -0.1675   -0.0934   -0.1710   -0.3077   -0.2726

Columns 18 through 20

   -0.0630   -0.5097    0.1823

How to replace inf values by 1.
I know how to do it using a loop but is there a way to do it without?
What if want to save it with another name?i.e. data remains same data1=data except inf is replaced by 1?

A: Use isinf to detect Inf, and use the output as a logical index into your array:
data(isinf(data)) = 1;


Q: Proving that $3\mathbb{Z}/6\mathbb{Z} \trianglelefteq \mathbb{Z}/6\mathbb{Z}$. I have to prove  that $$3\mathbb{Z}/6\mathbb{Z} \trianglelefteq \mathbb{Z}/6\mathbb{Z}.$$
I proved $3\mathbb{Z}/6\mathbb{Z} \leq \mathbb{Z}/6\mathbb{Z}$, so I have to show
$\forall A \in \mathbb{Z}/6\mathbb{Z},$ $A^{-1}+3\mathbb{Z}/6\mathbb{Z}+A \subset 3\mathbb{Z}/6\mathbb{Z}$.
(Proof)
Let $A \in \mathbb{Z}/6\mathbb{Z}$.
I can write $A=a+6\mathbb{Z}$ where $a \in \mathbb{Z}$ and then $A^{-1}=-a+6\mathbb{Z}$.
I'm stuck here.
What I have to do next is letting $B \in A^{-1}+3\mathbb{Z}/6\mathbb{Z}+A $ and showing $B \in 3\mathbb{Z}/6\mathbb{Z}.$
But when I let $B \in A^{-1}+3\mathbb{Z}/6\mathbb{Z}+A $, how can I express $B$ ?

A: Since $G:=\Bbb Z/6\Bbb Z$ is abelian, each of its subgroups is normal. (See @azif00's excellent comment.)

Every quotient of an abelian group is abelian. But $\Bbb Z$ is abelian, so $6\Bbb Z$ is normal in $\Bbb Z$, so $\Bbb Z/6\Bbb Z$ is abelian.

It suffices, then, to show that $H:=3\Bbb Z/6\Bbb Z\le G$.
I will use the one-step subgroup test
Since $0\times 3=0\times 6=0$, we have $0+6\Bbb Z\in H$. Hence $H\neq\varnothing$.
Suppose $a+6\Bbb Z\in H$. Then $a\in 3\Bbb Z$. But $3\Bbb Z\subseteq \Bbb Z$. Hence $a+6\Bbb Z\in G$. Hence $H\subseteq G$.
Suppose $x=a+6\Bbb Z, y=b+6\Bbb Z\in H$, for some $a,b\in 3\Bbb Z$. Then
$$\begin{align}
x-y&= (a+6\Bbb Z)-(b+6\Bbb Z)\\
&=(a+6\Bbb Z)+((-b)+6\Bbb Z)\\
&=(a+(-b))+6\Bbb Z\\
&=(a-b)+6\Bbb Z,
\end{align}$$
but $a-b\in 3\Bbb Z$ since $3\Bbb Z\le \Bbb Z$. Hence $x-y\in H$.
Hence $H\le G$.
Hence $H\unlhd G$.


Q: Add to a 7-Zip archive: How to exclude certain file types/extensions? I want to archive a folder, but I want to exlude all media files.
How do I leave out *.avi and *.flac when archiving?

A: Only possible solution is to use the command-line version (it doesn't work in the GUI [Add to Archive] dialog):
7z.exe a Archive.7z C:\Folder\* -r -x!*.avi -x!*.flac

The "Parameters" input box in the GUI can only be used for compression parameters and cannot be used with standard command line parameters.

A: Also
7za -bt -mx9 a archive.7z d:\backups\*  -x!*.7z

and
7za -bt -mx9 a archive.7z d:\backups\*.*  -x!*.7z

Created different result. The one with *.* seem to work.


Q: Maximum number of users in MultiSelect User field for SharePoint Online I am looking for an answer on how many users I can store for Multi Select user field.
Tried looking around but couldn't find the answer.
One of the below link someone answer the same question for 2010 and 2013 but not for SharePoint Online.
Maximum User limit of People Picker Field

A: I didn't find the official documentation for it, but I think it should be the same as SharePoint server, with a maximum value set to 750.


Q: vb.net readline or readkey don't want to stop my program my code is working i tried it separately but the problem here is that when i'm putting them together , the readkey or readline don't stop the program and the do loop is not working too, can someone take a look please thank in advance
Dim count As Integer
Dim first(5) As Integer
Dim temp As Integer
Dim answer As String

Sub Main()
    Do
        Console.WriteLine("Please enter your first number")
        first(0) = Console.ReadLine

        Console.WriteLine("Please enter your second number")
        first(1) = Console.ReadLine

        Console.WriteLine("Please enter your third number")
        first(2) = Console.ReadLine

        Console.WriteLine("Please enter your fourth number")
        first(3) = Console.ReadLine
        Console.WriteLine("Please enter your fifth number")
        first(4) = Console.ReadLine

        Console.WriteLine("Please enter your sixth number")
        first(5) = Console.ReadLine

        randomnumber()

        Console.WriteLine("do you want to continue?")
        answer = Console.ReadLine
    Loop Until (answer = "n" Or answer = "No")
    Console.ReadKey()
End Sub

Sub randomnumber()
    Dim r As New List(Of Integer)
    Dim rg As New Random
    Dim rn As Integer
    Dim arraywinner(5) As Integer

    Do
        rn = rg.Next(1, 40)
        If Not r.Contains(rn) Then
            r.Add(rn)
        End If
    Loop Until r.Count = 6

    'store bane random value in array'
    arraywinner(0) = r(0)
    arraywinner(1) = r(1)
    arraywinner(2) = r(2)
    arraywinner(3) = r(3)
    arraywinner(4) = r(4)
    arraywinner(5) = r(5)

    'print random numbers
    count = 0
    While count <= 5
        Console.WriteLine("the randoms numbers are : " & arraywinner(count))
        count = count + 1
    End While

    'look for the amount of number
    temp = 0
    For count1 As Integer = 0 To 5
        For count2 As Integer = 0 To 5
            If arraywinner(count1) = first(count2) Then
                temp = temp + 1
            End If
        Next
    Next

    If temp = 1 Or temp = 0 Then
        Console.WriteLine("You have got " & temp & " number")
    Else
        Console.WriteLine("You have got " & temp & " numbers")
    End If
    money(temp)
End Sub

Sub money(ByVal t1 As Integer)
    'prend cash'
    If temp = 6 Then
        Console.WriteLine("Jackpot $$$$$$$$$$$$$")
    ElseIf temp = 3 Then
        Console.WriteLine(" money = 120")
    ElseIf temp = 4 Then
        Console.WriteLine("money = 500")
    ElseIf temp = 5 Then
        Console.WriteLine("money= 10,000")
    Else
        Console.WriteLine(" try next time")
        End
    End If
End Sub

A: You have two problems in money():
Sub money(ByVal t1 As Integer)
    'prend cash'
    If temp = 6 Then
        Console.WriteLine("Jackpot $$$$$$$$$$$$$")
    ElseIf temp = 3 Then
        Console.WriteLine(" money = 120")
    ElseIf temp = 4 Then
        Console.WriteLine("money = 500")
    ElseIf temp = 5 Then
        Console.WriteLine("money= 10,000")
    Else
        Console.WriteLine(" try next time")
        End
    End If
End Sub

Your parameter is t1, but you're using temp in all of your code.  As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all.
Secondly, you have End in the block for 0, 1, or 2 matches.  The End statement Terminates execution immediately., which means the program just stops.  Get rid of that line.
There are so many other things you could change, but that should fix your immediate problem...

A: I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place.
Module Module1
Private rg As New Random

Public Sub Main()
    'keep variables with as narrow a scope as possible
    Dim answer As String = Nothing
    'This line initializes and array of strings called words
    Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"}
    Dim WinnersChosen(5) As Integer

    Do
        'To shorten your code use a For loop
        For index = 0 To 5
            Console.WriteLine($"Please enter your {words(index)} number")
            WinnersChosen(index) = CInt(Console.ReadLine)
        Next
        Dim RandomWinners = GetRandomWinners()
        Console.WriteLine("The random winners are:")
        For Each i As Integer In RandomWinners
            Console.WriteLine(i)
        Next
        Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen)

        If WinnersCount = 1 Then
            Console.WriteLine($"You have guessed {WinnersCount} number")
        Else
            Console.WriteLine($"You have guessed {WinnersCount} numbers")
        End If
        Dim Winnings = Money(WinnersCount)
        'The formatting :N0 will add the commas to the number
        Console.WriteLine($"Your winnings are {Winnings:N0}")
        Console.WriteLine("do you want to continue? y/n")
        answer = Console.ReadLine.ToLower
    Loop Until answer = "n"
    Console.ReadKey()
End Sub
'Too much happening in the Sub
'Try to have a Sub or Function do only one job
'Name the Sub accordingly
Private Function GetRandomWinners() As List(Of Integer)
    Dim RandomWinners As New List(Of Integer)
    Dim rn As Integer
    'Good use of .Contains and good logic in Loop Until
    Do
        rn = rg.Next(1, 40)
        If Not RandomWinners.Contains(rn) Then
            RandomWinners.Add(rn)
        End If
    Loop Until RandomWinners.Count = 6
    Return RandomWinners
End Function

Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer
    Dim temp As Integer
    For count1 As Integer = 0 To 5
        For count2 As Integer = 0 To 5
            If r(count1) = WinnersChosen(count2) Then
                temp = temp + 1
            End If
        Next
    Next
    Return temp
End Function

Private Function Money(Count As Integer) As Integer
    'A Select Case reads a little cleaner
    Select Case Count
        Case 3
            Return 120
        Case 4
            Return 500
        Case 5
            Return 10000
        Case 6
            Return 1000000
        Case Else
            Return 0
    End Select
End Function
End Module


Q: shifting registers to right in the mic-1 without fetches this is the first time I post a question here so feel free to give me some feedback were something not described in the proper manner. To the actual question:
I was wondering if there was a way to shift a word in one of the registers TO THE RIGHT by 2 bytes without fetches or  the arithmetical shifter  (EX with fetch: just write the word to memory address 0x0 and fetch 0x0 -> << 8 copy it back in OPC or whatever then OR to the desired register, fetch address 0x1 and OR again to the register without shifting to left this time).
So a register containing 0xcccc1111 should become 0x0000cccc
Here is a small description of the micro-architecture of the mic-1.
Thanks for the help
The purpose is to copy a word that starts from memory 0x2 into LV in a more efficient fashion: this should work but it uses both fetch and write and it's probably complete trash :(
MAR=0; rd;
PC=1;
H=PC=PC+1;
PC=PC+H; fetch;
MDR= MDR <<8; rd;
LV=MDR<<8; rd;
PC=PC+1;
H=MBRU << 8; fetch;
LV = LV OR H;
H = MBRU;
LV = LV OR H;


Q: Averaging an increasing number of columns of a dataframe I have a data frame (wc2) with 7 columns:
    cm5      cm10      cm15      cm20      cm25      cm30       run_time
1 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060        0
2 0.4084525 0.4028010 0.3617393 0.2595060 0.1294412 0.1220099        2
3 0.4087809 0.4042515 0.3711077 0.3119956 0.2241836 0.1290348        4
4 0.4088547 0.4045780 0.3732053 0.3218224 0.2611785 0.1720426        6
5 0.4088770 0.4046887 0.3739936 0.3255557 0.2739738 0.2081264        8
6 0.4088953 0.4047649 0.3744183 0.3273794 0.2798225 0.2273250       10

For every row (run_time) I want to average first the 1st column, then the 1st and 2nd columns, then the 1st, 2nd and 3rd columns and so on until the 6th column. The averaged result should be in a new column or a new data frame (I don't mind).
I did it using the following code:
wc2$dia10 <- wc2$cm5
wc2$dia20 <- rowMeans(wc2[c("cm5", "cm10")])
wc2$dia30 <- rowMeans(wc2[c("cm5", "cm10", "cm15")])
wc2$dia40 <- rowMeans(wc2[c("cm5", "cm10", "cm15", "cm20")])
wc2$dia50 <- rowMeans(wc2[c("cm5", "cm10", "cm15", "cm20", "cm25")])
wc2$dia60 <- rowMeans(wc2[c("cm5", "cm10", "cm15", "cm20", "cm25", "cm30")])

From my basic knowledge of R I gather there is a much better way of doing that but I can't figure out how. Especially for when I'll have a bigger number of columns.
I had a look at the answer for "Sum over and increasing number of columns of a data frame in R" but couldn't understand or apply it to my data.
Thanks for any help

A: You can use Reduce with accumulate = TRUE argument as follows,
sapply(Reduce(c, 1:(ncol(df)-1), accumulate = TRUE)[-1], function(i) rowMeans(df[i]))

Or to get the exact output,
setNames(data.frame(df[1],sapply(Reduce(c, 1:(ncol(df)-1),accumulate = TRUE)[-1], function(i)
           rowMeans(df[i]))), paste0('dia', seq(from = 10, to = ncol(df[-1])*10, by = 10)))

Or as  @A5C1D2H2I1M1N2O1R2T1 suggests in comments,
do.call(cbind, setNames(lapply(1:6, function(x) rowMeans(df[1:x])),
                                        paste0("dia", seq(10, 60, 10)))

Both giving,

    dia10     dia20     dia30     dia40     dia50     dia60
1 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060
2 0.4084525 0.4056268 0.3909976 0.3581247 0.3123880 0.2806583
3 0.4087809 0.4065162 0.3947134 0.3740339 0.3440639 0.3082257
4 0.4088547 0.4067164 0.3955460 0.3771151 0.3539278 0.3236136
5 0.4088770 0.4067829 0.3958531 0.3782787 0.3574178 0.3325359
6 0.4088953 0.4068301 0.3960262 0.3788645 0.3590561 0.3371009

Or to add it to the original data frame, then,
cbind(df, setNames(lapply(1:6, function(x) rowMeans(df[1:x])),
                                    paste0("dia", seq(10, 60, 10))))

A: Here is an alternative method with apply and cumsum. Using rowMeans is almost surely preferable, but this method runs through the calculation in one pass.
setNames(data.frame(t(apply(dat[1:6], 1, cumsum) / 1:6)),
         paste0("dia", seq(10, 60, 10)))
      dia10     dia20     dia30     dia40     dia50     dia60
1 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060
2 0.4084525 0.4056268 0.3909976 0.3581247 0.3123880 0.2806583
3 0.4087809 0.4065162 0.3947134 0.3740339 0.3440639 0.3082257
4 0.4088547 0.4067164 0.3955460 0.3771151 0.3539278 0.3236136
5 0.4088770 0.4067829 0.3958531 0.3782787 0.3574178 0.3325359
6 0.4088953 0.4068301 0.3960262 0.3788645 0.3590561 0.3371009

Using the smarter Reduce("+" with accumulate suggested by @alexis-laz,  we could do
mapply("/", Reduce("+", dat[1:6], accumulate = TRUE), 1:6)

or to get a data.frame with the desired names
setNames(data.frame(mapply("/", Reduce("+", dat[1:6], accumulate = TRUE), 1:6)),
         paste0("dia", seq(10, 60, 10)))

The uglier code below follows the same idea, without mapply
setNames(data.frame(Reduce("+", dat[1:6], accumulate = TRUE)) /
                    rep(1:6, each=nrow(dat)), paste0("dia", seq(10, 60, 10)))


Q: MediaWiki: Global default '' is invalid for field editfont Anyone see and know what this error means and/or how to fix it?  I place it in a google search and it doesn't appear to be something that anyone normally has an issue with:

Global default '' is invalid for field editfont
Backtrace:
#0 /srv/http/SupportWiki/includes/Preferences.php(1152): Preferences::getPreferences(Object(User))
#1 /srv/http/SupportWiki/includes/specials/SpecialPreferences.php(43): Preferences::getFormObject(Object(User))
#2 /srv/http/SupportWiki/includes/SpecialPage.php(559): SpecialPreferences->execute(NULL)
#3 /srv/http/SupportWiki/includes/Wiki.php(254): SpecialPage::executePath(Object(Title))
#4 /srv/http/SupportWiki/includes/Wiki.php(64): MediaWiki->handleSpecialCases(Object(Title), Object(OutputPage), Object(WebRequest))
#5 /srv/http/SupportWiki/index.php(117): MediaWiki->performRequestForTitle(Object(Title), NULL, Object(OutputPage), Object(User), Object(WebRequest))
#6 {main}

A: I was running MediaWiki 1.16.0.  I upgraded to MediaWiki 1.16.2 and this resolved the issue.


Q: Detecting if SKAction is done running, Swift I want to change the value of a variable after an action has been run and not during it is running. This is my code:
   override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

    if gameNotStarted {
        if firePosition.x != 320 || firePosition.y > 280 {
            fire.runAction(fireButtonReturn)
            iapButton.runAction(iapButtonReturn)
            aboutButton.runAction(abtButtonReturn)

            if fire.hasActions() == false {
                println("has no actions")
                firePosition.x = 320
                firePosition.y = 280
            }
        }
    }
}

The three actions I am running have exactly the same duration so I only need one to check if they have finished running. After they have finished running I want to change the value offirePosition.x andfirePosition.y.
It is very important that fire position values change exactly after the action has been run and absolutely not before the actions are done running.
However with my current code I never run theif fire.hasActions() ... part according to results and console.
I found similar questions, they were in obj-c.
Thanks for your help.

A: You should use a completion-handler for your kind of problem:
//Run the action
iapButton.runAction(iapButtonReturn,
    //After action is done, just call the completion-handler.
    completion: {
        firePosition.x = 320
        firePosition.y = 280
    }
)

Or you could use a SKAction.sequence and add your actions inside a SKAction.block:
var block = SKAction.runBlock({
    fire.runAction(fireButtonReturn)
    iapButton.runAction(iapButtonReturn)
    aboutButton.runAction(abtButtonReturn)
})

var finish = SKAction.runBlock({
    firePosition.x = 320
    firePosition.y = 280
})

var sequence = SKAction.sequence([block, SKAction.waitForDuration(yourWaitDuration), finish])

self.runAction(sequence)

A: you should use a completion handler:
fire.runAction(fireButtonReturn,
    completion: {
        println("has no actions")
        firePosition.x = 320
        firePosition.y = 280
    }
)

the problem with your solution is, that the action is initiated with the runAction call but then runs in the background while the main thread continues the execution (and therefore reaches it before the action is finished).

A: extension SKNode {
    func actionForKeyIsRunning(key: String) -> Bool {
        if self.actionForKey(key) != nil {
            return true
        } else {
            return false
        }
    }
}

You can use it :
if myShip.actionForKeyIsRunning("swipedLeft") {
   print("swipe in action..")
}


Q: Modify the height of Bootstrap Carousel control? The blue section of the following image shows the triggering area of the bootstrap carousel. I took the screenshot from the bootstrap doc.

I would like to modify the height of the triggering region (e.g. From 100% of the carousel height to 50%). May I know how can I modify it?
Thanks in advance

A: To solve this, just modify the properties of .carousel-control-prev and .carousel-control-prev in the CSS.

.carousel-control-prev,
.carousel-control-next {
  height: 25%;
  top: 37.5%;
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

            Previous

            Next

I have no idea why the top property could not override in the demo. But it works in my project.


Q: Choosing approach for an IM client-server app Update: totally re-wrote this to be more succint.
I'm looking at a new application, one part of which will be very similar to standard IM clients, i.e text chat, ability to send attachments, maybe some real-time interaction like a multi-user whiteboard.
It will be client-server, i.e all traffic goes through my central server. That means if I want to support cross-communication with other IM systems, I am still free to pick any protocol for my own client<-->server communication - my server can use XMPP or whatever to talk to other systems.
Clients are expected to include desktop apps, but probably also browser-based as well either through Flex/Silverlight or HTML/AJAX.
I see 3 options for my own client-server communication layer:

*

*XMPP. The benefits are clients already exist as do open-source servers. However it requires the most up-front research/learning and also appears like it might raise legal issues due to GPL.

*Custom sockets. A server app makes connections with the clients, allowing any text/binary data to be sent very fast. However this approach requires building said server from scratch, and also makes a JS client tricky

*Servlets (or similar web server). Using tried and tested Java web-stack, clients send HTTP requests similar to AJAX-based websites. The benefit is the server is easy to write using well-established technologies, and easy to talk to. But what restrictions would this bring? Is it appropriate technology for real-time communication?
Advice and suggests are welcome, especially what pros and cons surround using a web-server approach as compared to a socket-based approach.

A: I think you are re-inventing the wheel.  Consider using OpenFire or Tigase which are Java-based and very proven in this IM server space.  All the boiler-plate can be leveraged.  You tasks would be to add custom behaviors by writing plug-ins.


Q: Why is my Modal form posting a null model back to the controller I have a partial view that I load in a Modal..in the index view the model div with the HTML.Partial
looks like this.

            @Html.Partial("_EditDatabaseInfo")

the partial view code is
@model Hybridinator.Domain.Entities.Database

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Edit Database Info

    @using (Html.BeginForm("EditDatabaseInfo", "Database", FormMethod.Post, new { @class = "modal-body" }))
    {

@Html.LabelFor(m => m.database, "Database")

@Html.EditorFor(m => m.database)

@Html.LabelFor(m => m.database_server, "Database Server")

@Html.EditorFor(m => m.database_server)

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button class="btn btn-inverse btn-primary" type="submit">Save</button>

    }

If fire this controller successfully
 [HttpPost]
       public ActionResult EditDatabaseInfo(Database database)
       {
           string s = database.database;
           //do other stuff
           return RedirectToAction("Index");
       }

Everything works fine up until I try to access the model in the controller post which should be passed into ActionResult method.   The Model object is null
Object reference not set to an instance of an object.
anyone see what Im missing here?

A: You have to pass the model in Header from the view and from controller and in partialview too
lisk below
Please get look deeply in bold text and the text in between ** **
**@model Hybridinator.Domain.Entities.Database**

        @Html.Partial("_EditDatabaseInfo", **Model** )

[HttpPost]
   public ActionResult EditDatabaseInfo(Database database)
   {
       string s = database.database;
       //do other stuff
       // **you have to get the model value in here and pass it to index action**
       return RedirectToAction(**"Index", modelValue**);
   }

 public ActionResult Index(**ModelClass classValue**)
   {
      //pass the model value into index view.
       return View(**"Index", classValue**);
   }

A: Change the Model in view, partial view and in action . Instead of passing entity model, create view model and pass it in  view as well as partial view. consider the following

@model **DatabaseModel**

            @Html.Partial("_EditDatabaseInfo", **Model**)

@model DatabaseModel

    <button type="button" class="close" data-dismiss="modal">×Close</button>

Edit Database Info

    @using (Html.BeginForm( new { @class = "modal-body" }))
    {

@Html.LabelFor(m => m.DatabaseName, "Database")

@Html.EditorFor(m => m.DatabaseName)

@Html.LabelFor(m => m.DatabaseServer, "Database Server")

@Html.EditorFor(m => m.DatabaseServer)

        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button class="btn btn-inverse btn-primary" type="submit">Save</button>

    }

public class DatabaseModel
{
    public string DatabaseName { get; set; }
    public string DatabaseServer { get; set; }
}

As of my knowledge Database is a key word, because of that it is getting null


Q: Efficiently Modifying CGColor I have an iPhone app where I'm "adding" a lot of CGColors together by breaking them down into their components, averaging the components, and then making a new color with the new components. When I run this code, Instruments finds that I'm leaking lots of CGColors, and the app runs slowly.
I feel like I could solve the memory leak issue if there were a way to do what I'm doing without using CGColorCreate(colorspace, components) every time.
This is the code for the color "adding"
const CGFloat *cs=CGColorGetComponents(drawColor);
const CGFloat *csA=CGColorGetComponents(add->drawColor);
CGFloat r=(cs[0]*w+csA[0]*aW)/1;
CGFloat g=(cs[1]*w+csA[1]*aW)/1;
CGFloat b=(cs[2]*w+csA[2]*aW)/1;
CGFloat components[]={r, g, b, 1.f};
drawColor=CGColorCreate(CGColorSpaceCreateDeviceRGB(), components);

Any help would be really appreciated, even if the help is "add the colors less often." I'm sure I'm not the only person trying to modify CGColors.
EDIT: So, rob's comment put me on the right track, but I'm getting malloc double free errors because the method with the color adding is called multiple times before a new drawColor is assigned. Is there a way to check whether drawColor exists before I release it? Here is the new relevant code.
CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
CGColorRelease(drawColor);
drawColor=CGColorCreate(colorSpace, components);
CGColorSpaceRelease(colorSpace);

A: Pretty sure you just need to CGColorRelease(drawColor) to prevent the leak. See how that helps your performance.

A: If you're leaking CGColor objects, the first step to solving your problem is to stop leaking them.  You need to call CGColorRelease when you're done with a color object.  For example, you are obviously leaking the drawColor object in your example code.  You should be doing this:
CGColorRelease(drawColor);
drawColor=CGColorCreate(CGColorSpaceCreateDeviceRGB(), components);

to release the old object referenced by drawColor before you assign the new object to drawColor.
CGColor objects are immutable, so you won't be able to just modify your existing objects.


Q: ModelMapper map one object into three In my Java project I am using ModelMapper for mapping from entity object into DTO object.
My entity have inside object hierarchy that has three Long properties.
My DTO object has only one Long properties, so I created custom map to map between them.
public class MyMap extends PropertyMap<DTO, Entity> {

  /**
   * Main function that is called when mapping objects.
   */
  @Override
  protected void configure() {

    final Converter<Long, Hierarchy> hierarchyToId = context -> {

      if (context.getSource() != null) {

        final Long Id = context.getSource();

        final HierarchyDto dto = calculateHierarchy(Id)

        // map dto to entity.
        final Hierarchy hierarchy = new Hierarchy();
        hierarchy.setFirstId(dto.getFirstId());
        hierarchy.setSecondId(dto.getSecondId());
        hierarchy.setThirdId(dto.getThirdId());

        return hierarchy;
      }

      return null;
     };

    // map objects.
    this.using(hierarchyToId).map(this.source.getId(), this.destination.getHierarchy());
  }

}
This give me an error :
java.lang.NullPointerException: null ...

ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.modelmapper.ConfigurationException: ModelMapper configuration errors:
1) The destination property com....DTO.setId() matches multiple source property hierarchies:

com....getHierarchy()/com....getFirstId()
com....getHierarchy()/com....getSecondId()
com....getHierarchy()/com....getThirdId()

1 error] with root cause
org.modelmapper.ConfigurationException: ModelMapper configuration errors:

I understand that Mapper has problems that I map one object into 3 but what do I need to do that it will work.


Q: toggle custom image in a UIBarButtonItem I've been breaking my head for the past two days searching and trying some of my own solutions. I placed a UIBarButtonItem through IB with an image in the top bar to act as a mute/unmute button . Everything works except the image doesn't change. I used the following code and it compiles but no change
if( mute == YES ) {
    UIImage *unmuteImage = [UIImage imageNamed:@"audio-on.png"];
    [self.muteButton setImage:unmuteImage];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"muteKey"];
}
else {
    UIImage *muteImage = [UIImage imageNamed:@"audio-off.png"];
    [self.muteButton setImage:muteImage];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"muteKey"];
}

A: I finally figured it out...only took a couple of days but I've been too busy to post up a solution. We'll I finally got time and am happy to post my solution. I had a hunch that this would'nt work unless it was done 100% programmatically, and I was right. Here's the final solution to my problem:
if(mute == YES)
{
    UIImage *image = [UIImage imageNamed:@"audio-off.png"];
    UIButton *myMuteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myMuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );
    [myMuteButton setImage:image forState:UIControlStateNormal];
    [myMuteButton addTarget:self action:@selector(mute) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *myMuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myMuteButton];
    navBar.leftBarButtonItem = myMuteBarButtonItem;
    [myMuteBarButtonItem release];
}
else
{
    UIImage *image = [UIImage imageNamed:@"audio-on.png"];
    UIButton *myUnmuteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myUnmuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );
    [myUnmuteButton setImage:image forState:UIControlStateNormal];
    [myUnmuteButton addTarget:self action:@selector(mute) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *myUnmuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myUnmuteButton];
    navBar.leftBarButtonItem = myUnmuteBarButtonItem;
    [myUnmuteBarButtonItem release];
}

the good news is I finally finished my app and submitted it to the app store. Hopefully everything will go smooth and am looking forward to it!

A: Swift,
I set mine around an instance var, and used that to toggle my switch. I also had 3 buttons in my nav bar.
private var activeStaff:Staff? {
    didSet {
        let image = (activeStaff == nil) ? UIImage(named: "active")! : UIImage(named: "notActive")!
        let button = UIBarButtonItem(image: image, style: .Plain, target: self, action: "activePressed:")

        if navigationItem.rightBarButtonItems?.count == 3 {
            navigationItem.rightBarButtonItems?.removeAtIndex(0)
        }

        navigationItem.rightBarButtonItems?.insert(button, atIndex: 0)
    }
}


Q: Why is there a margin around hr and img tags? I am trying to remove the whitespace around hr and img tags, I have not had any luck yet, Here is a JSFiddle.
Can someone show me how to do this?
Is it a good idea to use hrs instead of divs when creating a sepearation/surrounding? Should I use a div instead? Can someone tell me which one is the better option. Sorry for the short question.
SOME CODE :

img.banner {
    height: 200px;
    width: 100%;
}
hr.line {
    background-color: red;
    color: red;
    height: 20px;
}
.margin_padding {
    margin: 0px;
    padding: 0px;
}

EDIT :
Borders have a default border size I forgot about and the image should be displayed block

A: Add display:block to your img tag and border:0 to your hr tag.
.margin_padding {
  margin: 0;
  padding: 0;
  border: 0;
  display: block;
}

A: What you see is the default margin of the  tag. The actual value depends on the browser.
A common practice to avoid most browser's different default values is explicitly setting margin and padding to 0:
html, body {
    margin: 0;
    padding: 0;
}


Q: Need to set Cells value to 1 if condition met else existing value incremented by 1 for a column in VBA-Excel I have a table in sheet1 with two columns Name and Loan Amount and a similar table in sheet2 with an additional column called Counter. Example:
Table in Sheet1        Table in Sheet2
Name    Loan Amount    Name    Loan Amount    Counter
Ajit    8000           Ajit    8000           2
Rahul   8001           Rahul   8001           3
Gaurav  8002           Gaurav  8002           4
varun   8003           Varun   8003           2
                       Nama    30004          2
                       Sutra   30005          4
                       Patra   30006          5
                       Pakhi   30007          6
                       Ratan   30008          5

If Name in sheet1 matches with the Name in sheet2 the Loan Amount corresponding to the Name in sheet1 should be set in sheet2 for same Name. Also Counter should be set to 1. And if Name does not match in both the sheets then Counter in sheet2 for those names should be incremented by 1 so that resulted table in sheet2 look like:
Output Table in Sheet2
Name        Loan Amount      Counter,
Ajit            8000            1
Rahul           8001            1
Gaurav          8002            1
Varun           8003            1
Nama            30004           3
Sutra           30005           5
Patra           30006           6
Pakhi           30007           7
Ratan           30008           6

Please help me out with this how can I achieve this result in VBA excel. Please see what I am doing so far to achieving this but i am not getting how to increase counter where names do not match:
Private Sub CommandButton1_Click()
Dim i As Integer
Dim j As Integer
Dim Count1 As Integer
Dim Count2 As Integer
Count1 = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
Count2 = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count
For i = 2 To Count1
    For j = 2 To Count2
        If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then
        Worksheets("Sheet2").Cells(j, 2).Value = Worksheets("Sheet1").Cells(i, 2).Value
        Worksheets("Sheet2").Cells(j, 3).Value = 1
        End If
    Next j
Next i
End Sub

But through I am not getting how to increment the cells value for which names are not matching in both sheets.

A: UPDATED :
As per your Error and Tested

Private Sub CommandButton1_Click()
  Dim i As Integer 's
Dim j As Integer
Dim Count1 As Integer
Dim Count2 As Integer
Dim cell As Range
Count1 = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
Count2 = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count
For i = 2 To Count1

    For j = 2 To Count2
        If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then
          Worksheets("Sheet2").Cells(j, 2).Value = Worksheets("Sheet1").Cells(i, 2).Value
          Worksheets("Sheet2").Cells(j, 3).Value = 0

          Exit For
        End If

    Next j

Next i

For Each cell In Range("C2:" & "C" & Cells(Rows.Count, "C").End(xlUp).Row)
cell.Value = cell.Value + 1
Next
End Sub

Let me know, if you have gotten issues.

A: Private Sub CommandButton1_Click()
Dim i As Integer
Dim j As Integer
Total1 = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count
Total2 = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count
MsgBox Total1
For i = 2 To Total1
For j = 2 To Total2
If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then
Worksheets("Sheet2").Cells(j, 2).Value = Worksheets("Sheet1").Cells(i, 2).Value
Worksheets("Sheet2").Cells(j, 3).Value = 1
End If
Next j
Next i
For j = 2 To Total2
 If Worksheets("Sheet1").Cells(i, 1).Value <> 1 Then
 Worksheets("Sheet2").Cells(j, 3).Value = Worksheets("Sheet2").Cells(j, 3).Value + 1
 End If
 Next j
 End Sub

This code is also working fine for the above solution.


Q: Get just inserted id lua-sqlite3 Im trying to get just inserted autoincremented id:
local luasql = require "luasql.sqlite3"

dbname = "dbname"
table1 = "table1"
table2 = "table2"

env = luasql.sqlite3()
con = env:connect(dbname)

-- Create table1
res1 = con:execute(string.format("CREATE TABLE '%s' (" ..
    "id INTEGER PRIMARY KEY AUTOINCREMENT, " ..
    "test1 varchar(32), " ..
    "test2 varchar(32))", con:escape(table1)))

-- Create table2
res2 = con:execute(string.format("CREATE TABLE '%s' (" ..
    "id INTEGER PRIMARY KEY AUTOINCREMENT, " ..
    "id_of_row_in_table_1 varchar(32), " ..
    "test2 varchar(32))", con:escape(table2)))

-- Insert data into table1
last_inserted_id = con:execute(string.format("INSERT INTO '%s' ('%s', '%s')", con:escape(table1), 'test1', 'test2', con:escape('1'), con:escape('1')))

print(last_inserted_id) -- unfortunately this do not return just inserted id

-- Insert data into table2
res = con:execute(string.format("INSERT INTO '%s' ('%s', '%s')", con:escape(table2), 'last_inserted_id', 'test2', con:escape(last_inserted_id), con:escape('1')))

How to get the last inserted id? I consider an insert function should return just inserted id but it don't.

A: You could do something like this (I'm using lsqlite3 so adjust accordingly):
db = sqlite3.open(':memory:')

db:execute [[
create table xxx(xxx);
insert into xxx values('one');
insert into xxx values('two');
insert into xxx values('three');
]]

sql = [[select last_insert_rowid() as num;]]
for ans in db:nrows(sql) do
  print(ans.num)
end