text:
Q: sending SMS with Twilio I"m trying to figure this out, sorry if it's too basic of a question.
I have iPhone app with several hundred users.  While they're interacting with my app, I need the ability to send them several SMS messages (max 10).
Say 300 users, using the app once a week, with 10 SMS per use:
300*4*10 * .0075 = $90
There is also a $1 per month phone fee. Is that per phone of my users, or the single Twilio number that I am sending texts from?
I'm hoping it's not per user number, which would make my monthly $390.
I've reached out to Twilio, but still waiting a response.

A: Twilio developer evangelist here.
That charge for the phone number is per number you buy within the Twilio dashboard, it is not per number you are sending to.
So in your calculation, you are spending $91 per month sending SMS, not $390.


text:
Q: text-overflow:ellipsis; not truncating overflowing text and giving ellipsis I am trying to force the paragraphs in a small div to all be one line, no wrap, and when they overflow over the div to be truncated with ellipsis.
I got the no wrap working with white-space:nowrap;, but the text is still overflowing over the div even though I have set text-overflow to be ellipsis.
What am I doing wrong?
It shouldn't be support, because, surprisingly, both of those css3 properties are widely supported.
Here is a js fiddle with the problem: http://jsfiddle.net/4C7CW/

A: text-overflow
The text-overflow declaration allows you to deal with clipped text: that is, text that does not fit into its box.
text-overflow comes into play only when:

*

*the box has overflow other than visible (with overflow: visible the text simply flows out of the box)

*the box has white-space: nowrap or a similar method of constraining the way the text is laid out. (Without this, the text would wrap to the next line)

So...
#card
{
    width:200px;
    background:red;
    color:#000000;
    font-size:16px;
}

#card p
{
    -o-text-overflow:ellipsis;
    text-overflow:ellipsis;
    white-space:nowrap;
    overflow:hidden;
}

http://jsfiddle.net/4C7CW/3/

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to escape single quote in dynamically created HTML tag content In my javascript code,
I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";

I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.
content= ''

Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help

A: This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');

// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
    fun(name);
    return false;
}
anchor.innerHTML = 'hello world';

// later
mydiv.appendChild(anchor);

Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:

*

*The first is to serialize the variable properly; I would use JSON.stringify() for that

*The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = 'hello';


text:
Q: Unable to send base64 image to server from android I explored many questions related to this issue but nothing solved my problem.
I am sending base64 encoded image in android and sending it to the server but that encoded string is unable to reach the Godaddy server.
What I've tried:

*

*Encoded Image to base64

*Decoding Image in PHP

*Log.d("showEncodedImageString", image); // Showing correctly

I followed the same code for my localhost using wampserver and it worked like a charm. But unable to send the imageString to a live server. It is like whenever I send this encoded string, php crashes somehow. I don't know. It should through back an echo statement which I am showing there as error but no it doesn't throwback anything.
Java Code:
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
                    String encodedImage = ImageBase64.encode(bitmap);

                    HashMap<String, String> postData = new HashMap<String, String>();
                    postData.put("image", "-" + encodedImage );

                    PostResponseAsyncTask task = new PostResponseAsyncTask(actCtx, postData, new AsyncResponse() {
                        @Override
                        public void processFinish(String s) {
                                Toast.makeText(actCtx, s, Toast.LENGTH_SHORT).show();
                                /*Picasso.with(actCtx).load(SERVER_ADDRESS + loggedInEmail + ".jpeg").into(imageProfileIv);*/
                                dialog.dismiss();
                        }

                    });
                    task.execute("http://fatappstudios.com/Webservices/Junaid/QuoteMedia/db_image_upload.php");
                    task.setEachExceptionsHandler(new EachExceptionsHandler() {
                        @Override
                        public void handleIOException(IOException e) {
                            Toast.makeText(getActivity(), "IOException", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void handleMalformedURLException(MalformedURLException e) {
                            Toast.makeText(getActivity(), "MalformedURLException", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void handleProtocolException(ProtocolException e) {
                            Toast.makeText(getActivity(), "ProtocolException", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
                            Toast.makeText(getActivity(), "UnsupportedEncodingException", Toast.LENGTH_SHORT).show();
                        }
                    });

PHP Code (try 1):
$name = $_POST["image"];

     try {
       echo $name;
     } catch(Exception $e) {
       echo 'Message: ' .$e->getMessage();
     }

PHP Code (try 2):
$name = $_POST["image"];
     echo $name;

If I simple echo "abc" and send any value but the encodedImage, it will show the abc string. So I am sure that db is connecting perfectly.
Please find a solution for me :(
P.S: For the time being. I even set all of the folders permissions on server to 777 so there is not issue of permission I assume.


text:
Q: How to implement wifi chat between android to IOS is it possible chat android to IOS using wifi in same network?
if yes,give sample code available for the same. I previously checked for bluetooth chat but it is not possible so now I look on wifi chat help please.

A: Alljoyn is c++ based library to build up bus connection for two or more devices. You can build up multiplayer game, chat messaging . - https://www.alljoyn.org/
If you would like to make it global ( I mean TCPIP based which i used Node.js is suitable for your project )
You do not get in to deep level. Node.js is here for help developers to build http level socket stream . I builded my own app android and ios with using Node.js client. And server part socket.io library will be handle messaging tail and also with  database driver


text:
Q: If Button text value is 2 then button should be disable mode if (Button1 = '2')
{
    Button1.Enabled = false;
}

this is my code

A: You should check the Text property of the Button and also make sure you are using the equality operator ==. Using just = will try to assign the char value of '2' to a control of Button, which will not work.
And as per the comments: Compare against a string, not a char.
if (Button1.Text == "2")
{
    Button1.Enabled = false;
}


text:
Q: Why does the ul element show when input is clicked? For some reason the ul gets display: none, and is not displayed even when the impute element is clicked.
This is the html
When this is clicked:
 <input class="input country" type="text"/>

This html should show (but it doesn't):

United States

This is the jQuery code:
function handleCountries() {
    $('#country-list').hide();
    $('#country').click(function () {
        $("#country-list").show();
    });
};

function handleTestOut() {
    handleCountries()
};

$(handleTestOut)

This is the html:

            <input class="input country" type="text"/>

United States

            <button>explore</button>

This is some css:
.container {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 200px;
}

.input {
  height: 30px;
  margin-bottom: 50px;
}

ul {
  height: 200px;
  width: 18%;
  overflow: hidden;
  overflow-y: scroll;
  position: absolute;
  background-color: blue;
  top: 20px
}

Here is the full code
Edit: I removed the invalid html, but am getting the same results

A: You hide it with:  $('#country-list').hide();
And what is with this functions calling each other?
You are using jQuery to call handleTestOut function in witch you call handleCountries function. It does not make much sense.
You will get absolutely same result if you just leave it out of functions:
But your main problem was you don't have #country id you have .country CSS class for click calling (or use input.country or .input class, or all of it input.country.input):

$('#country-list').hide();

$('.country').click(function() {
  $("#country-list").show();
});
html {
  height: 100%;
}

body {
  font-family: 'Nunito', sans-serif;
  color: #1b4639;
  background: #cbe2e4;
  height: 100%;
}

.wrapper {
  height: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

p {
  text-align: center;
  margin: 0;
  font-size: 24px;
}

.container {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 200px;
}

.input {
  height: 30px;
  margin-bottom: 50px;
}

ul {
  height: 200px;
  width: 18%;
  overflow: hidden;
  overflow-y: scroll;
  position: absolute;
  background-color: blue;
  top: 20px
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" />
  <link href='http://fonts.googleapis.com/css?family=Nunito:400,300' rel='stylesheet' type='text/css'>
  <title>Document</title>

Hello World!

      <input class="input country" type="text" />

United States

Afghanistan

Åland Islands

Albania

Algeria

American Samoa

Andorra

Angola

Anguilla

Antarctica

Antigua and Barbuda

Argentina

Armenia

Aruba

Australia

Austria

Azerbaijan

Bahamas

Bahrain

Bangladesh

Barbados

Belarus

Belgium

Belize

Benin

Bermuda

Bhutan

Bolivia, Plurinational State of

Bonaire, Sint Eustatius and Saba

Bosnia and Herzegovina

      <button>explore</button>


text:
Q: ASP.NET MVC vs. Webforms vs. HTTP Handlers (.ashx) - which is the most lightweight? I plan on building a simple, yet high usage webapp and need to settle on an architecture.

*

*basic server side logic / dynamic db
driven content about half a dozen to
a dozen pages serving up all said
content

*no need for URL rewriting,

*pretty simple page flow/routing

The objective is to publish this app to use the least amount of bandwidth, memory, and CPU as possible.  That said, my options are to

*

*build in ASP.NET MVC

*build in webforms with viewstate
disabled

*build using .ashx handlers with code
that concatenates all HTML output
into strings that it spits out
Which is the most lightweight solution?
I appreciate the responses so far, but i'm not asking for the best solution.  This is a simple app, and i want the solution that will use the fewest machine/network resources.

A: HttpHandlers are the most lightweight from your list of 3 options.
Personally, I would use ASP.NET MVC because it gives you a richer development environment with very little extra server overhead, especially if u turn most things off ..
eg. roles, etc.
Also use IIS7 intergrated mode and turn as much IIS7 settings off etc.

A: HttpHandlers are the most light weight, because the interface behind the ASHX file is IHttpHandler which is the basis of the Page object that is used both for Web Forms and MVC.

A: Omit the third option because it is very hard to control the application if it is all built using HttpHandlers.

basic server side logic / dynamic db
  driven content about half a dozen to

One of the major benefits of ASP.NET MVC is the ease of the separation of concerns. +1

a dozen pages serving up all said
  content no need for URL rewriting,
  pretty simple page flow/routing

ASP.NET MVC will give you an easy interface to set your routes, a lightweight,clear, and controllable views. +1

A: WebForms are going to be the heaviest in most cases. ASP.Net MVC is quite lightweight and surprisingly fast compared to WebForms.
Building an application using HttpHandlers to serve pages may be fast when serving static content, but if you plan to use some sort of templating to serve dynamic data, you're going to cause yourself a lot of undue work. As for performance, it's hard to say with this option because your templating could be nasty or possibly not.

A: ASP.NET MVC, Web Forms and the Generic Handler (.ashx) are all HttpHandlers implementing the IHttpHandler interface.
Out of these options the Generic Handler (.ashx) would be the most lightweight.

A: ASp.NET MVC is as close as you can get to HtTP and Html.

A: You should use MVC, because you have a lot of more control about the generated client code than in WebForms, and is simpler than ashx handlers.

A: MVC very much gives you more control over HTML produced.  So, from a bandwidth perspective, it definitely has better performance.  With this may also come conciseness of code to generate this HTML.
However, MVC doe not improve business/data layer, or database performance, it just separates them.  If you want to analyze, having multiple layers does not improve performance, just the structure of the program, which in turn may lend itself to methods for adding more performance.
A down side to MVC is learning how to think MVC and learning how to use the framework.  If that is not an issue, go for MVC, it will teach you some good habits, if you don't have them already.
And finally, HTTP Handlers are not really meant for being used in this way, they are for things like file proxies.


text:
Q: scan subnets for ilo ips so i have this script:
$srvILO = '172.16.2.210'
$username='svcilo'
$password='xxxx'

$status_message = get-HPiLoFirmwareversion -Server $srvILO -Username $username -Password $password -DisableCertificateAuthentication -WarningAction SilentlyContinue | Select-Object -ExpandProperty STATUS_MESSAGE

if ($status_message -eq 'OK'){
Write-Host "Status OK"
Exit 0
}
else {
Write-Host "$status_message"
Exit 0
}

I wanne deploy it at several customers that have several subnets and the ilo port is not always on the same ip.
Is there any way that i can scan the subnets to find part of the hostname, which always unclude ILO, and define a variable for the ip adress that is assigned to it?
Something like
$ILO IP = test-connecten ... scan subnets 192.168.0.210, 192.168.1.210, 192.168.2.210 etc... search for hostname that includes dns.

A: You could try something like this to scan all the IP in one range
$username='svcilo'
$password='xxxx'
$ipstart = "1"
$ipend = "255"
$ipgroupes = "172.168.2"
$ipstart..$ipend  | ForEach-Object{
$ip = "$ipgroupes.0" -replace "0$",$_

$DNSName = Resolve-DnsName -Name $ip | Select NameHost

if ($DNSName -like '*ILO*'){

    $status_message = get-HPiLoFirmwareversion -Server $ip -Username $username -Password $password -DisableCertificateAuthentication -WarningAction SilentlyContinue | Select-Object -ExpandProperty STATUS_MESSAGE

    if ($status_message -eq 'OK'){
        Write-Host "Status OK"
        Exit 0
        }

    else {
        Write-Host "$status_message"
        Exit 0
        }

}

}


text:
Q: CodingBat practice question - Python Strings I tried solving this python problem below on CodingBat:
"Given a string (str), return a new string where the first and last characters have been exchanged".
This was my attempt at solving it...which turned out to be incorrect and returned with the error "String index out of range".
def front_back(str):
    return str[-1] + str[1:-1] + str [0]

I would be grateful if someone could point out what I'm missing here and explain.
Thank you.

A: See if the modified function below works for you.
def front_back(str):
    if len(str) == 0:
        return ''
    if len(str) == 1:
        return str
    return str[-1] + str[1:-1] + str [0]

A: Will not work for empty strings, add some smart handling with if ;-) (don't use str as var name)
def front_back(mystr):
    return mystr[-1] + mystr[1:-1] + mystr[0] if mystr else mystr


text:
Q: Failure [INSTALL_FAILED_MISSING_SHARED_LIBRARY] while running Tango project in android studio I just downloaded a sample project (tango) from this link and imported it to android studio and started running the project. But when I run the project in my android phone, it gives an error

Failure [INSTALL_FAILED_MISSING_SHARED_LIBRARY]

I dont know what the issue is with it. Can someone help me?

A: The "missing shared library" is a the tango library that exists only on Tango enabled devices.
You should use the Tango Tablet Development Kit or other Tango enabled device run Tango sample.

A: The problem comes up because for external jars its not required to declare library on manifest... Deleting on manifest the writed on the post solves the problem


text:
Q: Uncrustify command for CUDA kernel I would like to apply uncrustify (via beautify in the Atom editor and a config file) to CUDA code. However, I don't know how to tell uncrustify to recognize CUDA kernel calls which have the following structure:
kernelName <<<N,M>>> (arg0,arg1,...);

However, uncrustify has problems with the <<< >>> and applying it gives the following unpleasant result
kernelName << < N, M >> >
    (arg0,arg1,...);

I would like to have it look more like a function call and also avoid the formatting of <<< to << <. Ideally, the result would look like
kernelName <<< N, M >>> (arg0,arg1,
      ...); // line break if argument list is too long

Which arguments can I add to my config.cfg to achieve the above result?
Thank you very much.

A: Looking through whole documentation of uncrustify, I have found 2 arguments that could influence in your CUDA kernel style:
sp_compare                                { Ignore, Add, Remove, Force     }
 Add or remove space around compare operator '<', '>', '==', etc

And:
align_left_shift                          { False, True }
  Align lines that start with '<<' with previous '<<'. Default=true

You can try to play around with these parameters to be more closely to the solution although I would try something like:
sp_compare     =   Remove
align_left_shift   = False


text:
Q: How can I move columns in small screen on bootstrap? I have 3 columns

 (1)  .col-md-4     |  (2)  .col-md-4    |   (3) .col-md-2  |  (4)  .col-md-2
I want this in small screen (Phone / small screen) as:

 (1)                           |    (4)   |
 (2)                           |    (3)   |

A: First of all, as far as I can tell you have not 3 but FOUR columns.
Secondly, what you want to do is called reordering.
You want to reorder the columns below the md breakpoint.
Here's how you do it:

1

2

3

4

With order-md-* you specify the order for each column from the medium breakpoint onwards.
And with order-* you specify the order you want below the medium breakpoint (i.e. that's the default "mobile-first" breakpoint).


text:
Q: Parse XML from web and add multiple markers on google map api I'd like to get coordinates with parsing XML from the web and add multiple markers on google map. I can get coordinates but the markers don't show. How can I fix my problem? There is no error.
This is one of the XML datas.
<row>
 <COT_ADDR_FULL_NEW>서울특별시 동대문구 홍릉로1길 26</COT_ADDR_FULL_NEW>
 <COT_ADDR_FULL_OLD>서울특별시 동대문구 청량리동 777</COT_ADDR_FULL_OLD>
 <COT_COORD_X>127.043361984</COT_COORD_X>
 <COT_COORD_Y>37.580800789</COT_COORD_Y>
 <COT_CONTS_ID>Sijang_ddm_015</COT_CONTS_ID>
 <COT_CONTS_LAN_TYPE>KOR</COT_CONTS_LAN_TYPE>
 <COT_CONTS_NAME>청량리전통시장</COT_CONTS_NAME>
 <COT_SI_NAME/>
 <COT_GU_NAME>동대문구</COT_GU_NAME>
 <COT_DONG_NAME/>
 <COT_SAN_NAME/>
 <COT_MASTER_NO/>
 <COT_SLAVE_NO/>
 <COT_EXTRA_NAME/>
 <COT_TEL_NO>966-1040</COT_TEL_NO>
</row>

This is my javascript code.

XML parsing works very well. I think saving coordinates or setting position on the map have some problems.

A: Two issues:

*

*Your latitude and longitude are backwards (COT_COORD_X is longitude, COT_COORD_Y is latitude).

{lat: 127.043361984, lng: 37.580800789}

(latitude must be between 90 and -90, center of map is:
 var seoul = {
    lat: 37.558424,
    lng: 127.000509
  };

*There is an ordering issue in your code.  The map is being initialized after the getXML() function is called, so the markers that are created in that function aren't added to the map.

Instead of:
window.onload = function() {
  getXML();

  console.log(seoul);
  var seoul = {
    lat: 37.558424,
    lng: 127.000509
  };
  map = new google.maps.Map(
    document.getElementById('map'), {
      zoom: 11,
      center: seoul
    });
}

Do:
window.onload = function() {
  var seoul = {
    lat: 37.558424,
    lng: 127.000509
  };
  console.log(seoul);
  map = new google.maps.Map(
    document.getElementById('map'), {
      zoom: 11,
      center: seoul
    });
  getXML();
}

proof of concept fiddle

code snippet:

var map;
var marker;
var loc; // for saving coordinates that get from XML

window.onload = function() {
  var seoul = {
    lat: 37.558424,
    lng: 127.000509
  };
  console.log(seoul);
  map = new google.maps.Map(
    document.getElementById('map'), {
      zoom: 11,
      center: seoul
    });
  getXML();
}

// function that sets map markers
function setMarkers() {
  console.log("setMarkers");
  console.log(loc);
  /*for (var i = 0; i < Object.keys(locations).length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(Object.values(locations)),
      map: map
    });
  }*/
  marker = new google.maps.Marker({
    position: loc, // seet map marker position with loc
    map: map
  });
}

function getXML() {
  // alert("getXML 실행");
  var xml = parseXml(xmlData);
  var datas = xml.getElementsByTagName("row");
  var output = "";
  var count = 0;
  for (var i = 0; i < datas.length; i++) {
    if (typeof datas[i].getElementsByTagName("COT_COORD_X")[0].childNodes[0] == undefined ||
      datas[i].getElementsByTagName("COT_COORD_X")[0].childNodes[0] == null) {
      continue;
    } else {
      var lng = Number(datas[i].getElementsByTagName("COT_COORD_X")[0].childNodes[0].nodeValue);
      var lat = Number(datas[i].getElementsByTagName("COT_COORD_Y")[0].childNodes[0].nodeValue)

      console.log(lat + " " + lng);
      loc = {
        lat: lat,
        lng: lng
      };
    } // else
    setMarkers(); // after parse all XML datas, call setMarkers function
  } // for
}

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('MicrosoftXMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');
  }
};
var xmlData = '<rows><row><COT_ADDR_FULL_NEW>서울특별시 동대문구 홍릉로1길 26</COT_ADDR_FULL_NEW><COT_ADDR_FULL_OLD>서울특별시 동대문구 청량리동 777</COT_ADDR_FULL_OLD><COT_COORD_X>127.043361984</COT_COORD_X><COT_COORD_Y>37.580800789</COT_COORD_Y><COT_CONTS_ID>Sijang_ddm_015</COT_CONTS_ID><COT_CONTS_LAN_TYPE>KOR</COT_CONTS_LAN_TYPE><COT_CONTS_NAME>청량리전통시장</COT_CONTS_NAME><COT_SI_NAME/><COT_GU_NAME>동대문구</COT_GU_NAME><COT_DONG_NAME/><COT_SAN_NAME/><COT_MASTER_NO/><COT_SLAVE_NO/><COT_EXTRA_NAME/><COT_TEL_NO>966-1040</COT_TEL_NO></row></rows>;'
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}


text:
Q: Detect image inside circle - HTML5 Canvas Game I'm working on a HTML5 game using a canvas element.

I'm drawing a circle like this (the user can move this circle around):
ctx.arc(chomperX,chomperY,chomperRadius,0,Math.PI*2);

I'm placing bomb images on in the canvas like this:
ctx.drawImage(bombImg,bombX,bombY,15,15);

The objective is for the user to move the "chomper" circle over the bomb image and eat it.  My questions is, how can I detect that the bomb is INSIDE the circle? I'm trying to do this by calculating the distance from the circle to the bomb image, but I'm getting mixed results.  Here's how I'm getting the distance.
bx = bombX - chomperX;
by = bombY - chomperY;
bombDistance = Math.floor(Math.sqrt(bx * bx + by * by))
if (bombDistance < bombRadius + chomperRadius) { console.log("THE BOMB IS IN THE CIRCLE!"); }

A: Assuming the bombRadius is less than chomperRadius,
bx = bombX - chomperX;
by = bombY - chomperY;
bombDistance = Math.sqrt(bx * bx + by * by);
if (bombDistance < chomperRadius - bombRadius) { console.log("THE BOMB IS IN THE CIRCLE!"); }


text:
Q: how to change the color key height in heatmap.2 I am trying to reduce the size of the heatmap.2 color key
it is now like this

key=T,  # add the key color
key.title =NA,
cexRow = 0.75,
cexCol=0.75,

I want to reduce the higth of it and become like this

This is how I plot my heatmap
heatmap.2(mat_data,
          key=T,  # add the key color
          key.xlab="label",
          key.title =NA,
          cexRow = 0.75,
          cexCol=0.75,
          #lhei = c(5,5),
          #cellnote = mat_data,  # will display the values
          main = "title to be shonwn ", # heat map title
          #notecol=NA,          # change font color of cell labels to black
          density.info="none",  # turns off density plot inside color legend
          trace="none",         # turns off trace lines inside the heat map
          margins =c(15,20),     # widens margins around plot
          col=myPalette,       # use on color palette defined earlier
          breaks=col_breaks,    # enable color transition at specified limits
          dendrogram="row",     # only draw a row dendrogram
          Colv="NA",
          notecex=1.0)

I found that
keysize=1
can change the size by you don't have any power to adjust the size as you want

A: This can be set with the lhei parameter in heatmap.2()
heatmap.2(data,lhei = c(1,7))

The parameter is a vector of length two, and appears to be the relative height of the key and the heatmap.


text:
Q: Hide Status bar with if statement? I have a QR code reader in my app.  Once the reader scans a code, it takes the app to a survey page.  I'm trying to get the survey page to hide the statusbar.  Here is my code:
- (void)zxingController:(ZXingWidgetController*)controller didScanResult:(NSString *)result {

   // self.resultsToDisplay = result;
    if (self.isViewLoaded) {

        [[NSBundle mainBundle] loadNibNamed:@"yellaViewController" owner:self options:nil];
        initWithNibName:@"yellaViewController" bundle:[NSBundle mainBundle]];

        [topImage setImage:[UIImage imageNamed:@"yellalogoREAL.png"]];

        [[UIApplication sharedApplication] setStatusBarHidden:YES];

    }

This isn't working for me, and the statusbar stays visible.  What am I doing wrong?
ALSO: Is there a way I can hide the tabbarcontroller on the surveypage using the same if statement?

A: In ZxingController's viewDidAppear:  (ZxingWidgetController.m)
self.isStatusBarHidden = [[UIApplication sharedApplication] isStatusBarHidden];
if (!isStatusBarHidden)
    [[UIApplication sharedApplication] setStatusBarHidden:YES];

it cached the previous statusbar state, and when you exit the ZxingController, in viewDidDisappear:
if (!isStatusBarHidden)
    [[UIApplication sharedApplication] setStatusBarHidden:NO];

Since the viewDidDisappear in ZxingController will enter after zxingController:didScanResult:
So your setStatusBarHidden in zxingController:didScanResult: is no use.


text:
Q: What does Error: TCP connection reset by peer - PHP/CURL/HTTPS issues I am stuck here:
I get this Error: TCP connection reset by peer.
This is my CURL Script
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_webpay);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_TIMEOUT, 60);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POST, false );
Without the comments, I get the error message.
Just leaving those options readable in the code above displays the page without the error but does not give me access to the $header.
I have done this:
curl_setopt($ch, CURLOPT_CAINFO, "/abc/ssl/certs/abc.crt");
I get a different error.
Can someone guide me on what am missing? I am using php 5.4.16 on CentOS 7.
I want to get all the CURL options working, cos I need to get feedback from the headers.


text:
Q: What type of function argument declaration does this C function has? I'm Working on FFTW (Fastest Fourier Transform in the West) and came over this C function. I did not understand the declaration of this function where parameters are present inside ()(). I never saw a declaration as such. Can anyone brief it out?
void X(execute_dft_r2c)(const X(plan) p, R *in, C *out)
    {
      /*
       *Body
       */
    }

A: X is a macro that adds a precision-naming prefix depending on compilation parameters.
I believe the point (at least one of them) is to avoid mismatches by causing errors if source files have been compiled with different precision settings.
(C does not have type-safe linkage.)
Look in fftw3/kernel/ifftw.h:
/* determine precision and name-mangling scheme */
#define CONCAT(prefix, name) prefix ## name
#if defined(FFTW_SINGLE)
  typedef float R;
# define X(name) CONCAT(fftwf_, name)
#elif defined(FFTW_LDOUBLE)
  typedef long double R;
# define X(name) CONCAT(fftwl_, name)
# define TRIGREAL_IS_LONG_DOUBLE
#elif defined(FFTW_QUAD)
  typedef __float128 R;
# define X(name) CONCAT(fftwq_, name)
# define TRIGREAL_IS_QUAD
#else
  typedef double R;
# define X(name) CONCAT(fftw_, name)
#endif

In the first case, your declaration expands to
void fftwf_execute_dft_r2c(const fftwf_plan p, R *in, C *out)


text:
Q: How do I view and share a running Angular app through Vagrant? I have a basic Angular app installed using a Yeoman fullstack installer, and I can see the basic pages running on http://localhost:9000 when I run 'grunt serve'.
I also have a Vagrant installation running using the ubuntu/trusty64 box. I was originally seeing a 404 when trying to view http://127.0.0.1:4567/, but following some instructions I found online, I edited the file in 'vagrant ssh' at /etc/apache2/sites-enabled/000-default.conf by removing the html part of the path in that file. After doing 'vagrant reload' I now see the list of files in my project dir when I go to that URL.
How do I go about viewing my angular app like it is at localhost:9000? If I get this working will this mean that if I share via Vagrant, they'll see the angular app running as it should? Do I still need to be running grunt serve in combination with Vagrant?
I'm pretty new to all this setup, so I'm just following the instructions at https://github.com/DaftMonk/generator-angular-fullstack & https://docs.vagrantup.com/v2/getting-started/index.html
I'm not great with Linux/cmd line stuff as yet, hence my problems... :)
Thanks!

A: I started writing instructions for you on how to get it done. But then realised that you are not very comfortable with linux commands. I have created a angular-seed project that uses vagrant, angular and requirejs. Its easy to set up and I have written instructions on how to do that in my github page.
Just clone it, follow the instruction and you will have a working seed project in no time. Some of the features of the seed are:
Uses vagrant and puppet to provision the vm. All required dependencies are automatically installed.
Grunt tasks for:

*

*autoloading bower dependencies

*compile sass or scss

*livereload

*server for access of site locally

If you have any difficulties or questions, feel free to contact me.


text:
Q: In how many ways 10 objects can be colored? (combinatorics) On a table there are 10 different objects that can be colored using 5 different colors
a) How many ways can the 10 objects be colored? $10 \choose 5$
b) How many ways can the 10 objects be colored using all different colors? $5! \cdot 5!$ because I have to order 5 colors in 10 places, but when 5 places are "colored" I have 5 more place to color.
c) How many ways can the 10 objects be colored in such a way that each color is used at most 3 times? any idea?
Are my first two solutions right? what's about the third question? maybe $ 10 \choose 5 $ - $10  \choose 2$?

A: Those are not correct answers. Your solution before the edit was considering identical objects and used stars and bars. The edited solution does not answer either. The question says different objects. So for the first question, please note there are $5$ color choices for each object and hence the answer should simply be $ \ \displaystyle 5^{10}$ ways.
The second question seeks that all colors must be used (In contrast, in the first question, it is possible that all objects get colored using only one color as an example). So one approach is to use Principle of Inclusion Exclusion.
The answer to the second question should be,
$\displaystyle 5^{10} - {5 \choose 1} \cdot 4^{10} + {5 \choose 2} \cdot 3^{10} - {5 \choose 3} \cdot 2^{10} + {5 \choose 4}$
Alternatively use Stirling Number of the second kind (wiki) which gives you number of ways to arrange $10$ different objects in $5$ identical heaps. We then multiply by $5!$ to assign $5$ different colors to those heaps.
$\displaystyle 5! \cdot {10 \brace 5}$
Here is a hint for the third: Think if each color is used at most $3$ times, how many minimum colors must be used to color all $10$ objects and how many cases do you get? That is one approach.

A: Your first two solutions are wrong.  There are $5$ choices for the color of each of $10$ objects, so the number of choices in all, by the multiplication rules is $5^{10}$.
For the second problem, you can use the principle of inclusion and exclusion.  There are $5^{10}$ ways to color the objects.  We want to subtract the colorings that use only four colors.  There are $\binom54=5$ ways to choose the $4$ colors so this gives $$5^{10}-5\cdot4^{10}$$ ways.  But what about colorings that use only $3$ colors?  We've subtracted them twice at the previous step, once for each possible fourth color, so now we have to add them back in. We have $$5^{10}-5\cdot4^{10}+\binom53\cdot3^{10}$$  You still need to figure out the adjustments that need to be made for colorings that use only $2$ colors or $1$ color.
For the third one, the easiest way that occurs to me is first to figure out all the ways that you can choose no more than $5$ positive integers no larger than $3$ that add up to $10$.  One example is $3,3,2,1,1$.  There are $\binom52$ ways to choose the color that are use $3$ times, and then $3$ ways to choose the color used twice, and the remaining colors are each used once.  Then there are $$\binom{10}{3,3,2,1,1}$$ ways to use the paint the houses with these colors so $$\binom52\binom31\binom{10}{3,3,2,1,1}$$ for this color pattern.  Do this for all the patterns (there aren't many) and add them up.


text:
Q: Twitter og:image card not displaying for first time Integrate twitter og cards on my site. While sharing on twitter everything works fine except image which is not loading for first time. After that it works fine but for first time image is displaying .
Is that an issue or its work like that? If issue then how can I fix that?

A: I've had this problem too. It seems to me that this is what's happening:
When Twitter or the validator inspects your URL, it calls a backend function to create the thumbnail image and store it in Twitter's CDN.
But the JS code you are running in your browser times out on that call after 2 or 3 seconds.
So, if for whatever reason (image size, processing, transfer time, protocol negotiation, etc), it takes the Twitter function more than that to retrieve the image from your site, produce a thumbnail and store it, the JS code in the browser is not listening anymore.
The function keeps running, and eventually finishes. And that's why the subsequent attempts all work, because the thumbnail is already in Twitter's CDN.
So, the solution is to make the site deliver those images as fast as possible. Big files naturally will take longer to transfer and process so you should look into that as well.


text:
Q: How can i change the orientation to landscape mode? I am new to iOS. I developed one application, in my View i have lot of objects are there. When i am changing the iPad to landscape mode, all objects positions are changing. I mean all objects height and width and positions are also changed so i am getting problem with it. Now, should i change every object resolution or is there any direct methods to solve this problem. Please send me the code. Thanks in advance.

A: You need to implement below:-
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
CGRect bounds = [[UIScreen mainScreen] bounds]; // portrait bounds
if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
    bounds.size = CGSizeMake(bounds.size.height, bounds.size.width);
}
        return YES
    }

A: If you want to support multiple orientations then you can specify the layout(s) using the old "springs and struts" system or you can use Autolayout. For the beginning with iOS7, take a look at this tutorial.


text:
Q: Difference between anything but and anything other than? If I say "anything but ordinary", it means it is not ordinary, it is unique and different.
What if "anything other than ordinary"? Does it mean the same as "anything but ordinary" or does it simplify emphasize the state of being ordinary?


text:
Q: How to Read a SortedList from a File? I have a SortedList, the key is Contact.name and the value, is an object, Contact. I´m writing this list to a file, with BinaryWriter and I don´t have any trouble but now I want to read this list, and after, look for an specific contact. I don´t know how to do it. I think that I must read the file and after that look for the contact, but how can I fill the SortedList with the binary code saved in the file?

A: Sounds like you want BinaryReader which will take the File output from BinaryWriter and deserialize into your original type.
This is a good example of using both on msdn

A: Here's a quick example on how to do, both, read and write from a binary file.
static void Main(string[] args)
    {

        WriteContacts(new List<Contact>( new []{ new Contact { ID = 1, Name = "Juan", Age = 34 }, new Contact { Name = "Pedro", Age = 23, ID = 2 } }));
        FindContactInFile("Juan");
        FindContactInFile("Mario");
        Console.ReadKey();
    }

    private static void FindContactInFile(string name)
    {
        IFormatter formatter = new BinaryFormatter();

        using (Stream s = new FileStream("contacts.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var contacts = (List<Contact>)formatter.Deserialize(s);
            var person  = contacts.Where(x=>x.Name==name).FirstOrDefault();
            if (person != null)
                Console.WriteLine("Persona encontrada: {0}", person.Name);
            else
                Console.WriteLine("{0} no fue encontrado en el archivo.", name);
        }
    }

    private static void WriteContacts(List<Contact> contacts)
    {
        IFormatter formatter = new BinaryFormatter();
        using (Stream s = new FileStream("contacts.bin", FileMode.Create, FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(s, contacts);
        }
    }
}
[Serializable]
class Contact
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

Many things can be improved there, like not reading the entire file every time you search for someone. Or not reading the entire file at once to begin with... In any case, the key concept here is that in order to store something in a binary file you need to serialize the object. For this you can use one of the BinaryFormatters provided by .NET (as I did above) and to read back from the file, you simply do the opposite.


text:
Q: How to attach the Konvajs Transformer to multiple shapes without groupping them? I'm working on a Konvajs based designer tool project where u'll be able to select multiple shapes with MouseClick+CntrlKey.
The idea is that once the first shape is selected, the Transformer is created an attached to it. If u're holding CntrlKey and click over other shapes the Transformer will be updated (with forceUpdate()) to include those too.
Thanks to this tutorial I've managed to attach the Transformer to a newly created temporary group where all shapes are being added one by one when they get selected. As soon as u clear the selection, the shapes are removed from that group.
The problem with adding shapes to a temporary group is that u cannot keep the shapes original z-index during the time they still in that group, so they all are moved to the top. That's why I'm trying to find a way to attach the Transformer to multiple shapes directly without adding them into a group.
Any help will be appreciated! Thanks in advance!

A: From konva@5.0.0 it is possible to attach several nodes:
const tr = new Konva.Transformer();
layer.add(tr);

tr.nodes([shape1, shape2]);
layer.draw();

https://konvajs.org/docs/select_and_transform/Basic_demo.html


text:
Q: Single vs multi-page angular application in ASP.NET Core I'm an angular beginner and am currently working through a few angular tutorials. I have some ASP.NET MVC experience from a few years back.
What I think I am trying to understand is whether I should be attempting to design my application as a SINGLE or MULTI page application.
As far as I understand, there are two main schools of thought, when it comes to Angular and ASP.NET CORE applications:

*

*Create a simple ASP.NET CORE application serving a single page. That page will be a single-page angular application, which will take care of its own routing, etc, presenting a variety of different views and potentially using an API exposed through ASP.NET for data

*Create a multi-page ASP.NET CORE application, serving a number of different pages, each of which will be a razor page, with some part of it being an angular application

Am I understanding this right? I think the single-page application makes sense to me, but I do find that I am quite confused on multi-page approach... I am not quite clear on which part of multi-page application is angular supposed to fill and whether every single page should be its own angular application.
I have tried searching for a comparison of the two, but was unable to find anything decent. :(

A: In Multi-Page Applications, the client (browser) which typically sends a request for page to the server to initiates the communication. Then the server processes the request and sends the HTML of the page to the client (browser). For every request server sends the full html to the client, not to load patch html to the client.
In Single-Page Applications (SPAs) at first the entire page is loaded in the client by the initial request, after that the subsequent action has to update by Ajax request and no need to reload the entire page. The SPA reduces the time by to respond to user actions and result is more fluid experience.

A: I don't think the classification you use is correct.
To me it is:

*

*Traditional "multi page" application: HTML generated on server (ie MVC and Razor) and pushed to the browser at every request.

*Single page applications (SPA): HTML downloaded a single time from the server and manipulated on client via Javascript (ie Angular).

Probably you are talking about "multiple" "single page applications" where you break a complex SPA into smaller ones.
Ie you could have a "user" SPA and an "admin" SPA published from the same website.

A: If you want to build single page application(ajax based) in Asp.net Core MVC solution without using any third party JavaScript framework then better you have to look this github repository.
https://github.com/KishorNaik/Sol_Ajax_Spa_MVC_Core


text:
Q: PLS-00103 compilation error when creating table within a procedure I am writing some PL/SQL code which create table for database.
When I try to trace the code I keep getting error PLS-00103. I have looked at other threads and it suggests there is a missing a begin of loop but I cannot see where that might be.
SET SERVEROUTPUT
EXECUTE THELLO;
 CREATE OR REPLACE PROCEDURE THELLO AS
    WELCOME VARCHAR(50);
BEGIN
    CREATE TABLE NEW_PART(
P_PARTKEY   NUMBER(12)  NOT NULL,
P_NAME      VARCHAR(55) NOT NULL,
P_MFGR      VARCHAR(25) NOT NULL,
P_BRAND     CHAR(10)    NOT NULL,
P_TYPE      VARCHAR(25) NOT NULL,
P_SIZE      NUMBER(12)  NOT NULL,
P_CONTAINER     CHAR(10)    NOT NULL,
P_RETAILPRICE   NUMBER(12,2)    NOT NULL,
P_COMMENT   VARCHAR(23) NOT NULL,
    CONSTRAINT NEW_PART_PEKEY PRIMARY KEY (P_PARTKEY),
    CONSTRAINT NEW_PART_CHECK1 CHECK(P_PARTKEY >= 0),
    CONSTRAINT NEW_PART_CHECK2 CHECK(P_SIZE >= 0),
    CONSTRAINT NEW_PART_CHECK3 CHECK(P_RETAILPRICE >= 0) );

CREATE TABLE NEW_SUPPLIER(
S_SUPPKEY   NUMBER(12)  NOT NULL,
S_NAME      CHAR(25)    NOT NULL,
S_ADDRESS   VARCHAR(40) NOT NULL,
S_NATIONKEY NUMBER(12)  NOT NULL,
S_PHONE     CHAR(15)    NOT NULL,
S_ACCTBAL   NUMBER(12,2)    NOT NULL,
S_COMMENT   VARCHAR(101)    NOT NULL,
    CONSTRAINT NEW_SUPPLIER_PKEY PRIMARY KEY (S_SUPPKEY),
    CONSTRAINT NEW_SUPPLIER_FKEY1 FOREIGN KEY (S_NATIONKEY)
        REFERENCES NATION(N_NATIONKEY),
    CONSTRAINT NEW_SUPPLIER_CHECK1 CHECK(S_SUPPKEY >= 0) );

CREATE TABLE NEW_PARTSUPP(
PS_PARTKEY  NUMBER(12)  NOT NULL,
PS_SUPPKEY  NUMBER(12)  NOT NULL,
PS_AVAILQTY NUMBER(12)  NOT NULL,
PS_SUPPLYCOST   NUMBER(12,2)    NOT NULL,
PS_COMMENT  VARCHAR(199)    NOT NULL,
    CONSTRAINT NEW_PARTSUPP_PKEY PRIMARY KEY (PS_PARTKEY, PS_SUPPKEY),
    CONSTRAINT NEW_PARTSUPP_FKEY1 FOREIGN KEY (PS_PARTKEY)
        REFERENCES NEW_PART(P_PARTKEY),
    CONSTRAINT NEW_PARTSUPP_FKEY2 FOREIGN KEY (PS_SUPPKEY)
        REFERENCES NEW_SUPPLIER(S_SUPPKEY),
    CONSTRAINT NEW_PARTSUPP_CHECK1 CHECK(PS_PARTKEY >= 0),
    CONSTRAINT NEW_PARTSUPP_CHECK2 CHECK(PS_AVAILQTY >= 0),
    CONSTRAINT NEW_PARTSUPP_CHECK3 CHECK(PS_SUPPLYCOST >= 0) );

DECLARE

BEGIN

  FOR PARTKEY IN (SELECT DISTINCT PS_PARTKEY FROM PARTSUPP)
  LOOP
    INSERT INTO NEW_PART ( SELECT *
                           FROM PART
                           WHERE P_PARTKEY = PARTKEY.PS_PARTKEY );
    COMMIT;
  END LOOP;

  FOR SUPPKEY IN (SELECT DISTINCT PS_SUPPKEY FROM PARTSUPP)
  LOOP
    INSERT INTO NEW_SUPPLIER ( SELECT *
                               FROM SUPPLIER
                               WHERE S_SUPPKEY = SUPPKEY.PS_SUPPKEY );
    COMMIT;
  END LOOP;

  INSERT INTO NEW_PARTSUPP ( SELECT *
                             FROM PARTSUPP
                 WHERE PS_PARTKEY IN ( SELECT P_PARTKEY
                                                   FROM NEW_PART ) AND
                                   PS_SUPPKEY IN ( SELECT S_SUPPKEY
                                                   FROM NEW_SUPPLIER ) );
  COMMIT;
END THELLO;
/
show errors
prompt Done.

PROBLEM:

PLS-00103: Encountered the symbol "CREATE" when expecting one of the following: ( begin case declare end exception exit for goto if loop mod null pragma raise return select update while with    << continue close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe purge json_exists json_value json_query json_object json_array

A: As I did comment, table creation can not be the part of the procedure unless it is used in EXECUTE IMMEDIATE.
Create table separately before creating procedure.
CREATE TABLE NEW_PART(
P_PARTKEY   NUMBER(12)  NOT NULL,
P_NAME      VARCHAR(55) NOT NULL,
P_MFGR      VARCHAR(25) NOT NULL,
P_BRAND     CHAR(10)    NOT NULL,
P_TYPE      VARCHAR(25) NOT NULL,
P_SIZE      NUMBER(12)  NOT NULL,
P_CONTAINER     CHAR(10)    NOT NULL,
P_RETAILPRICE   NUMBER(12,2)    NOT NULL,
P_COMMENT   VARCHAR(23) NOT NULL,
    CONSTRAINT NEW_PART_PEKEY PRIMARY KEY (P_PARTKEY),
    CONSTRAINT NEW_PART_CHECK1 CHECK(P_PARTKEY >= 0),
    CONSTRAINT NEW_PART_CHECK2 CHECK(P_SIZE >= 0),
    CONSTRAINT NEW_PART_CHECK3 CHECK(P_RETAILPRICE >= 0) );

CREATE TABLE NEW_SUPPLIER(
S_SUPPKEY   NUMBER(12)  NOT NULL,
S_NAME      CHAR(25)    NOT NULL,
S_ADDRESS   VARCHAR(40) NOT NULL,
S_NATIONKEY NUMBER(12)  NOT NULL,
S_PHONE     CHAR(15)    NOT NULL,
S_ACCTBAL   NUMBER(12,2)    NOT NULL,
S_COMMENT   VARCHAR(101)    NOT NULL,
    CONSTRAINT NEW_SUPPLIER_PKEY PRIMARY KEY (S_SUPPKEY),
    CONSTRAINT NEW_SUPPLIER_FKEY1 FOREIGN KEY (S_NATIONKEY)
        REFERENCES NATION(N_NATIONKEY),
    CONSTRAINT NEW_SUPPLIER_CHECK1 CHECK(S_SUPPKEY >= 0) );

CREATE TABLE NEW_PARTSUPP(
PS_PARTKEY  NUMBER(12)  NOT NULL,
PS_SUPPKEY  NUMBER(12)  NOT NULL,
PS_AVAILQTY NUMBER(12)  NOT NULL,
PS_SUPPLYCOST   NUMBER(12,2)    NOT NULL,
PS_COMMENT  VARCHAR(199)    NOT NULL,
    CONSTRAINT NEW_PARTSUPP_PKEY PRIMARY KEY (PS_PARTKEY, PS_SUPPKEY),
    CONSTRAINT NEW_PARTSUPP_FKEY1 FOREIGN KEY (PS_PARTKEY)
        REFERENCES NEW_PART(P_PARTKEY),
    CONSTRAINT NEW_PARTSUPP_FKEY2 FOREIGN KEY (PS_SUPPKEY)
        REFERENCES NEW_SUPPLIER(S_SUPPKEY),
    CONSTRAINT NEW_PARTSUPP_CHECK1 CHECK(PS_PARTKEY >= 0),
    CONSTRAINT NEW_PARTSUPP_CHECK2 CHECK(PS_AVAILQTY >= 0),
    CONSTRAINT NEW_PARTSUPP_CHECK3 CHECK(PS_SUPPLYCOST >= 0) );

Now, your procedure code.
CREATE OR REPLACE PROCEDURE THELLO AS
    WELCOME VARCHAR(50);
BEGIN

  FOR PARTKEY IN (SELECT DISTINCT PS_PARTKEY FROM PARTSUPP)
  LOOP
    INSERT INTO NEW_PART ( SELECT *
                           FROM PART
                           WHERE P_PARTKEY = PARTKEY.PS_PARTKEY );
    COMMIT;
  END LOOP;

  FOR SUPPKEY IN (SELECT DISTINCT PS_SUPPKEY FROM PARTSUPP)
  LOOP
    INSERT INTO NEW_SUPPLIER ( SELECT *
                               FROM SUPPLIER
                               WHERE S_SUPPKEY = SUPPKEY.PS_SUPPKEY );
    COMMIT;
  END LOOP;

  INSERT INTO NEW_PARTSUPP ( SELECT *
                             FROM PARTSUPP
                 WHERE PS_PARTKEY IN ( SELECT P_PARTKEY
                                                   FROM NEW_PART ) AND
                                   PS_SUPPKEY IN ( SELECT S_SUPPKEY
                                                   FROM NEW_SUPPLIER ) );
  COMMIT;
END THELLO;
/


text:
Q: Google Apps Script: read text from a .txt file After taking a look at the provided tutorial for sending emails from a spreadsheet with Google Apps Script, I modified the given code with aims to be able to send the set of emails out with attachments as well.
It works well enough, even with a couple quirks from the limitations of Google Apps Script (the files have to be in the Google Drive, and all files in the Google Drive with whichever name is appropriate are taken from all folders in the drive).
function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 1;   // Number of rows to process
  // Fetch the range of cells A2:C3
  var dataRange = sheet.getRange(startRow, 1, numRows, 3)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var attachment = row[2];    // File name provided.
    var subject = "Mass Email";
    var files = DriveApp.getFilesByName(attachment); // Get all files with name.
    var blobs = []; // Array for attachment.
    // Move files into blobs
    while (files.hasNext()) {
      var file = files.next();
      blobs.push(file.getAs(MimeType.PLAIN_TEXT));
    }
    MailApp.sendEmail(emailAddress, subject, message, {
      attachments: blobs, // add attachments
      cc: "extra@email.com" // CC to employer
    });
  }
}

After I first used it, however, I learned that I need to send the files not as attachments, but as the message body of the emails, among some other changes (this is for work). That is, I will only ever email one 'attachment' at a time to each email, and instead of that file being an attachment, its content should be copied over to the message of the email. The attachments are currently text files, and I'd like them to stay that way, but it isn't the most vital thing.
I cannot determine a way to do this with Google Apps Script. Is this possible, or will I have to have a different way of emailing these files? (Hopefully not by hand.)

A: as mentioned in my last comment, converting your .txt files to Google documents makes it easy to achieve.
see below (suggestion)
function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 1;   // Number of rows to process
  // Fetch the range of cells A2:C3
  var dataRange = sheet.getRange(startRow, 1, numRows, 3)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (i in data) {
    var row = data[i];
    Logger.log(row)
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var attachment = row[2];    // File name provided.
    var subject = "Mass Email";
    var files = DriveApp.getFilesByName(attachment); // Get all files with name.
    while (files.hasNext()) {
      var file = files.next();
      var Id = file.getId();
      var content = DocumentApp.openById(Id).getBody().getText();
      Logger.log(content)
    MailApp.sendEmail(emailAddress, subject, message+'\n'+content)
    }
  }
}

A: Try this. It's more faster and simpler.
var docContent = file.getBlob().getDataAsString();
Logger.log(docContent);


text:
Q: Error with TwilioRestClient in Python 2.7 I recently installed Twilio module and I am using Python 2.7
Credentials.py -->
account_sid = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"

auth_token = "978XXXXXXXXXXXXXXXXXXXXXX"

my_phone = "+XXXXXXXXXXXX"

my_twilio = "+XXXXXXXXXXXX"

message.py ----->
from twilio.rest import TwilioRestClient

from credentials import account_sid, auth_token, my_phone, my_twilio

client = TwilioRestClient(account_sid, auth_token)

message = 'Hello Sarthak, How are you?'

final_message = client.messages.create(to=my_phone, from_=my_twilio,
body=message)

When I try to run this, I am getting this error :-

A: From twilio.rest import Client

TwilioRestClient is deprecated. You have to import Client instead. Make sure you are using Python 3 too.


text:
Q: how to configure translator locale based on User entity without session In symfony you are supposed to set the Requests locale before an internal event listener configures the TranslatorInterface.

The custom listener must be called before LocaleListener, which initializes the locale based on the current request. To do so, set your listener priority to a higher value than LocaleListener priority (which you can obtain by running the debug:event kernel.request command).

https://symfony.com/doc/current/translation/locale.html
My problem is that I have to access the users locale but the listeners run on kernel.request event which is executed before the firewall (ie user is not logged in at this moment).
How am I supposed to configure the translator based on users locale stored in database?
I have tried the solution from this thread (Locale based on the user's Preferences) but its not working.
Currently as a workaround I have to manually pass the locale argument to all TranslatorInterface::trans calls.


text:
Q: Linux - Is there a way to convert .bz2 files to .tar.bz2 files using pipes? Is there a way to convert a .bz2 file to a .tar.bz2 file without decompressing the entire thing to disk and then re-compressing?  The decompressed size is larger than my drive.  Since bz2 operates on blocks, it would seem like you could just decompress a block, pipe it, re-compress it, remove the decompressed block from memory, etc.
I asked this on Ubuntu Forums and didn't find an answer.

A: Update: My original answer doesn't work at all, sorry.  tar won't accept a data stream from STDIN as input, so the first command fails.
The only way I can think of to accomplish what you want is to write your own program to add the required tar headers and such around your data stream.  Then you could write:
$ bzcat foo.bz2 | stream-to-tar | bzip - > foo.tar.bz2

... and (assuming your program gets the tar format right) you could decompress it with a standard tar xf foo.tar.bz2.

This probably isn't how you want to do it, since it doesn't provide any of the usual advantages of tar'ing the file in the first place.
$ bzcat foo.bz2 | tar cjf foo.tar.bz2 -

Now, the problem is that tar doesn't include any filesystem in it cause all we've given it is a decompressed data stream.  That means you need to decompress/untar it like this:
$ tar --to-stdout -xjf foo.tar.bz2 > foo

A: I think you'll find that the answer is:  You don't do this.  The compression gained from a .tbz2 file vs. a .bz2 file is pretty minimal if you compressed it with --best.  Here is an example over an httpd error log:
 39M ./httpd-error.log
904K ./httpd-error.log.bz2
904K ./httpd-error.log.tbz2

Otherwise, you'll have to do it with a stop by the hard drive.


text:
Q: 2 errors compiling clang and llvm with Visual C++ 2015 Community There are 2 errors:
1.) C2039 in project clangCodeGen in file BackendUtil.cpp on line 574, "MCIncrementalLinkerCompatible" is not a member of "llvm::MCTargetOptions".
2.) C2660 in project clang in file cc1as_main.cpp on line 404, cannot use 9 arguments for the function "llvm::Target::createMCObjectStreamer".

A: It seems your version of clang is not compatible with your version of LLVM.
The IncrementalLinkerCompatible flag causing your problem was only added to LLVM four days ago (http://permalink.gmane.org/gmane.comp.compilers.llvm.cvs/292184).
So I think you must have downloaded the current version of it rather than 3.7.0.


text:
Q: When using an Ansible playbook, how do you store and use a password containing quotes or other metacharacters without them being interpereted? My company uses Ansible (which I am a novice at) and we have a playbook and a related role for joining new Linux machines to AD.  Our admin accounts have their passwords rolled three times a day, and we can't set them ourselves.  The Ansible playbook works so long as there is not a ' (single quote) in the password.  There may be other characters that cause it to break, but I know that ' does it for sure.
Here are the relevant bits of the scripts:
cat setup-ad.yml

---
- hosts: "{{ hosts }}"

  vars_prompt:
  - name: "username"
    prompt: "Enter admin account"
    private: no

  - name: "password"
    prompt: "Enter Password"
    unsafe: yes
    private: yes

  vars:
    domain: "{{ 'mycompany.com' }}"
    passwd: "{{ password | regex_escape() }}"

  roles:
  - join-ad

grep -B2 -A3 'passwd' ./roles/join-ad/tasks/main.yml

  - name: join to active directory
    command: net ads join MYCOMPANY.COM -U {{ username }}@MYCOMPANY.COM%'{{ passwd }}' createcomputer=Restricted/Servers/Unix --request-timeout=120 --no-dns-updates
    no_log: false
    when: ansible_distribution_major_version >= 6

  - name: join to active directory
    command: net ads join MYCOMPANY.COM -U {{ username }}@MYCOMPANY.COM%'{{ passwd }}' createcomputer=Restricted/Servers/Unix --request-timeout=120
    no_log: false
    when: ansible_distribution_major_version <= 5

The error we get is:
TASK [join-ad : join to active directory] ************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ValueError: No closing quotation
fatal: [newserver.mycompany.com]: FAILED! => {"changed": false, "module_stderr": "Shared connection to newserver.mycompany.com closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n  File \"/root/.ansible/tmp/ansible-tmp-1590785720.2-224244797633747/AnsiballZ_command.py\", line 102, in <module>\r\n    _ansiballz_main()\r\n  File \"/root/.ansible/tmp/ansible-tmp-1590785720.2-224244797633747/AnsiballZ_command.py\", line 94, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/root/.ansible/tmp/ansible-tmp-1590785720.2-224244797633747/AnsiballZ_command.py\", line 40, in invoke_module\r\n    runpy.run_module(mod_name='ansible.modules.commands.command', init_globals=None, run_name='__main__', alter_sys=True)\r\n  File \"/usr/lib64/python2.7/runpy.py\", line 176, in run_module\r\n    fname, loader, pkg_name)\r\n  File \"/usr/lib64/python2.7/runpy.py\", line 82, in _run_module_code\r\n    mod_name, mod_fname, mod_loader, pkg_name)\r\n  File \"/usr/lib64/python2.7/runpy.py\", line 72, in _run_code\r\n    exec code in run_globals\r\n  File \"/tmp/ansible_command_payload_4D4oFT/ansible_command_payload.zip/ansible/modules/commands/command.py\", line 344, in <module>\r\n  File \"/tmp/ansible_command_payload_4D4oFT/ansible_command_payload.zip/ansible/modules/commands/command.py\", line 263, in main\r\n  File \"/usr/lib64/python2.7/shlex.py\", line 279, in split\r\n    return list(lex)\r\n  File \"/usr/lib64/python2.7/shlex.py\", line 269, in next\r\n    token = self.get_token()\r\n  File \"/usr/lib64/python2.7/shlex.py\", line 96, in get_token\r\n    raw = self.read_token()\r\n  File \"/usr/lib64/python2.7/shlex.py\", line 172, in read_token\r\n    raise ValueError, \"No closing quotation\"\r\nValueError: No closing quotation\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

PLAY RECAP *******************************************************************************************************
newserver.mycompany.com : ok=9    changed=0    unreachable=0    failed=1    skipped=2    rescued=0    ignored=0

Okay, so the issue is that at some point the ' is being interpreted as the beginning of a quoted series of characters, rather than as simply part of the password.  My problem is I don't know how to get Ansible? Python? YAML? Jinja? to treat the string of characters the user inputs as nothing more than a string of characters.  Is "string literal" the correct term here?
If I ssh to the target server and run the net ads join command manually, and let it prompt for my password, it will work even with a ' in it, so at the very least I know it's not the Samba command that's the issue.
The things I've tried (which haven't helped) are:

*

*Add 'hard quotes' around {{ passwd }}

*Add unsafe: yes to the password definition

*Add passwd: "{{ password | regex_escape() }}" to escape metacharacters

*Lots of internet searching on Stack and Google

Any and all help would be appreciated.

A: This  might be what you're looking for
- command: "net ads join MYCOMPANY.COM
            -U {{ username }}@MYCOMPANY.COM%{{ passwd|quote }}
            createcomputer=Restricted/Servers/Unix --request-timeout=120"

See YAML gotcha and String filters.


text:
Q: Equivalent of `shift` from pandas Initial DataFrame in Pandas
Let's suppose we have the following in Python with pandas:
import pandas as pd

df = pd.DataFrame({
    "Col1": [10, 20, 15, 30, 45],
    "Col2": [13, 23, 18, 33, 48],
    "Col3": [17, 27, 22, 37, 52] },
    index=pd.date_range("2020-01-01", "2020-01-05"))

df

Here's what we get in Jupyter:

Shifting columns
Now let's shift Col1 by 2 and store it in Col4.
We'll also store df['Col1'] / df['Col1'].shift(2) in Col5:
df_2 = df.copy(deep=True)

df_2['Col4'] = df['Col1'].shift(2)

df_2['Col5'] = df['Col1'] / df['Col1'].shift(2)

df_2

The result:

C# version
Now let's setup a similar DataFrame in C#:
#r "nuget:Microsoft.Data.Analysis"

using Microsoft.Data.Analysis;
var df = new DataFrame(
    new PrimitiveDataFrameColumn<DateTime>("DateTime",
        Enumerable.Range(0, 5).Select(i => new DateTime(2020, 1, 1).Add(new TimeSpan(i, 0, 0, 0)))),
    new PrimitiveDataFrameColumn<int>("Col1", new []{ 10, 20, 15, 30, 45 }),
    new PrimitiveDataFrameColumn<int>("Col2", new []{ 13, 23, 18, 33, 48 }),
    new PrimitiveDataFrameColumn<int>("Col3", new []{ 17, 27, 22, 37, 52 })
);

df

The result in .NET Interactive:

Question
What's a good way to perform the equivalent column shifts as demonstrated in the Pandas version?
Notes
The above example is from the documentation for pandas.DataFrame.shift:
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html
Update
It does indeed look like there isn't currently a built-in shift in Microsoft.Data.Analysis. I've posted an issue for this here:
https://github.com/dotnet/machinelearning/issues/6008

A: Helper functions
Perform a column shift.
PrimitiveDataFrameColumn<double> ShiftIntColumn(PrimitiveDataFrameColumn<int> col, int n, string name)
{
    return
        new PrimitiveDataFrameColumn<double>(
            name,
            Enumerable.Repeat((double?) null, n)
                .Concat(col.Select(item => (double?) item))
                .Take(col.Count()));
}

Carry out division, taking care of null values in divisor.
PrimitiveDataFrameColumn<double> DivAlt3(PrimitiveDataFrameColumn<int> a, PrimitiveDataFrameColumn<double> b, string name)
{
    return
        new PrimitiveDataFrameColumn<double>(name, a.Zip(b, (x, y) => y == null ? null : x / y));
}

Then the following:
var df = new DataFrame(
    new PrimitiveDataFrameColumn<DateTime>("DateTime",
        Enumerable.Range(0, 5).Select(i =>
            new DateTime(2020, 1, 1).Add(new TimeSpan(i, 0, 0, 0)))),
    new PrimitiveDataFrameColumn<int>("Col1", new []{ 10, 20, 15, 30, 45 }),
    new PrimitiveDataFrameColumn<int>("Col2", new []{ 13, 23, 18, 33, 48 }),
    new PrimitiveDataFrameColumn<int>("Col3", new []{ 17, 27, 22, 37, 52 })
);

df.Columns.Add(ShiftIntColumn((PrimitiveDataFrameColumn<int>)df["Col1"], 2, "Col4"));

df.Columns.Add(DivAlt3((PrimitiveDataFrameColumn<int>) df["Col1"], (PrimitiveDataFrameColumn<double>) df["Col4"], "Col5"));

results in:

Complete notebook
See the following notebook for a full demonstration of the above:
https://github.com/dharmatech/dataframe-shift-example-cs/blob/003/dataframe-shift-example-cs.ipynb
Notes

*

*It would be great if Microsoft.Data.Analysis came with column shift functionality.

*It would also be great if column division handled nulls natively.

Would love to see other perhaps more idiomatic approaches to this.


text:
Q: Shrapoint 2013 does not have border underneath Library name In SP 2010 when I had a library in a page the library name displayed a nice soft blue line/border underneath the library name..
When I have the same library in SP 2103 only the Library name displays.
Any suggestions..note for SP2010 its all oob

A: The UI for 2013 was changed in many places.
You can add your own CSS style overruling SharePoints style definition
<style>
 .pageTitle{
   border-bottom:blue;
 }
</style>

Several places you can add your own stylesheet

*

*Site Settings -> Masterpage (if Publishing Features are enabled)

*Editting the MasterPage with SP Designer add a link to your own stylesheet

*Site- Settings > Design Manager Create a whole new Design

*Inside a CEWP but that will only get you the styles on the one page

*Using a Browser Plugin (Chrome) Stylish this changes anything in the page you want, but only in your browser


text:
Q: Sending an error from server to client - fullstack js I am currently working on a first MERN fullstack (using mongoose).
I am trying to cover all possible errors, including server side errors, and notifying the client. For example: I am trying to run the app while my local MongoDB server is not running, to find that specific error, and catch it.
So of course there is an error, but it seems like the .catch after the EventNote.find (EventNote is the mongoose model) doesn't catch it, and certainly does not send it back to the client (ideally a modal will pop up).
Any help will be appreciated!
Note: The app and the route- they all work exactly as expected, so a req does reach the route, and normally does send back the expected data.

router.get("/get_events_by_month/:month", (req, res) => {
  const { month: query } = req.params;

  EventNote.find({ month: query })
    .then(data => {
      res.status(201).send(data);
    })
    .catch(err => {
      console.log(err);
      res.status(500).send(err);
    });
});

A: OK. Since that specific error I was trying to create, it occurs on the mongoose.connect and not while trying to access a route...


text:
Q: SQL order by two column, omit if second column doesn't meet the order Let's say we have next data
id |    date    | price
------------------------
1  | 10-09-2016 |   200
2  | 11-09-2016 |   190
3  | 12-09-2016 |   210
4  | 13-09-2016 |   220
5  | 14-09-2016 |   200
6  | 15-09-2016 |   200
7  | 16-09-2016 |   230
8  | 17-09-2016 |   240

and we have to order by date first, and price second, however if the price must be in order. If current price is less than previous we should omit this row, and the result will be:
id |    date    | price
------------------------
1  | 10-09-2016 |   200
3  | 12-09-2016 |   210
4  | 13-09-2016 |   220
7  | 16-09-2016 |   230
8  | 17-09-2016 |   240

Is it possible without join?

A: Use LAG window function
SELECT *
FROM   (SELECT *,
               Lag(price)OVER( ORDER BY date) AS prev_price
        FROM   Yourtable) a
WHERE  price > prev_price
        OR prev_price IS NULL -- to get the first record

A: If "previous" is supposed to mean the previous row in the output, then keep track of a running maximum. Postgres solution with a window function in a subquery:
SELECT id, date, price
FROM  (
   SELECT *, price >= max(price) OVER (ORDER BY date, price) AS ok
   FROM   tbl
   ) sub
WHERE  ok;

A: If Postgres:
select id, date, price
from
(select
    t.*,
    price - lag(price, 1, price) over (order by id) diff
from
    your_table) t
where diff > 0;

If MySQL:
select id, date, price from
(
    select t.*,
        price - @lastprice diff,
        @lastprice := price
    from
    (select *
    from your_table
    order by id) t
    cross join (select @lastprice := 0) t2
) t where t.diff > 0;


text:
Q: Discord Text channel creation I'm not sure about the code to create a text channel
I want it to be a command like create and then it would create 3 channels at the same time and then a message saying success.
I'm just not sure on the code to create a text channel and implement it so that when I do create it would make 3 pre-registered channels. Where I don't have to say create channel 1, channel 2, and so on. Just say create and it will create 3 channels that I have put the names from the code. Also, this is discord.py

A: Add this into the command:
for name in channel_names:
    await ctx.guild.create_text_channel(name)


text:
Q: How can I define default options for xorg graphics devices I have a laptop and an external USB graphics card. I have a xorg.conf.d snippet like this:
Section "Device"
  Identifier  "USB3"
  Driver      "modesetting"
  Option      "kmsdev" "/dev/dri/card1"
  Option       "PageFlip" "off"
EndSection

That works fine but only if the USB adapter is plugged in and recognized before the X server starts. X will detect the adapter when I hotplug it, but it will not apply the option "PageFlip" "off". I have found documentation on how to configure input device options using udev, because obviously hotplugging input devices is more common than hotplugging graphics output devices.
Is there a way to configure a X Device that is hotplugged, either through udev or any kind of xorg.conf.d snippet?

A: Seems like it was proposed some time ago but not accepted. The preferred solution to implement a VideoClass directive similar to InputClass has apparently never been done.


text:
Q: Using Android In-App Billing classes for multiple apps, in a shared library project I'm using the Google Play billing API (Version 3) for all my applications which use a shared library project (also created by me) and I have a question regarding the setup for the helper classes classes (in package .inappbilling.util) and the IInAppBillingService.aidl file (that generates IInAppBillingService.java class):
Is it ok (good practice) to store those files in my shared library and then use them in all my apps or do I have to create a copy in every project for those applications (in the case that the files generated by android plugin are somehow dependent on the project )?

A: Store common files in a shared library.


text:
Q: Retrieving data from API using Axios Async Await and Typescript. Array shows length: 1? I have been fighting this for days now and can't seem to find a solution that works.  I just keep going from one error to another.  Currently, I am getting a single entry in my table with no data being populated, just a blank line. Could someone please help me figure out why my table in not populating.
This solution worked perfectly in my sandbox application, but once I put it in the actual project it started failing.  I suspect that is it because the actual project uses Typescript,  and so far Typescript had jacked up almost every enhancement I have tried to add to this app.
My console.log(res.data) is returning:

[{…}]
   0: {results: (23) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
        totalResultCount: 23
        [[Prototype]]: Object
     length: 1
     lastIndex: (...)
     lastItem: (...)
     [[Prototype]]: Array(0)

My console.log("res.data", JSON.stringify(res.data, null, 2)) is returning:
res.data {
  "results": [
    {
      "modelIdInfo": {
        "modelKey": "85",
        "version": 0
      },
      "name": "Name1",
      "versionInfo": {
        "version": 0,
        "versionOn": "2023-02-20T17:53:46.0092161-06:00",
        "versionBy": "UNKNOWN"
      },
      "isArchived": false
    },
    {
      "modelIdInfo": {
        "modelKey": "11",
        "version": 0
      },
      "name": "Name2",
      "versionInfo": {
        "version": 0,
        "versionOn": "2023-02-20T17:53:46.0092161-06:00",
        "versionBy": "UNKNOWN"
      },
      "isArchived": false
    },
    {
      "modelIdInfo": {
        "modelKey": "110",
        "version": 0
      },
      "name": "Name3",
      "versionInfo": {
        "version": 0,
        "versionOn": "2023-02-20T17:53:46.0092161-06:00",
        "versionBy": "UNKNOWN"
      },
      "isArchived": false
    },

-- for all 23 results--

As you can see from the console I am getting an array of data with 23 entries, but it is saying a length of 1.  I just can't seem to get it to populate the table with the Array.
My only guess is that the length of 1 is what is causing the single line on the table rather than 23 lines as I would have expected.
I tried using "setTableData([res.data[0].results]);" as recommended, but but kept getting no results.
If I use "setTableData([res.data.results[0]]);" it is now populating the table, but only with the first result (Name1).
If I remove the [] surrounding the 'res.data.results[0]' or 'res.data' as I originally had, I get a "e.map is not a function" error and a blank screen.
Here is my API call:
const [tableData, setTableData] = React.useState([]);
const [loading, setLoading] = React.useState(true);

React.useEffect(() => {
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await axios.get(baseURL);
      // setTableData([res.data]);
      setTableData([res.data.results[0]]);
      console.log( res.data );
      console.log("res.data", JSON.stringify(res.data, null, 2))
      console.log( tableData);
    } catch (error) {
      console.error(error.message);
    }
    setLoading(false);
 };

 fetchData();
}, [baseURL, setTableData, setLoading]);

My Table
{loading ?
  <LoadingData />
  :
  (dataLength === 0 ?
    <NoResults />
    :
    tableData.map((item, id) => (
      <TableRow key={item.index} >
        <TableCell>
          {item.name}
        </TableCell>
      </TableRow>
    ))
  )
}


text:
Q: Issue with `` within .replace() tags How can I edit my current code to work with `` within replace.
As of current because it's inside a loop .each it will find the correct word but then add  around that word like 6 times. I want it to only add it once, so I read you can use /g for that, however using `` I think is causing my issue, however I don't know how to incorporate both?
Here is my JS:
$("#pstad-descrptn-mirror div").each(function () {
   let get_pstad_desc_div = $(this).text();
   let get_pstad_desc_STORE = get_pstad_desc_div
       .split(", and comes with")[0]
       .split("located in ")[1];

   $(this).html(function () {
      return $(this)
        .html()
        .replace(
           `/(${get_pstad_desc_STORE})/g`,
           `<span>${get_pstad_desc_STORE}</span>`
        );
   });
})

I'm open to a javascript or jquery solution.
Many thanks

A: I'm guessing that your HTML looks something like this...

        Take-away located in Brisbane, and comes with free chips

The problem with your current query is that it finds all the
 elements that are children of the ID'd container.
You can use the child combinator selector operator to only retrieve the immediate
 children and operate on their content.
You can also use a regular expression to more easily extract your store string.
document.querySelectorAll("#pstad-descrptn-mirror > div").forEach((el) => {
  const store = el.textContent.match(/located in (.+?), and comes with/)?.[1];
  el.innerHTML = el.innerHTML.replaceAll(store, `<span>${store}</span>`);
});

document.querySelectorAll("#pstad-descrptn-mirror > div").forEach((el) => {
  const store = el.textContent.match(/located in (.+?), and comes with/)?.[1];
  el.innerHTML = el.innerHTML.replaceAll(store, `<span>${store}</span>`);
});
#pstad-descrptn-mirror span {
  font-weight: bold;
}

Take-away located in Brisbane, and comes with free chips.

Located in Brisbane, QLD

No matches in this div, nothing will be replaced


text:
Q: Defining "templated class" functions outside of a class I have this class
template <class T> class dynamic_array
  {

and this function:
void dynamic_array::randorder()
  {
  srand(time(NULL));
  int *ap;
  for(ap=array;k!=array+size;++k){*k=rand();}
  }

The compiler is complaining about my function  - "not having template parameters".  How do I add this in?

A: template <class T>
void dynamic_array<T>::randorder()
{
  srand(time(NULL));
  for(int *ap = array; k != array + size; ++k)
  {
    *k = rand();
  }
}

A: It should be
template <class T>
void dynamic_array<T>::randorder()
  {
...
  }

Also, keep in mind that you have to put the definition into a header file if you need to use it in different .cpp files.
I suppose array must be a data member of type T, so the following doesn't apply here.  But in general if you see that some member functions of a class template do not depend on the template parameters, it makes sense to factor them out into a non-template base class.  It reduces the size of the executable and makes your life easier.


text:
Q: I Changed The Name Of The Folder My Project Was In And Now Xcode Cannot Find My Project I am using xcode 4. I simply changed the name of the physical folder all the files for my project are now when I click on the project file and open it in xcode ITS GONE! xcode is not letting me launch the project now. Please help!

A: Go to the folder, click on the project file. If the files are red or not there, add them back. That should be enough. Otherwise, if there is any error message, post it. Changing a project folder name is not enough to screw up a project, so I guess you did something else.


text:
Q: Push Notification in .Net core 2.1 MVC with Azure MySQL as database I am creating my website application in .net core 2.1. I have to deploy it in WebApp of Azure. Backend DB is Azure MySQL service.
Can i create SignalR with MySQL and show notification in my .net core MVC application?


text:
Q: Show that a certain length is maximized when lines are parallel Consider two fixed circles whose interiors are not disjoint with centers $A$ and $B$. Let a line $\ell$ be drawn perpendicular to line $AB$, which intersects both circles at $X$ and $Y$ respectively. The question is how to place $\ell$ to to maximize the length of $XY$. (Note that line $\ell$ intersects each circle twice; since we want to maximize $XY$ we choose $X$ and $Y$ so that they are on opposite sides of $AB$).
My conjecture is that we should place $\ell$ so that $AX$ and $BY$ are parallel but I am unsure of how to prove this.
Ideally I would have a geometric proof because the original statement is geometrical, and often, these optimization problems have a nice way of looking at them that makes it obvious where the maximal case occurs.

A: I would really just compute it analytically, and say the derivative is equal to $0$. I use $BY=b$, $AX=a$, $DB=x$. Then you get $YD=\sqrt{b^2-x^2}$. $DA=a-b-x$, so $DX=\sqrt{a^2-(a-b-x)^2}$. $$XY=\sqrt{b^2-x^2}+\sqrt{a^2-(a-b-x)^2}$$
$$\frac{d\, XY}{d\,x}=\frac{-x}{\sqrt{b^2-x^2}}+\frac{a-b-x}{\sqrt{a^2-(a-b-x)^2}}=0$$
You can rewrite this last equation as
$$\frac{DB}{YD}=\frac{AD}{XD}$$
This implies that the triangles $BDY$ and $ADX$ are similar, and therefore $YB||AX$.


text:
Q: How to stop babel from prefixing "_" for methodnames containing same name as javascript keywords I am transforming a class from es6 to es5 using babel transpiler.
This is the sample class.
class TestClass{
 switch(){
 }
 getState(){

 }
}

This gets transformed as
 var TestClass = function () {
  function TestClass() {
    _classCallCheck(this, TestClass);
     }

    _createClass(TestClass, [{
       key: "switch",
       value: function _switch() {}
    }, {
       key: "getState",
       value: function getState() {}
    }]);

    return TestClass;
 }();

If you notice here, switch method is automatically prefixed with "_" by babel. How to avoid this?
Here is the babel transformation demo

A: You didn't test it first. There is nothing wrong with Babel. The _switch() is naught but an internal unexposed method that Babel creates during transpile (something you shouldn't really care about). Your accessible method is still called .switch() as all things should be.
class TestClass{
 switch(){
   return "foo"
 }
 getState(){

 }
}

console.log(new TestClass().switch()) //foo
console.log(new TestClass()._switch()) //undefined

"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var TestClass = function () {
  function TestClass() {
    _classCallCheck(this, TestClass);
  }

  _createClass(TestClass, [{
    key: "switch",
    value: function _switch() {
      return "foo";
    }
  }, {
    key: "getState",
    value: function getState() {}
  }]);

  return TestClass;
}();

console.log(new TestClass().switch())


text:
Q: msysgit: Prevent the Git bash from locking files of running shell scripts I have some scripts that are (always) running during development. Trying to write to these files in Windows 7 fails (git pull fails with Permission denied error). Everything works fine in Linux.

*

*Can I prevent Git bash from locking the files without changing my global UAC settings?

*What other alternatives do I have (besides fixing/hacking the Git bash or Windows)?

Here is an example script as basis for the discussion:
#!/bin/bash
echo "command + args: $0 $1 $2 $3"
while sleep 2; do date +%s; done

I found a somehow related topic. But unfortunately it did not provide a suitable solution, e.g., Run as Administrator does not help.
Another interesting observation is that I can still write the files when editing them in vim using :w! (forcing an overwrite).

A: You could simply run a copy of the file.
cp foo.sh /usr/local/bin
foo.sh

This would allow you to edit the file in the repo while the other is running. You could also try a hard link.
ln foo.sh /usr/local/bin
foo.sh


text:
Q: I am receiving 'null' when entering specific dates in my output My code compiles and runs perfectly, but when I any dates that are Saturdays the output is 'null' instead of 'SATURDAY'. Examples will be provided below to further explain this problem.
I have tried to change my if statement on my "getDayOfWeek" method but I seem to have no solution, I have also tried to obtain help from an experienced coder but they seem to be struggling due to java not being their main language...
The code:
class MyDate {

    // properties of date object
    private int day, month, year;

    // constructor with arguments
    public MyDate(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public boolean isDateValid() {
        if (month > 12 || month < 1 || day < 1) { // if values exceed 12 or are negative: return false
            return false;
        } else if (year <= 1582 && month <= 10 && day <= 15) { //     starting date
            //   checking
            return false;
        } // for 31 day months: January, March, May, July, August, October, December
        else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {

            if (day > 31) {
                return false;
            }

        } // for 30 day months: April, June, September, November
        else if (month == 4 || month == 6 || month == 9 || month == 11) {

            if (day > 30) {
                return false;
            }

        } // February check
        else if (month == 2) {

            // leap year check for February
            // 29 days in a leap year
            // 28 days in a common year
            if (isLeapYear()) {
                if (day > 29) {
                    return false;
                }

            } else {
                if (day > 28) {
                    return false;
                }
            }
        }
        return true;
    }

    // checks if input year is leap year
    private boolean isLeapYear() {
        if (year % 4 != 0) {
            return false;
        } else if (year % 400 == 0) {
            return true;
        } else if (year % 100 == 0) {
            return false;
        } else {
            return true;
        }
    }

    // method returns the day of MyDate object
    public int getDay() {
        return day;
    }

    // parameter for day to set
    public void setDay(int day) {
        this.day = day;
    }

    // method returns the month of MyDate object
    public int getMonth() {
        return month;
    }

    // parameter for month
    public void setMonth(int month) {
        this.month = month;
    }

    // method returns the year of MyDate object
    public int getYear() {
        return year;
    }

    // parameter for year
    public void setYear(int year) {
        this.year = year;
    }

    // method returns all variables: day/month/year of MyDate object
    public String toString() {
        return day + "/" + month + "/" + year;
    }
}

public class MyCalendar {

    //enums for days of week
    public static enum Day {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,  SATURDAY;
    };

    //enums for month of year
    public static enum Month {
        JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
    };

    //enums for week number of month
    public static enum Week {
        FIRST, SECOND, THIRD, FOURTH, FIFTH;
    };

    //to store Date object
    private MyDate date;

    //constructor taking mydate object
    public MyCalendar(MyDate enteredDate) {
        this.date = enteredDate;
    }

    //main method
    public static void main(String[] args) {

        boolean dateValid = false; //valid date false
        Scanner input = new Scanner(System.in); //scanner for input
        MyDate enteredDate = null;

        //till valid date found
        while (!dateValid) {
            System.out.print("Enter the date as day month year : ");
            //taking input and creating date output
            enteredDate = new MyDate(input.nextInt(), input.nextInt(), input.nextInt());
            //validating date input

            if (enteredDate.isDateValid()) { //if valid
                MyCalendar myCalendar = new MyCalendar(enteredDate);
                //creating calendar table

                myCalendar.printDateInfo(); //printing date info
                myCalendar.printCalendar(); //printing calendar
                dateValid = true; //setting validate to true
            } else {
                System.out.println(enteredDate + " is not a valid date, please re-input a valid date: ");
            }
        }

        input.close();
    }

    // returns number of days in current month
    private int getNumberOfDays() {
        int days = 31;
        int month = date.getMonth();
        if (month == 4 || month == 6 || month == 9 || month == 11)
            days = 30;
        return days;
    }

    //print calendar of input month
    public void printCalendar() {
        System.out.println("\n\nThe Calendar of "+Month.values()[date.getMonth()-1]+" "+date.getYear()+" is :");
        int numberOfMonthDays = getNumberOfDays();
        Day firstWeekdayOfMonth = getDayOfWeek(1, date.getMonth(), date.getYear());
        int weekdayIndex = 0;
        System.out.println("Su Mo Tu We Th Fr Sa");
        // The order of days depends on the input of date
        // to display output of calendar

        for (int day = 0; Day.values()[day] != firstWeekdayOfMonth; day++) {
            System.out.print("   "); // this loop to print the first day in the
            // correct place
            weekdayIndex++;
        }
        for (int day = 1; day <= numberOfMonthDays; day++) {

            if (day < 10)
                System.out.print(day + " ");
            else
                System.out.print(day);
            weekdayIndex++;
            if (weekdayIndex == 7) {
                weekdayIndex = 0;
                System.out.println();
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }

    //method to print about date information in literal form
    public void printDateInfo() {
        System.out.println(date + " is a " + getDayOfWeek(date.getDay(), date.getMonth(), date.getYear())
        + " located in the " + Week.values()[getWeekOfMonth() - 1] + " week of "
        + Month.values()[date.getMonth() - 1] + " " + date.getYear());
    }

    /*
     * gets day of the week, returns enum type Day
     *
     * Zellar's congruence to calculate the day of week
     * for any given date after October 15 1582
     * (h) = (q+(13*(m+1)/5)+K+(K/4)+(J/4)+5J)%7 ,q- day of month,
     * m- month, k = year of century (year%100), J = (year/100)
     */
    public Day getDayOfWeek(int day, int month, int year) {
        int q = day;
        int m = month;

        if (m < 3) {
            m = 12 + date.getMonth();
            year = year - 1;
        }
        int K = year % 100;
        int J = year / 100;
        //calculating h value
        int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;
        Day output = null;
        if (h < Day.values().length && h > 0) {
            output = Day.values()[h - 1]; //getting respective  enum value
        }
        return output; //returning enum value
    }

    // get week number of current date
    public int getWeekOfMonth() {
        int days = date.getDay();
        int weeks = days / 7;
        days = days % 7;
        if (days > 0)
            weeks++;
        return weeks;
    }

}

Expected results:
java MyCalendar 29/02/2019
29/02/2019 in not a valid date, please re-input a valid date:         25/05/2019
25/05/2019 is a Saturday and located in the fourth week of May 2019
The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
            1   2   3   4
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

Actual results:
25/05/2019 is a null located in the FOURTH week of MAY 2019

The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
            1   2   3   4
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

Results of another date (that is not a Saturday):
24/05/2019 is a FRIDAY located in the FOURTH week of MAY 2019

The calendar of May 2019 is:
SUN MON TUE WED THU FRI SAT
            1   2   3   4
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

Specified problem:
The output prints null on all dates that are on the day of Saturday, whereas other dates that are not a Saturday will achieve the correct output needed.

A: if (h < Day.values().length && h > 0) {

should change to
if (h < (Day.values().length + 1) && h > 0) {

A: *

*If this is for production code, the comment by Basil Bourque is correct: you should not develop your own MyDate class but rely on the built in LocalDate class.

*If on the other hand, as I would assume, this is a programming exercise, it's a fine one, and there's no reason (that I can see) why you shouldn't struggle your way through it.

Your formula for calculating the day of the week is:
    //calculating h value
    int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7;

(As an aside, please find better variable names and also respect the Java naming convention: a variable name cannot be an uppercase letter.) I don't understand the formula, but assuming that it is correct, it calculates the day of week as 0 = Saturday, 1 = Sunday up to 6 = Friday. To use this number as a lookup into your Day enum use
        output = Day.values()[(h + 6) % 7]; //getting respective  enum value

Since h will always be non-negative and less than 7, you don't need the enclosing if statement. Just assign to output unconditionally. With these changes I get

Enter the date as day month year : 25 5 2019
25/5/2019 is a SATURDAY located in the FOURTH week of MAY 2019

The Calendar of MAY 2019 is :
Su Mo Tu We Th Fr Sa
         1  2  3  4
5  6  7  8  9  10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31


text:
Q: Change cursor to pointer on ion-input Is there a way to apply cursor: pointer; to an ion-input element? It seems like no matter what I do, it's showing the default i-beam cursor.
My input:
<ion-input [readonly]="true" [placeholder]="getPlaceholder() | translate"></ion-input>

CSS I've tried:
ion-input {
  input {
    cursor: pointer;
  }
}

ion-input {
  cursor: pointer;
}

ion-input::part(input) {
  cursor: pointer;
}

And I've tried the !important tag on all of these.

A: Here is a working stackblitz which shows the solution.
In order to solve this type of problem:

*

*Right click on the ion input element.

*Observe that your element is on the shadow dom.

*Further observe that what you are really interested in is the native input which has a class of native-input.

*Add the following CSS to correctly pierce the shadowDom.

::ng-deep ion-input .native-input {
  cursor: pointer;
}

Using ::ng-deep will pierce the dom, and the rest takes care of the correct selection for style application.


text:
Q: ADT list of integers to test program Is there anywhere I can find an ADT list of integers I can use to test this program I wrote for an assignment question? Or can someone tell me how to make one or provide one for me, it would be greatly appreciated!
 /**
  * Finds the Max integer from the ADT list of integers
  *
  * @author (Siren P)
  * @version (03/12/2016)
  */
  public class MaxIntegers
  {
    public int maxInt (ListReferenceBased aList)
    {
    //Declare variable for max integer
    int max;

    //Checks every integer in list
    for(int i = 0 ; i <= aList.size(); i++)
    {
        if(i == 0)
        {
            //first element stored as max
            max = aList.get(i);
        }
        else
        {
            if(aList.get(i) > max)
            {
                //if element is bigger than current stored element then it will be overwritten
                max = aList.get(i);
            }
        }
    }
    //Returns the max integer
    return max;
}

}

A: You can use an ArrayList:
java.util.List<Integer> aList = new java.util.ArrayList<Integer>();

// add some ints to the list
aList.add(1);
aList.add(2);
aList.add(3);
aList.add(4);

A: We need the code for the ListReferenceBase class to construct a list. My guess would be that it is a sort of LinkedList, but I don't know the functions the class offers.
Probably something like that would work (put that in your MaxIntegers class)
public static void main(String[] args) {
    MaxIntegers test = new MaxIntegers();
    ListReferenceBased testlist = new ListReferenceBased();
    testlist.add(5);
    testlist.add(2);
    testlist.add(55);
    System.out.println(maxInt(testlist));
}

Besides that a few side notes:

*

*You should declare the method maxInt as static. This means you don't need an object to invoke the method (in this case there is no reason why you would need one, that's why you should make it static.)

*Your code likely won't work. If (and this is very likely) ListReferenceBased starts the index at 0, then the condition of your for loop (i <= list.size()) will go too far. The correct way would be i < list.size().

If there is no implementation of ListReferenceBased and it is just a placeholder, you can swap that out in your class and my example with 'LinkedList' for instance. It also would be possible to write List<Integer> instead, which would you allow to pass all kinds of lists to the method, they just have to implement the java.util.List interface.