text:
Q: How to match or capture a specific substring-pattern from a given string via regex? How can I cut password from message via regular expression?
And how I can use it in function, because code duplication is not a good idea ?
Now I'm doing it via slice like this:
  message.html.body.slice(14,24));

message output:
  html: MessageContent {
    links: [],
    images: [ [Image] ],
    body: 'Your password 5gIlrjtxDy'
  },

I'm trying to do it like this :
const [_, retailerPassword] = retailerMessage.html.body.trim().match(/Your\s+password\s+(\w+)/);
  console.log(retailerPassword);

const [_, recipentPassword] = recipentMessage.html.body.trim().match(/Your\s+password\s+(\w+)/);
  console.log(recipentPassword);

But after that I have problem with redeclaring block-scoped variable '_'.
And I tried to do it in function :
const extractPassword(text:string):string => {
const [_, password] = `

Your password QfzW4zbHg4

`.trim().match(/Your\s+password\s+(\w+)/);
return password
}

A: The OP's main problem comes from following combination ...

*

*Using the same destructuring assignment pattern twice via const and therefore colliding with the 2nd _-assignment.

*The usage of _ is due to using the password capturing group which is the 2nd entry of the match method's result array; thus being forced to somehow contain the 1st entry, which is the regex match, by assigning it to the never to be used _-variable.
This easily can be fixed by not using destructuring assignments at all. One simply writes ...
const retailerPassword = retailerMessage
  .html.body.trim().match(/Your\s+password\s+(\w+)/)[1];

const recipentPassword = recipentMessage
  .html.body.trim().match(/Your\s+password\s+(\w+)/)[1];

Note
A more generic and/or language agnostic approach like ... /(?<=\s)\w+(?=<img)/ or even simpler /\S+(?=<img)/ ... could try to ...

*

*match anything which is not a whitespace (for passwords where whitespace is not allowed)

*until the next match will be the character sequence '<img' ...

const retailerMessage = {
  html: {
    links: [],
    images: [ [Image] ],
    body: 'Your password 5gIlrjtxDy',
  }
};

const retailerPassword = retailerMessage
  // // [https://regex101.com/r/jwAf0r/2]
  // .html.body.trim().match(/(?<=\s)\w+(?=<img)/);
  // [https://regex101.com/r/jwAf0r/1]
  .html.body.trim().match(/\S+(?=<img)/)[0];

console.log({ retailerPassword });
.as-console-wrapper { min-height: 100%!important; top: 0; }

Edit
... since the OP did ask for it ...

function getPasswordFromMessage(message) {

  // // [https://regex101.com/r/jwAf0r/2]
  // .html.body.trim().match(/(?<=\s)\w+(?=<img)/);

  // [https://regex101.com/r/jwAf0r/1]
  return message?.html?.body?.trim()?.match(/\S+(?=<img)/)?.[0] ?? null;
}

const retailerMessage = {
  html: {
    links: [],
    images: [],
    body: 'Your password 5gIlrjtxDy',
  }
};
const recipientMessage = {
  html: {
    links: [],
    images: [],
    body: 'Your password FooBarBIZ',
  }
};

const retailerPassword = getPasswordFromMessage(retailerMessage);
const recipientPassword = getPasswordFromMessage(recipientMessage);
const failedGetPassword = getPasswordFromMessage({});

console.log({
  retailerPassword,
  recipientPassword,
  failedGetPassword,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: You could use the string replace method for that.
Also, the block-scoped variable redeclaration problem might be because you're altering the message object; If so, copying the string should solve the issue.
Like so:
const retailerStr = retailerMessage.html.body;
const pass = retailerStr.replace(/Your\s+password\s+(\w+)(.*)/,'$1');
// pass === "5gIlrjtxDy"


text:
Q: Can a flashed Mac Pro 2009 (5,1) support macOS Mojave Can macOS Mojave be installed on a Mac Pro 2009 that has been flashed/upgraded to the 5,1 firmware (Mine already is) with a Metal supported GPU like a AMD RX 580?

A: Yes, got Mojave on my 2009 5,1 flashed with the High Sierra update this morning using the 6/18 Mojave download.
The Apple store wouldn't let me download Mojave directly to my 2009, had to download on another machine (a 10.13 Fusion VM) then create a bootable USB, boot my 2009 from the USB and install from there.

A: Yes, per the specifications macOS Mojave runs on a Mac Pro 2010 with a Metal-capable GPU. The software is unaware that your machine is really a 2009, as it only checks the board ID which matches a 5,1 machine. Currently running Beta 5 on my 2009, with an AMD Radeon R9 270X flashed with EFI firmware. Be sure to remove any other GPUs from the machine. I first had an issue then remembered I had my original GT 120 installed. I was required to update my EFI firmware, and it successfully updated to MP51.0089.B00. The firmware update may require a GPU with EFI firmware (gray boot screen.)

A: just nervously updated from High Sierra to Mojave on my Mac Pro early 2009  (4,1 flashed to 5,1. - dosdude patch for High Sierra ages ago - then the Mojave boot installer/patcher usb drive method by dosdude just last night..)
it did feel a bit like an impulsive move from what i'd read about compatible systems, i was expecting maybe a complete death of the factory fitted gpu as its not Metal (still using the original nvidia GeForce GT120!), was ready to buy an new gpu.
so theres hope out there, not experienced any major gpu issues other than a lack of transparent dock and a few other minor things, but still does dark mode.
TBH just relieved it actually booted. however i'm ready to go for a new rx560 if needed....
good luck out there anyone searching for answers.

A: Interestingly,  My Mac Pro 4,1 flashed to a 5,1 had no problem downloading the Beta for Mojave (7/27/18), but will not do the firmware update.
It's not clear to me hw it's failing as my video card is a modern nVidia that doesn't show the great screen at POST.
I think I will try to replace it with the original card and see if I get any more info that way...
Much later I add...  using the original card (Radeon 5870) I was able to install the firmware update and then swap in a modern video card.
My nVidia 1060 card still isn't usable, as there aren't web drivers for Mojave yet,  my RX 580 works but doesn't provide audio over HDMI, which was flawless in High Sierra.

A: My early 2009 4.1 flashed to 5.1 installed the firmware update and installed fine. I hadn't read about Metal GPU requirements, and my GTX 970 didn't work (grey bars at top of safari, etc.)
I switched it for a gtx 680 but it's very flaky. I'm trying to edit video in Final Cut, Premiere and DaVinci Resolve, all of which crash regularly and quite spectacularly.
Going to try an RX 580 next...

A: I've to say that installing directly Mojave was not working perfectly for me on my 2009 4.1 flashed to 5.1.
Experiencing some slow and weird behavior.
But installing the latest High Sierra and then upgrading to Mojave was the real deal.
Everything has been working flawlessly since.
I also Bought the RX560 graphics card and it works fine.
Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse custom splash screen with updating progress monitor I'd like to create a splash screen for my eclipse product that has both name/password inputs and a progress monitor with system "Loading..." messages. I've created my splashHandler extension with splashHandler and product mapping. The splashHandler itself is the wizard-produced InteractiveSplashHandler similar to what's described here: Eclipse RCP application - custom splash screen
I've changed it to use a ProgressMonitorPart so I can get a message area above the monitor bar. I create it in #createUI and It's returned in #getBundleProgressMonitor. But how can I hook it into the application start-up so that it increments the progress and provides the stock messages? I have a plugin_customization.ini with the org.eclipse.ui preference for SHOW_PROGRESS_ON_STARTUP set to true. This file is referenced in my product extension. What am I missing?


text:
Q: Install new relic Django 1.5 in virtualenv with supervisord I've a completely good running Django site on a production server with Django 1.5 inside a virtualenv and controlled with supervisord.
I cannot however get the new relic monitoring going. Everything starts fine, but my application is not showing in the new relic dashboard.
here is my supervisor config:
[program:<PROJECTNAME>]
process_name=gunicorn
directory=/var/www/<PROJECTNAME>/<PROJECTNAME>
environment=
    DJANGO_SETTINGS_MODULE='settings.prod',
    SECRET_KEY='xxx',
    DB_USER='xxx',
    DB_PASSWD='xxx',
    NEW_RELIC_CONFIG_FILE="/var/www/<PROJECTNAME>/newrelic.ini"
command=/var/www/<PROJECTNAME>/env/bin/newrelic-admin run-program /var/www/<PROJECTNAME>/env/bin/gunicorn wsgi:application -c  /var/www/<PROJECTNAME>/<PROJECTNAME>/gunicorn_settings.py
group=www-data
autostart=True
stdout_logfile = /var/log/webapps/<PROJECTNAME>/gunicorn.log
logfile_maxbytes = 100MB
redirect_stderr=True

And this is the gunicorn_settings config file:
pythonpath = '/var/www/<PROJECTNAME>/'
pidfile = '/tmp/<PROJECTNAME>.pid'
user = 'www-data'
group = 'www-data'
proc_name = '<PROJECTNAME'
workers = 2
bind = 'unix:/tmp/gunicorn-<PROJECTNAME>.sock'
stdout_logfile = '/var/log/gunicorn/<PROJECTNAME>.log'
loglevel = 'debug'
debug = True

wsgi.py contains an extra pythonpath /var/www/
I've another Django 1.2 site running inside a virtualenv with supervisor and new relic on the same server just fine.


text:
Q: I got error when i separate a single strCommandText into 3 strCommandText lines I got this error Incorrect syntax near the keyword 'join'. I guess i arranged it wrongly. It worked when it was in one line. I want to arrange it in 3 lines so it lo
Previous
string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID Left outer join Patient as p on a.patientid = p.patientId left outer join medicalcentre as m on a.mcID = m.mcid";

After
string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT";
strCommandText += "AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID";
strCommandText += "Left outer join Patient as p on a.patientid = p.patientId";
strCommandText += "left outer join medicalcentre as m on a.mcID = m.mcid";

A: Add a space to separate the text
    string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT ";
    strCommandText += "AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID ";
    strCommandText += "Left outer join Patient as p on a.patientid = p.patientId ";
    strCommandText += "left outer join medicalcentre as m on a.mcID = m.mcid ";

You could also remove the string concatenation using the verbatim prefix
    string strCommandText = @"SELECT appointmentID, aDate, aTime, aStatus,
               aContact, aHeight, aWeight, p.pFirstName, m.mcCentre, n.nFirstName
               FROM APPOINTMENT AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID
               LEFT OUTER JOIN Patient AS p on a.patientid = p.patientId
               LEFT OUTER JOIN medicalcentre AS m on a.mcID = m.mcid";

A: You need spaces after every string you add.
Without spaces, your first concatenation seems like FROM APPOINTMENTAS a LEFT OUTER instead of FROM APPOINTMENT AS a LEFT OUTER which creates an invalid sql query.
string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT ";
strCommandText += "AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID ";
strCommandText += "Left outer join Patient as p on a.patientid = p.patientId ";
strCommandText += "left outer join medicalcentre as m on a.mcID = m.mcid";

You can have a multine string with using verbatim string literal like;
string strCommandText = @"SELECT appointmentID, aDate, aTime, aStatus,
                        aContact, aHeight, aWeight, p.pFirstName, m.mcCentre, n.nFirstName
                        FROM APPOINTMENT AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID
                        LEFT OUTER JOIN Patient AS p on a.patientid = p.patientId
                        LEFT OUTER JOIN medicalcentre AS m on a.mcID = m.mcid";

A: You need to add space for every new string that you add to the command.
        string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT";
        strCommandText += " AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID";
        strCommandText += " Left outer join Patient as p on a.patientid = p.patientId";
        strCommandText += " left outer join medicalcentre as m on a.mcID = m.mcid";

A: You're missing spaces.  When you concatenate in the way you are doing it, it's easy to miss leading/trailing spaces. I'd use a stringbuilder rather than concatenating strings:
        var builder = new StringBuilder();
        builder.Append("SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName From APPOINTMENT");
        builder.AppendLine("AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID");
        builder.AppendLine("Left outer join Patient as p on a.patientid = p.patientId");
        builder.AppendLine("left outer join medicalcentre as m on a.mcID = m.mcid");

        var commandText = builder.ToString();

Your current method will produce the following string:
SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName From APPOINTMENTAS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseIDLeft outer join Patient as p on a.patientid = p.patientIdleft outer join medicalcentre as m on a.mcID = m.mcid

Notice the APPOINTMENTAS, n.NurseIDLeft and patientIdleft.  This is because of the missing spaces in your method of concatenation.


text:
Q: If $\phi : G \to H$ is a group homomorphism with kernel $K,$ and $\phi(g) = h,$ find the fiber over $h$ in $G$, i.e. the set $\phi^{-1}(h).$
If $\phi : G \to H$ is a group homomorphism with kernel $K,$ and $\phi(g) = h,$ find the fiber over $h$ in $G$, i.e. the set $\phi^{-1}(h).$

My thought is that:
Take $k \in K.$ Then $\phi(k) = e'$ where $e'$ is the identity in $ H$.
Then $\phi(gk) = \phi(g)\phi(k) = he' = h$.
So $\phi^{-1}(h) = gK $.
Looks pretty short, but would this proof enough?

A: You have proven that $gK\subseteq \phi^{-1}(h)$ (and this proof is fine). It remains to show inclusion the other way.
Let $g'\in\phi^{-1}(h)$, which is to say $\phi(g')=h$. Then we have $\phi(g^{-1}g')=e'$, so $g^{-1}g'\in K$, which means $g'=gg^{-1}g'\in gK$.


text:
Q: HELP ASAP I want to install ubuntu
Possible Duplicate:
How do I set up a dual boot Windows  and Ubuntu?

I want to install ubuntu for my pc but i dont want to lose my windows. I want to install both OS on my pc. How can I do it and how can i download the OS? please reply. thanks.

A: When you visit the Ubuntu homepage, there's a nice orange button, labled "Get Ubuntu now". Click that button and select the correct architecture for your system. If you don't know, just stick with the recommended options.
Please read these instructions for installing Ubuntu alongside an existing Windows installation.
Please please please read this document thoroughly before you begin. If you have any further questions, the Ubuntu wiki is a great resource.
Again, please read the manual.

A: Download it from here
http://www.ubuntu.com/download/desktop
Check the MD5SUM of the downloaded ISO image
Either create a Live Cd through Burning it or a Live USB through Universal USB installer or through Unetbootin , from windows.
First try Ubuntu through above Live Media , before installing.
Read these guides and follow them for Installation procedure.
How do I install Ubuntu?
Illustrated Dual-Boot instructions

A: To download Ubuntu, visit www.ubuntu.com, then click "Get Ubuntu now." I'm going to assume you want the desktop version, so click "Ubuntu Desktop."
Now, if you want an easy way to try Ubuntu and get just about the full experience, just a tiny bit slower, scroll down and click "Windows Installer."
Otherwise, you need to first select either 64bit, or 32bit, if your computer is somewhat old, choose 32bit, otherwise, you are probably safe with 64bit. Click the orange button labeled Start Download, and wait for it to finish.
Then, go to http://www.ubuntu.com/download/help/burn-a-cd-on-windows for instructions on burning an Ubuntu CD or DVD or http://www.ubuntu.com/download/help/create-a-usb-stick-on-windows to use a USB (if your computer is older, or you want the easiest option, you should use a CD).
Once done, insert the CD and turn off your computer, turn it back on, and allow Ubuntu to boot. Follow the instructions until you get to the installation prompt. Choose "Install Ubuntu Alongside Them" to keep Windows and install Ubuntu.
Move the slider to choose how much of your hard disk each OS will use. Click install and then follow the installation steps (It's easy stuff like "choose your region" etc).
You'll then receive a prompt telling you to restart...
Welcome to Ubuntu!


text:
Q: How to shuffle a collection of integers so that the output is same in both C++ and Java? I am porting a piece of code from C++ to Java. In C++, I shuffle a vector<int> as below:
std::vector<int> integers(10); //Size is not constant and can change.
std::iota(std::begin(std::begin(integers), std::end(integers), 0); //fills the vector with integers from 0 to 9
std::mt19937 gen;
gen.seed(integers.size());
std::shuffle(std::begin(integers), std::end(integers), gen);

After doing some reseach, I found out that, java uses Linear Congruential Generator (LCG) to generate random numbers.
In order to use same parameters used by Java.util.random for LCG, I changed my random number generator engine to (According to this wikepedia page LCG):
std::linear_congruential_engine<unsigned long, 0x5DEECE66D, 11, 281474976710655>  engine(10);

C++ shuffled result : 6,9,0,3,8,4,1,2,7,5

Here is the correspoding Java code:
ArrayList<Integer> array = new ArrayList(10);
for(int i = 0; i < 10; ++i){
    array.add(i, i);
}
Collections.shuffle(array,  new Random(10));
for(int i = 0; i < 10; ++i){
    System.out.print(array.get(i));
}

Java shuffled result: 9,7,8,0,1,4,5,2,6,3

*

*Is there a way to make C++ stadard random number generators to
behave the same way as of Java or vice versa?

*Is there any other (probably simpler) approach I could take to solve
this problem? I don't mind changing my existing C++ code.

A: Write JNI code to do it.. The C++ code would look like:
JNIEXPORT jintArray JNICALL Java_NativeRandom_generateRandomIntegers(JNIEnv *env, jclass cls, int size)
{
    std::vector<int> integers(size);
    std::iota(std::begin(integers), std::end(integers), 0);

    std::mt19937 gen;
    gen.seed(size);
    std::shuffle(std::begin(integers), std::end(integers), gen);

    jintArray result = env->NewIntArray(size);
    if (result)
    {
        env->SetIntArrayRegion(result, 0, size, &integers[0]);
        return result;
    }
    return nullptr;
}

On the Java side it would look like:
public class NativeRandom {

    static {
        System.loadLibrary("NativeRandom.so");
    }

    public static native int[] generateRandomIntegers(int size);

    public static void main(String[] args) {
        int[] randomNumbers = generateRandomIntegers(10);
        System.out.println(randomNumbers);
    }
};

A: A linear congruential generator, according to Wikipedia, has several variables (modulus, multiplier, increment), which differ across implementations. The parameters used for Java and C++, as you can see by the link, are vastly different. Therefore, even if you seeded them both identically, they would produce different values. Therefore, there is no change in your code that would natively allow both the C++ and Java versions to produce the same random number sequence.
If you wanted a specific random sequence, your best bet is probably to find a third-party RNG library with support for these two languages, but StackOverflow frowns upon suggesting external libraries, so good luck ;)


text:
Q: Error message appears compiling derived class When I try to compile my derived class IntSearchTree, the error message
IntSearchTree.java:3: error: constructor IntBinTree in class IntBinTree
cannot be applied to given types;

IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {

required: int,IntBinTree,IntBinTree

found: no arguments

reason: actual and formal argument lists differ in length

1 error

, appears.
The following code shows the most important lines of the base class:
 class IntBinTree {
   int node;
   IntBinTree left;
   IntBinTree right;

   IntBinTree(int node, IntBinTree left, IntBinTree right) {
     this.node = node;
     this.left = left;
     this.right = right;
   }
 }

And the most important lines of the derived class:
 class IntSearchTree extends IntBinTree {
 IntSearchTree left;
 IntSearchTree right;

   IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
     this.node = node;
     this.left = left;
     this.right = right;
   }
 }

I tried to solve that problem by giving the constructor in the base clase the private modifier
 private IntBinTree(int node, IntBinTree left, IntBinTree right) {...}

, but the compiling error message was the same.
So the first question is how is it possible to define a constructor in a way that it is visible in the base class, but not in derived classes?
And the second question is, why is the base constructor still visible in the derived class, even if I use the private modifier?

A: You need a no-args constructor.
Place this into your IntBinTree class:
IntBinTree()
{
}

Or you can use this instead in the IntSearchTree class:
IntSearchTree(int node, IntSearchTree left, IntSearchTree right) {
     super(node,left,right);
  }

When you do not have a no-args constructor in the super class, you need to explicitly call the constructor you want to use in the child class.  This super() will call the constructor that takes in the node, left, right from IntBinTree().

A: I can see two problems with that implementation.

*

*You probably don't want to declare left and right fields again in your derived class - it's not causing a compilation error, but for sure will cause some problems hard to debug later.

*Creation of derived class requires calling a constructor of its super class - in that case, you could call super(node, left, right) in your current constructor, or super(). Remember that java creates by default public parameterless constructor for any class you create.


text:
Q: HTMLElement.getClientRects() sorted order If I call getClientRects() on an Element in javascript (see documentation at MDN), is there a defined order of the returned array?  Are the rects in the order of appearance of their respective child elements, as one would expect (at least in my mind)?

A: I answered my own question.  From the W3C spec:

Return a ClientRectList object containing a list of ClientRect objects in content order describing the border boxes (including those with a height or width of zero)...

(Emphasis added)


text:
Q: Nested SVG selections in D3 I have a list of n associative arrays.
[{'path': 'somepath', 'relevant': [7, 8, 9]}, {'path': 'anotherpath', 'relevant': [9], ...}
Within a large SVG, I want to: a) create rects ("buckets") whose dimensions are proportional to the lengths of their 'relevant' sublists, and b) create rects ("pieces"), for each of the elements in the sublists, placed "inside" their respective buckets.
After reading Mike Bostock's response to a similar question, I'm sure that I need to use group ("g") elements to group the pieces together. I can get the code below to produce the DOM tree that I want, but I'm stumped on how to code the y values of the pieces. At the point where I need the value, D3 is iterating over the subarrays. How can I get the index of the current subarray that I'm iterating over from inside it when i no longer points to the index within the larger array?
var piece_bukcets = svg.selectAll("g.piece_bucket")
                      .data(files)
                      .enter()
                      .append("g")
                      .attr("class", "piece_bucket")
                      .attr("id", function (d, i) { return ("piece_bucket" + i) })
                      .append("rect")
                      .attr("y", function (d, i) { return (i * 60) + 60; })
                      .attr("class", "bar")
                      .attr("x", 50)
                      .attr("width", function (d) {
                        return 10 * d["relevant"].length;
                      })
                      .attr("height", 20)
                      .attr("fill", "red")
                      .attr("opacity", 0.2)

        var pieces = svg.selectAll("g.piece_bucket")
                        .selectAll("rect.piece")
                        .data( function (d) { return d["relevant"]; })
                        .enter()
                        .append("rect")
                        .attr("class", "piece")
                        .attr("id", function (d) { return ("piece" + d) })
                        .attr("y", ????)  // <<-- How do I get the y value of d's parent?
                        .attr("x", function (d, i) { return i * 10; })
                        .attr("height", 10)
                        .attr("width", 10)
                        .attr("fill", "black");

Is there a method on d available to find the index of the node it's currently inside? In this case, is there a method I can call on a "piece" to find the index of its parent "bucket"?

A: You can use the secret third argument to the function:
.attr("y", function(d, i, j) {
  // j is the i of the parent
  return (j * 60) + 60;
})

There's a simpler way however. You can simply translate the g element and everything you add to it will fall into place.
var piece_buckets = svg.selectAll("g.piece_bucket")
                  .data(files)
                  .enter()
                  .append("g")
                  .attr("class", "piece_bucket")
                  .attr("transform", function(d, i) {
                    return "translate(0," + ((i*60) + 60) + ")";
                  })
                  .attr("id", function (d, i) { return ("piece_bucket" + i) });
piece_buckets.append("rect")
                  .attr("class", "bar")
                  .attr("x", 50)
                  .attr("width", function (d) {
                    return 10 * d["relevant"].length;
                  })
                  .attr("height", 20)
                  .attr("fill", "red")
                  .attr("opacity", 0.2);

var pieces = piece_buckets.selectAll("rect.piece")
                    .data(function (d) { return d["relevant"]; })
                    .enter()
                    .append("rect")
                    .attr("class", "piece")
                    .attr("id", function (d) { return ("piece" + d); })
                    .attr("x", function (d, i) { return i * 10; })
                    .attr("height", 10)
                    .attr("width", 10)
                    .attr("fill", "black");


text:
Q: Tmux find window configurations I bound my f key to find words in current pane of tmux. How can I bind find window to a different key? I also want to do other things like naming a window etc. The way I have started setting my tmux config is to google for the functionaluty I need and copy it into my tmux conf. Is there a documentation on how to do all this on my own.
 How does one come up with a config like bind-key s copy-mode \; send-key ? or bind-key C-a send-prefix.
I tried adding bind-key f find-window  hoping it would bind f to find-window. But doesn't work
Thanks

A: Here is a list of the default tmux commands. As you can see, the default bind for f is not bind-key f find-window but bind-key f command-prompt "find-window '%%'"
The rest of your question is very unclear. You can vim ~/.tmux.conf and add whatever commands you want, such as bind-key C-a send-prefix. That line is in my tmux.conf and it works fine.
One possibility is that you aren't reloading your config file after changes (tmux won't do this with existing windows by default). You can use prefix+:source-file ~/.tmux.conf to reload your config file. You can add a command to your config to make this easier while you tweak it:
bind-key R source-file ~/.tmux.conf \; display-message "Config reloaded..."


text:
Q: How to build a python package into an exe I have written my program in python. It is written across seven files and in three of the files I import a custom package. The thing is I cant build my program into an exe. I have tried pyinstaller 1.5.1 and py2exe. I have followed every tutorial I could find but with no success. Every time I have tried when I go to run the exe created I get an error message saying it cannot find my custom package. I think I have just not been able to get the complete package to be built into the exe. Please help.
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')

mfcfiles = [os.path.join(mfcdir, i) for i in ["mfc90.dll", "mfc90u.dll", "mfcm90.dll", "mfcm90u.dll", "Microsoft.VC90.MFC.manifest"]]

data_files = [("Microsoft.VC90.MFC", mfcfiles),]

setup(
    data_files = data_files,
    options = {'py2exe': {'optimize': 2}},
    windows = [{'script': "LoadFilesGUI.py"}],
    zipfile = "shared.lib",
)

another:
from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'optimize': 2}},
    windows = [{'script': "LoadFilesGUI.py"}],
    zipfile = None,
    console=['LoadFilesGUI.py'],
)

A: By "custom package", I am assuming you mean your custom python modules that make up your application. I might suggest trying to use the "includes" option of the setup() call to manually specify the python modules that should be included, in case they are not discovered automatically:
setup(
    windows = [{'script': "LoadFilesGUI.py"}],
    data_files = data_files,
    zipfile = None,
    options = {
        'py2exe': {
            'optimize': 2,
            'bundle_files': 1,
            'includes' : [],
        }
    },
)

For instance, in my project which uses PyQt4, my includes looks like this:
options={
    "py2exe": {
        "includes" : ['sip','PyQt4.QtCore','PyQt4.QtGui',
                        'PyQt4.QtNetwork','PyQt4.QtWebKit']
    }
}

The rest of your setup.py script seems to be pretty standard. Make sure that your included modules are part of your PYTHONPATH, either being relative to your project, or explicitly added to the path.
If, as you have stated in your comments, MyPackage is a package within your project, then you would want:  'includes' : ['MyPackage']
If this still gives you errors, then the problem could be with the structure of your project and package, or again, with your PYTHONPATH

A: cx_freeze is the answer.
From my experience is the most reliable option.
Sometimes it misses some dependency, but you can easily add that manually once you discover what's missing.


text:
Q: JBoss support Websockets? Does JBoss support WebSockets?  Where can I find an example?
( I did try looking around for an answer, but ended up confused by product names.  There is something called infinispan which might handle websockets, then there is HornetQ which might not be up to date, then there is a patch for Netty...  I don't know what these different products are.  Maybe what I am trying to do is handled in Tomcat already?)
I just want some sample code so I can get a sense of how this type of connection would be handled by JBoss.  I would like to try to connect to some clients with web-socket-js )

A: JBoss 6 supports asynchronous servlet handling. Websockets are on the client side. I guess they will work.
If you want to have comet regardless of the underlying implementation, take a look at Atmosphere - it will choose the most advanced method available.


text:
Q: Error when printing crystal report , Index and length must refer to a location within the string. Parameter name: length When I try to print my crystal report this error shows up:

Index and length must refer to a location within the string. Parameter
  name: length


text:
Q: Pass Data from the TabBarController to child view controllers on initial load I have a Tab Bar Controller and two linked child view controllers connected to it.
However I need to pass values from the TabBarController to the children right when the tabs are loaded for the first time.

A: Inside viewDidLoad of the custom tab class do
let vc = self.viewControllers.last! as! SecondVC
vc.loadViewIfNeeded()
vc.somePro = <#value#>


text:
Q: Javascript regex for words including spaces and other characters String search : 'authorizations'
Actual :
Authorizations
PCP / Authorizations
Expected is :
Authorizations
PCP / Authorizations
I am trying to bold the search results, but I want to bold only the exact matches. I used this regex but it does not gives the desired result.
        $(event.target).autocomplete({
                        minLength: 1,
                        source: $(event.target).attr("data-source").replace("[","").replace("]","").split(",")
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            var term = this.term,
                regex = new RegExp('\\b' + term + '\\b', 'gi');
                label = item.label.replace(regex, '$&');
                $link = $("").html(label);
            return $("

").append($link).appendTo(ul);
        };

A: Since you only want to bold on exact equivalence, then why not just use == to compare the string:
    $(event.target).autocomplete({
                    minLength: 1,
                    source: $(event.target).attr("data-source").replace("[","").replace("]","").split(",")
    }).data("ui-autocomplete")._renderItem = function(ul, item) {
        var term = this.term;
        if (item.label == 'Authorizations') {
            label = 'Authorizations';
        }
        else {
            label = item.label;
        }
        $link = $("").html(label);

        return $("

").append($link).appendTo(ul);
    };


text:
Q: Limit calculation known formula can anyone explain to me why this limit is true? I've tried to solve it using the known limit, but I got 1
$$\lim_{n \rightarrow \infty}\frac{(1+\frac1n)^{n^2}}{e^n} = \frac{1}{\sqrt{e}}.$$

A: You could take the logarithm and rewrite:
$$\ln \frac{\left(1+\frac1n \right)^{n^2}}{e^n} = n^2 \ln \left(1+\frac1n \right)-n =\frac{\ln \left(1+\frac1n \right)-\frac1n}{\frac{1}{n^2}}$$
For $n \to \infty$, you get the indeterminate form $\tfrac{0}{0}$ so you can apply l'Hôpital's rule:
$$\lim_{n \to \infty} \frac{\ln \left(1+\frac1n \right)-\frac1n}{\frac{1}{n^2}}=\lim_{n \to \infty} \frac{\frac{-\frac{1}{n^2}}{\left(1+\frac1n \right)}+\frac{1}{n^2}}{\frac{-2}{n^3}}
=\cdots=\lim_{n \to \infty} \frac{n}{-2(n+1)}=-\frac{1}{2}$$
So with $\lim_{n \to \infty} u_n = e^{\lim_{n \to \infty} \ln u_n}$, you have:
$$\lim_{n \to \infty}\frac{\left(1+\frac1n \right)^{n^2}}{e^n}
= e^{-\tfrac{1}{2}}=\frac{1}{\sqrt{e}}$$

A: Let $a_n$ be the sequence of your problem. Then:
$\ln a_n=n(n\ln(1+\frac{1}{n})-1)$
By the Taylor series of the logarithm, we have that there exists $x_n \in (0.\frac{1}{n})$:
$\ln(1+\frac{1}{n})=\frac{1}{n}-\frac{1}{2n^2}+\frac{1}{3n^3(x_n+1)^3} \Rightarrow n(n\ln(1+\frac{1}{n})-1)=-\frac{1}{2}+\frac{1}{3n(x_n +1)^3}$
Since $x_n\rightarrow 0$ when $n\rightarrow +\infty$, we take the limits in the previous equality and conclude that $\ln a_n\rightarrow -\frac{1}{2}\Rightarrow a_n\rightarrow e^{-\frac{1}{2}}=\frac{1}{\sqrt{e}}$


text:
Q: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column in 'field list' using Criteria and mapping annotation i have criterias  to access result by
First Hibernate Dao is
AnswerText answersText = questionManager.getAnswerTextByAnswerIdAndLanguageId(answers.getAnswerId(), 1L);

@Override
    public AnswerText getAnswerTextByAnswerIdAndLanguageId(Number answerId,Number languageId) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(AnswerText.class);
        criteria.add(Restrictions.eq("answer.answerId", answerId));
        criteria.add(Restrictions.eq("languageId", languageId));
        List<AnswerText> results = criteria.list();
        return (results !=null && !results.isEmpty()? results.get(0): null);
    }

Answers.java

@Entity
@Table(name = "ANSWERS")
@Cacheable

@JsonIgnoreProperties(ignoreUnknown = true)
public class Answer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ANSWER_ID")
    private Long  answerId;

    @Column(name = "QUESTION_ID")
    private Long      questionId;

    @Column(name = "DATE_CREATED")
    private Timestamp   dateCreated;

    @Column(name = "CREATED_BY_ID")
    private Long      creatorId;

    @Column(name = "DATE_MODIFIED")
    private Timestamp   dateModified;

    @Column(name = "MODIFIED_BY_ID")
    private Long    modifierId;

    @OneToMany(fetch = FetchType.EAGER,mappedBy = "answer" )
    private Set<AnswerText> answerText = new HashSet<AnswerText>();

            //getters and setters

AnswerText.java

@Entity
@Table(name = "ANSWERTEXT")
@Cacheable

@JsonIgnoreProperties(ignoreUnknown = true)
public class AnswerText {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ANSWER_TEXT_ID")
    private Long answerTextId;

    @ManyToOne
    @JoinColumn(name="answerId", insertable=false, updatable=false,
                nullable=false)
    private Answer answer;

    @Column(name = "ANSWER_TEXT")
    private String answerText;

    @Column(name = "LANGUAGE_ID")
    private Long languageId;

            //getters and setters

When i access the to fetch resultset, it shows below error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'answertext2_.answerId' in 'field list'

Then i changed to below in
AnswerText.java
@ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ANSWER_ID", nullable = false)
    private Answer answer;

Answers.java
@OneToMany(fetch = FetchType.EAGER,mappedBy = "answer" )
    @Fetch(FetchMode.JOIN)
    private Set<AnswerText> answerText = new HashSet<AnswerText>();

This produce no error But fetch results twice on calling
Second HibernateDao call is
List<Answer> answerList = questionManager.getAnswersByQuestionId(Long.parseLong("2"));
            System.out.println("answerList :"+answerList1.size());

    @Override
public ArrayList<Answer> getAnswersByQuestionId(Number questionId) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Answer.class);
    criteria.add(Restrictions.eq("questionId", questionId));
    ArrayList<Answer> answerList = (ArrayList) criteria.list();
    return answerList;
}

Can Please anyone point me what is going wrong here. PLease help me.

A: You have done right changing the JoinColumn-name.
Your multiple results in my opinion is bound to:
FetchType.EAGER and the selection of

FetchMode JOIN As indicated you'll have to worry about duplicated
  results. On the other hand JOIN creates the least amount of queries.
  In a high latency environment a single JOIN could be considerable
  faster then multiple SELECTS. Keep in mind that joining too much data
  could put a strain on the database.
  from http://www.solidsyntax.be/2013/10/17/fetching-collections-hibernate/

With FetchMode.SELECT you would get the result like you want to have it.


text:
Q: Does OpenBSD have anything equivalent to Debian's /etc/network/if-up.d/ scripts? I want to run a script after an OpenBSD interface has been configured (dynamic IP address assigned, routes configured, etc.) I can't find anything in the hostname.if man page about this; does such a feature exist in OpenBSD?

A: While you can run shell commands from hostname.if, you might find ifstated(8) a better fit.


text:
Q: How to use 'clipto' func in fabric.js 1.7 above I use fabric.js.
I use 'clipto' function to crop an image,
but it doesn't work in the version 1.7 above of the fabric.js.
When I include the version 1.6.7 or below, it works well.
https://jsfiddle.net/uemon/nqg2q2qs/
var canvas = new fabric.Canvas('c',{
backgroundColor: '#ffffff',
});

var imgURL = 'http://fabricjs.com/lib/pug.jpg';
var path = new fabric.Path('M121.32,0L44.58,0C36.67,0,29.5,3.22,24.31,8.41\
c-5.19,5.19-8.41,12.37-8.41,20.28c0,15.82,12.87,28.69,28.69,28.69c0,0,4.4,\
0,7.48,0C36.66,72.78,8.4,101.04,8.4,101.04C2.98,106.45,0,113.66,0,121.32\
c0,7.66,2.98,14.87,8.4,20.29l0,0c5.42,5.42,12.62,8.4,20.28,8.4c7.66,0,14.87\
-2.98,20.29-8.4c0,0,28.26-28.25,43.66-43.66c0,3.08,0,7.48,0,7.48c0,15.82,\
12.87,28.69,28.69,28.69c7.66,0,14.87-2.99,20.29-8.4c5.42-5.42,8.4-12.62,8.4\
-20.28l0-76.74c0-7.66-2.98-14.87-8.4-20.29C136.19,2.98,128.98,0,121.32,0z');

fabric.Image.fromURL(imgURL, function(image) {

   canvas.add(image);
   image.set({
            clipTo: function(ctx) {
                path.set({
                        left: -100,
                        top: -100
                    });
                path.render(ctx);
            }
   });
   canvas.renderAll();
});

But when I include the fabric.js of the version 1.7.0 or above, it doesn't work.
https://jsfiddle.net/uemon/affumnxh/1/
How can I use 'clipto' function in the ver.1.7 or above ?
Thank you in advance.

A: I could solve the problem by using 'objectCaching: false'.
See https://github.com/kangax/fabric.js/issues/3454
The final code is below.
var canvas = new fabric.Canvas('c',{
  backgroundColor: '#ffffff',
});

var imgURL = 'http://fabricjs.com/lib/pug.jpg';
var path = new fabric.Path('M121.32,0L44.58,0C36.67,0,29.5,3.22,24.31,8.41\
c-5.19,5.19-8.41,12.37-8.41,20.28c0,15.82,12.87,28.69,28.69,28.69c0,0,4.4,\
0,7.48,0C36.66,72.78,8.4,101.04,8.4,101.04C2.98,106.45,0,113.66,0,121.32\
c0,7.66,2.98,14.87,8.4,20.29l0,0c5.42,5.42,12.62,8.4,20.28,8.4c7.66,0,14.87\
-2.98,20.29-8.4c0,0,28.26-28.25,43.66-43.66c0,3.08,0,7.48,0,7.48c0,15.82,\
12.87,28.69,28.69,28.69c7.66,0,14.87-2.99,20.29-8.4c5.42-5.42,8.4-12.62,8.4\
-20.28l0-76.74c0-7.66-2.98-14.87-8.4-20.29C136.19,2.98,128.98,0,121.32,0z');

fabric.Image.fromURL(imgURL, function(image) {

   canvas.add(image);
   image.set({
            clipTo: function(ctx) {
                path.set({
                        left: -100,
                        top: -100,
                        objectCaching: false
                    });
            path.render(ctx);
        }
   });
   canvas.renderAll();
});


text:
Q: How to change color on every element in div when hovering? I am trying to change the color of content, including h4 title, when hovering over div but the title does not get white colored. Don't know how I can achieve this:

.iconbox-blue {
  background: #fff;
  color: #000;
}

.iconbox-blue:hover {
  color: #fff;
  background: blue;
}

Header

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

What am I doing wrong? How can I make the h4 title color white when hovering over iconbox-blue div?

A: You just need to simply add a hover effect that changes the anchor-element.
As anchor tag does not inherit attributes like if an href attribute is present.
.iconbox-blue:hover a{
  color: #fff;
}

.iconbox-blue {
  background: #fff;
  color: #000;
}

.iconbox-blue:hover {
  color: #fff;
  background: blue;
}
.iconbox-blue:hover a{
  color: #fff;
}

Header

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

A: Add one additional style for the H4:
.iconbox-blue:hover,
.iconbox-blue:hover h4 {
   color: #fff;
   background: blue;
}


text:
Q: Multidimensional arrays in PHP created by a mysql query I have a base table in a MySQL database that has 200,000 records.
The structure of this table is as follows:
    CREATE TABLE `npanxxmaster` (
  `npanxx` varchar(6) NOT NULL DEFAULT '',
  `npa` varchar(3) DEFAULT NULL,
  `ocn_lata` varchar(7) DEFAULT NULL,
  `lata` varchar(3) DEFAULT NULL,
  `st` varchar(2) DEFAULT NULL,
  `canada` varchar(10) DEFAULT NULL,
  `ext` varchar(10) DEFAULT NULL,
  `er` double DEFAULT NULL,
  `ra` double DEFAULT NULL,
  `un` double DEFAULT NULL
)

I'm storing this table into an array with the key being the npanxx value.
I have a flat csv file that has the following structure:
npanxx(or npa only), ER, RA , UN

For a little more information npanxx is a 6 digit number and npa will always be a 3 digit number (from the npanxx).
Now this flat file, in the first column can have either npanxx (6 digits) or npa (3 digits).
What I need to do is read in each line of the csv file (which I can already do) and I store that into an array with the following code:
if (($handle = fopen($fileName, "r")) !== FALSE) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE){

Now here comes the tricky part. What I need to do is go through each of the $row (lines in the csv file) and find a match in the original $npanxxmaster array that I made from the MySQL table. The problem I have is the flat file can contain in its first column either npanxx or npa. And what I need to do with those are match them with the matching npanxx or npa in the $npanxxmaster array with any $row that has an npanxx taking precident over one that only has an npa.
For example:
If given in the flat csv file the following $rows:
201,.002,.002,.002
201200,.001,.001,.001

All entries in the $npanxxmaster array with an npa of 201 would get the .002,.002,.002 OTHER THAN 201200 which would get .001,.001,.001
I have no been able to achieve this at all. I can provide more code of what I have tried or more explanation if needed because i'm assuming I butchered that explanation.
Thank you all in advance for all the help!

A: When processing the query, make two arrays. One that maps NPANXX to rows, and another that maps NPA to an array of NPANXX.
$npanxx_array = array();
$npa_array = array();
while ($row = $stmt->fetch()) {
    $npanxx = $row['npanxx'];
    $npa = $row['npa'];
    $npanxx_array[$npanxx] = $row;
    if (!isset($npa_array[$npa])) {
        $npa_array[$npa] = array();
    }
    $npa_array[$npa][] = $npanxx;
}

Then when you're processing the CSV, you can look up the appropriate field.
while ($row = fgetcsv($handle)) {
    if (strlen($row[0]) == 6) {
        $npanxx_to_update = array($row[0]);
    } else {
        $npanxx_to_update = $npa_array[$row[0]];
    }
    foreach ($npaxx_to_update as $npanxx) {
        // update $npanxx_array[$npanxx]
    }
}


text:
Q: Is it safe to cancel diskpart format in progress? I am currently formatting my external 1863 GiB HDD, because I had found out there were many bad sectors, however the numbers of the cylinders where the bad sectors are located change everytime I run a test, no filesystem corruptions were found, no corrupt files, and when I just run the tests merely a week ago, the disk was fine. During last week nothing can physically harm my disk happened. I think this is possibly logical bad sector or failure in the USB convertor chip. I will replace the disk if there are physical bad sectors.
I have run these commands in elevated cmd:
diskpart
list disk
select disk 1
clean
create partition primary
format fs=ntfs

And the formatting takes forever... It takes several minutes to climb 1%, currently 12 percent completed
But I had read somewhere I can use clean all in diskpart to zero fill a disk, this will likely fix logical bad sectors, and I want to do that now, but the formatting is currently in progress, so will it harm my HDD if I ctrl+c the format progress?

A: It won't harm anything, but you have to realize that a "Clean all" will take almost just as long. (Both a full format and a clean all need to overwrite the entire disk. That is always going to take a while on large disk.)
Anyway... If you have random bad blocks on an external disk it is either the disk itself or the USB enclosure that is faulty.
Doing a full format or "clean all" through that same enclosure doesn't prove/solve anything if the enclosure is at fault. You can't trust it to do it right.
Also: Disk-tests and/or SMART data are often unreliable if done via USB as the controller chip inside the enclosure may manipulate the tests.
The only way to be sure if the disk itself is good is to take it out of the enclosure and connect it directly with SATA to the motherboard, or put it in another (known to be good) enclosure and format it there.


text:
Q: How can I align button in Center or right using IONIC framework?
I want the login and register button in right,and Search button in Center, I searched alot but didn't get any solution.
And also how can I align text area in a proper position.
Here is my html code:

    <ion-pane  style = "background-color:#4992E2;">
      <ion-header-bar class="bar bar-subheader" style = " margin-top: -35px; background-color:#F9F9F9;">

NetHealth Appointment Booking

      </ion-header-bar>
      <ion-content >

                    <button class="button button-small  button-light" >
                      Login!
                    </button>
                     <button class="button button-small  button-light">
                      Register Here!
                    </button>

Date

                <input type="text" placeholder="Text Area">

Suburb

                <input type="text" placeholder="Text Area">

Clinic

                <input type="text" placeholder="Text Area">

        <button class=" center button button-small  button-light">
          Search
        </button>

        </ion-content>
    </ion-pane>

I know in the bootstrap, but I am new to ionic, please tell me how can I do this.

A: You should put the button inside a div, and in the div you should be able to use the classes: text-left, text-center and text-right.
for example:

      <button class="button button-small button-light">Search</button>

And about the "textarea" position:

    Date
    <input type="text" placeholder="Text Area">

Demo using your code:
http://codepen.io/douglask/pen/zxXvYY

A: Ultimately, we are trying to get to this.

    <button ion-button>Login</button>

A: Css is going to work in same manner i assume.
You can center the content with something like this :
.center{
     text-align:center;
}

Update
To adjust the width in proper manner, modify your DOM as below :

     Date
        <input type="text" placeholder="Text Area" />

     Suburb
        <input type="text" placeholder="Text Area" />

CSS
label {
    display:inline-block;
    border:1px solid red;
    width:100%;
    font-weight:bold;
}

input{
    float:right; /* shift to right for alignment*/
    width:80% /* set a width, you can use max-width to limit this as well*/
}

Demo
final update
If you don't plan to modify existing HTML (one in your question originally), below css would make me your best friend!! :)
html, body, .con {
    height:100%;
    margin:0;
    padding:0;
}
.item-input-inset {
    display:inline-block;
    width:100%;
    font-weight:bold;
}
.item-input-inset > h4 {
    float:left;
    margin-top:0;/* important alignment */
    width:15%;
}
.item-input-wrapper {
    display:block;
    float:right;
    width:85%;
}
input {
    width:100%;
}

Demo

A: To use center alignment in ionic app code itself, you can use the following code:
<ion-row center>
 <ion-col text-center>
  <button ion-button>Search</button>
 </ion-col>
</ion-row>

To use right alignment in ionic app code itself, you can use the following code:
<ion-row right>
 <ion-col text-right>
  <button ion-button>Search</button>
 </ion-col>
</ion-row>

A: And if we want to align a checkbox to the right, we can use item-end.
<ion-checkbox checked="true" item-end></ion-checkbox>

A: Another Ionic way.  Using this ion-buttons tag, and the right keyword puts all the buttons in this group to the right.  I made some custom toggle buttons that i wanted on one line, but the group to be right justified.

<ion-buttons right>
<button ....>1</button>
<button ....>2</button>
<button ....>3</button>
</ion-buttons>

A: I Found the esiest soltuion just wrap the button with div and put  text-center align-items-center in it like this  :

<buttonion-button block class="button-design " text-center>Sign In </button>

A: center tag aligns the buttons within it as expected:
<ion-footer>
    <ion-toolbar>

            <button royal>
                Contacts
                <ion-icon name="contact"></ion-icon>
            </button>
            <button secondary>
                Receive
                <ion-icon name="arrow-round-back"></ion-icon>
            </button>
            <button danger>
                Wallet
                <ion-icon name="home"></ion-icon>
            </button>
            <button secondary>
                Send
                <ion-icon name="send"></ion-icon>
            </button>
            <button danger>
                Transactions
                <ion-icon name="archive"></ion-icon>
            </button>
            <button danger>
                About
                <ion-icon name="information-circle"></ion-icon>
            </button>

    </ion-toolbar>
</ion-footer>


text:
Q: Question regarding Run command in Windows This line below in the cmd shell unzips the content of a zip file D:\zips\test.zip in the folder C:\Users\mike\Desktop\test:
C:\Program Files\7-Zip\7z.exe e -oC:\Users\mike\Desktop\test D:\zips\test.zip

If I use Run nothing happens with the ouput error 1:
Run["C:\\Program Files\\7-Zip\\7z.exe e -oC:\\Users\\mike\\Desktop\\test D:\\zips\\test.zip"]

A: This is an expansion of my comment.
With its use of backslashes and spaces in directory names, the Windows OS a bit of an odd ball.  If you open a CMD prompt and try to execute the 7z.exe help (-h) without quotes, then I get the following error:
C:\Users\Tim>c:\Program Files\7-Zip\7z.exe -h
'c:\Program' is not recognized as an internal or external command,
operable program or batch file.

Now, the CMD prompt will automatically add quotes if you start typing a path to an executable and these quotes will need to be represented in the Run[] function.  The actual CMD prompt will look like this
C:\Users\Tim>"c:\Program Files\7-Zip\7z.exe" -h

7-Zip 18.05 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2018-04-30

Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]

<Commands>
  a : Add files to archive
  b : Benchmark
  d : Delete files from archive....

The following Mathematica code should execute 7z.exe help and read the output.
outputfile = CreateFile[];
Run["\"C:\\Program Files\\7-Zip\\7z.exe\" -h >>"  <> outputfile];
stext = OpenRead[outputfile];
ReadString[stext]
Close[stext];
DeleteFile[outputfile];
(* 7-Zip 18.05 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2018-04-30

Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]

<Commands>
  a : Add files to archive
  b : Benchmark *)


text:
Q: Exporting the values in List to excel Hi I am having a list container which contains the list of values. I wish to export the list values directly to Excel. Is there any way to do it directly?

A: The simplest way using ClosedXml.
Imports ClosedXML.Excel

var dataList = new List<string>() { "a", "b", "c" };
var workbook = new XLWorkbook();     //creates the workbook
var wsDetailedData = workbook.AddWorksheet("data"); //creates the worksheet with sheetname 'data'
wsDetailedData.Cell(1, 1).InsertTable(dataList); //inserts the data to cell A1 including default column name
workbook.SaveAs(@"C:\data.xlsx"); //saves the workbook

For more info, you can also check wiki of ClosedXml.
https://github.com/closedxml/closedxml/wiki

A: Exporting values List to Excel

*

*Install in nuget next reference

*Install-Package Syncfusion.XlsIO.Net.Core -Version 17.2.0.35

*Install-Package ClosedXML -Version 0.94.2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML;
using ClosedXML.Excel;
using Syncfusion.XlsIO;

namespace ExporteExcel
{
    class Program
    {
        public class Auto
        {
            public string Marca { get; set; }

            public string Modelo { get; set; }
            public int Ano { get; set; }

            public string Color { get; set; }
            public int Peronsas { get; set; }
            public int Cilindros { get; set; }
        }
        static void Main(string[] args)
        {
            //Lista Estatica
            List<Auto> Auto = new List<Program.Auto>()
            {
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2019, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2018, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2017, Color= "Azul", Cilindros=6, Peronsas= 4 }
            };
            //Inizializar Librerias
            var workbook = new XLWorkbook();
            workbook.AddWorksheet("sheetName");
            var ws = workbook.Worksheet("sheetName");
            //Recorrer el objecto
            int row = 1;
            foreach (var c in Auto)
            {
                //Escribrie en Excel en cada celda
                ws.Cell("A" + row.ToString()).Value = c.Marca;
                ws.Cell("B" + row.ToString()).Value = c.Modelo;
                ws.Cell("C" + row.ToString()).Value = c.Ano;
                ws.Cell("D" + row.ToString()).Value = c.Color;
                ws.Cell("E" + row.ToString()).Value = c.Cilindros;
                ws.Cell("F" + row.ToString()).Value = c.Peronsas;
                row++;

            }
            //Guardar Excel
            //Ruta = Nombre_Proyecto\bin\Debug
            workbook.SaveAs("Coches.xlsx");
        }
    }
}

A: OK, here is a step-by-step guide if you want to use COM.

*

*You have to have Excel installed.

*Add a reference to your project to the excel interop dll. To do this
on the .NET tab select
Microsoft.Office.Interop.Excel.
There could be multiple assemblies
with this name. Select the
appropriate for your Visual Studio
AND Excel version.

*Here is a code sample to create a new Workbook and fill a column with
the items from your list.

using NsExcel = Microsoft.Office.Interop.Excel;

public void ListToExcel(List<string> list)
{
    //start excel
    NsExcel.ApplicationClass excapp = new Microsoft.Office.Interop.Excel.ApplicationClass();

    //if you want to make excel visible
    excapp.Visible = true;

    //create a blank workbook
    var workbook = excapp.Workbooks.Add(NsExcel.XlWBATemplate.xlWBATWorksheet);

    //or open one - this is no pleasant, but yue're probably interested in the first parameter
    string workbookPath = "C:\test.xls";
    var workbook = excapp.Workbooks.Open(workbookPath,
        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
        true, false, 0, true, false, false);

    //Not done yet. You have to work on a specific sheet - note the cast
    //You may not have any sheets at all. Then you have to add one with NsExcel.Worksheet.Add()
    var sheet = (NsExcel.Worksheet)workbook.Sheets[1]; //indexing starts from 1

    //do something usefull: you select now an individual cell
    var range = sheet.get_Range("A1", "A1");
    range.Value2 = "test"; //Value2 is not a typo

    //now the list
    string cellName;
    int counter = 1;
    foreach (var item in list)
    {
        cellName = "A" + counter.ToString();
        var range = sheet.get_Range(cellName, cellName);
        range.Value2 = item.ToString();
        ++counter;
    }

    //you've probably got the point by now, so a detailed explanation about workbook.SaveAs and workbook.Close is not necessary
    //important: if you did not make excel visible terminating your application will terminate excel as well - I tested it
    //but if you did it - to be honest - I don't know how to close the main excel window - maybee somewhere around excapp.Windows or excapp.ActiveWindow
}

A: Using ClosedXML edit library( there is no need to install MS Excel
I just write a simple example to show you how you can name the file, the worksheet and select cells:
    var workbook = new XLWorkbook();
    workbook.AddWorksheet("sheetName");
    var ws = workbook.Worksheet("sheetName");

    int row = 1;
    foreach (object item in itemList)
    {
        ws.Cell("A" + row.ToString()).Value = item.ToString();
        row++;
    }

    workbook.SaveAs("yourExcel.xlsx");

If you prefer you can create a System.Data.DataSet or a System.Data.DataTable with all data and then just add it as a workseet with workbook.AddWorksheet(yourDataset) or workbook.AddWorksheet(yourDataTable);

A: You could output them to a .csv file and open the file in excel. Is that direct enough?

A: Using the CSV idea, if it's just a list of Strings.  Assuming l is your list:
using System.IO;

using(StreamWriter sw = File.CreateText("list.csv"))
{
  for(int i = 0; i < l.Count; i++)
  {
    sw.WriteLine(l[i]);
  }
}

A: Fast way - ArrayToExcel (github)
byte[] excel = myList.ToExcel();
File.WriteAllBytes("result.xlsx", excel);

A: The most straightforward way (in my opinion) would be to simply put together a CSV file. If you want to get into formatting and actually writing to a *.xlsx file, there are more complicated solutions (and APIs) to do that for you.

A: the one easy way to do it is to open Excel create sheet containing test data you want to export then say to excel save as xml open the xml see the xml format excel is expecting and generate it by head replacing the test data with export data
SpreadsheetML Markup Spec
@lan this is xml fo a simle execel file with one column value i genereted with office 2003 this format is for office 2003 and above
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Dancho</Author>
  <LastAuthor>Dancho</LastAuthor>
  <Created>2010-02-05T10:15:54Z</Created>
  <Company>cc</Company>
  <Version>11.9999</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>13800</WindowHeight>
  <WindowWidth>24795</WindowWidth>
  <WindowTopX>480</WindowTopX>
  <WindowTopY>105</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="6" x:FullColumns="1"
   x:FullRows="1">
   <Row>
    <Cell><Data ss:Type="String">Value1</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value2</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value3</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value4</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value5</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value6</Data></Cell>
   </Row>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>5</ActiveRow>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet2">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet3">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>

A: Depending on the environment you're wanting to do this in, it is possible by using the Excel Interop. It's quite a mess dealing with COM however and ensuring you clear up resources else Excel instances stay hanging around on your machine.
Checkout this MSDN Example if you want to learn more.
Depending on your format you could produce CSV or SpreadsheetML yourself, thats not too hard. Other alternatives are to use 3rd party libraries to do it. Obviously they cost money though.

A: List<"classname"> getreport = cs.getcompletionreport();

var getreported = getreport.Select(c => new { demographic = c.rName);

where cs.getcompletionreport() reference class file is Business Layer for App
I hope this helps.

A: I know, I am late to this party, however I think it could be helpful for others.
Already posted answers are for csv and other one is by Interop dll where you need to install excel over the server, every approach has its own pros and cons.
Here is an option which will give you

*

*Perfect excel output [not csv]

*With perfect excel and your data type match

*Without excel installation

*Pass list and get Excel output :)

you can achieve this by using NPOI DLL, available for both .net as well as for .net core
Steps :

*

*Import NPOI DLL

*Add Section 1 and 2 code provided below

*Good to go

Section 1
This code performs below task :

*

*Creating New Excel object - _workbook = new XSSFWorkbook();

*Creating New Excel Sheet object - _sheet =_workbook.CreateSheet(_sheetName);

*Invokes WriteData() - explained later Finally, creating and

*returning MemoryStream object

=============================================================================
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace GenericExcelExport.ExcelExport
{
    public interface IAbstractDataExport
    {
        HttpResponseMessage Export(List exportData, string fileName, string sheetName);
    }

    public abstract class AbstractDataExport : IAbstractDataExport
    {
        protected string _sheetName;
        protected string _fileName;
        protected List _headers;
        protected List _type;
        protected IWorkbook _workbook;
        protected ISheet _sheet;
        private const string DefaultSheetName = "Sheet1";

        public HttpResponseMessage Export
              (List exportData, string fileName, string sheetName = DefaultSheetName)
        {
            _fileName = fileName;
            _sheetName = sheetName;

            _workbook = new XSSFWorkbook(); //Creating New Excel object
            _sheet = _workbook.CreateSheet(_sheetName); //Creating New Excel Sheet object

            var headerStyle = _workbook.CreateCellStyle(); //Formatting
            var headerFont = _workbook.CreateFont();
            headerFont.IsBold = true;
            headerStyle.SetFont(headerFont);

            WriteData(exportData); //your list object to NPOI excel conversion happens here

            //Header
            var header = _sheet.CreateRow(0);
            for (var i = 0; i < _headers.Count; i++)
            {
                var cell = header.CreateCell(i);
                cell.SetCellValue(_headers[i]);
                cell.CellStyle = headerStyle;
            }

            for (var i = 0; i < _headers.Count; i++)
            {
                _sheet.AutoSizeColumn(i);
            }

            using (var memoryStream = new MemoryStream()) //creating memoryStream
            {
                _workbook.Write(memoryStream);
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(memoryStream.ToArray())
                };

                response.Content.Headers.ContentType = new MediaTypeHeaderValue
                       ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.Content.Headers.ContentDisposition =
                       new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"{_fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
                };

                return response;
            }
        }

        //Generic Definition to handle all types of List
        public abstract void WriteData(List exportData);
    }
}

=============================================================================
Section 2
In section 2, we will be performing below steps :

*

*Converts List to DataTable Reflection to read property name, your

*Column header will be coming from here

*Loop through DataTable to Create excel Rows

=============================================================================
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;

namespace GenericExcelExport.ExcelExport
{
    public class AbstractDataExportBridge : AbstractDataExport
    {
        public AbstractDataExportBridge()
        {
            _headers = new List<string>();
            _type = new List<string>();
        }

        public override void WriteData<T>(List<T> exportData)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();

            foreach (PropertyDescriptor prop in properties)
            {
                var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                _type.Add(type.Name);
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ??
                                  prop.PropertyType);
                string name = Regex.Replace(prop.Name, "([A-Z])", " $1").Trim(); //space separated
                                                                           //name by caps for header
                _headers.Add(name);
            }

            foreach (T item in exportData)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }

            IRow sheetRow = null;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                sheetRow = _sheet.CreateRow(i + 1);
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    ICell Row1 = sheetRow.CreateCell(j);

                    string type = _type[j].ToLower();
                    var currentCellValue = table.Rows[i][j];

                    if (currentCellValue != null &&
                        !string.IsNullOrEmpty(Convert.ToString(currentCellValue)))
                    {
                        if (type == "string")
                        {
                            Row1.SetCellValue(Convert.ToString(currentCellValue));
                        }
                        else if (type == "int32")
                        {
                            Row1.SetCellValue(Convert.ToInt32(currentCellValue));
                        }
                        else if (type == "double")
                        {
                            Row1.SetCellValue(Convert.ToDouble(currentCellValue));
                        }
                    }
                    else
                    {
                        Row1.SetCellValue(string.Empty);
                    }
                }
            }
        }
    }
}

=============================================================================
Now you just need to call
WriteData() function by passing your list, and it will provide you your excel.
I have tested it in WEB API and WEB API Core, works like a charm.

A: Pass List to "Write" Method, which will convert the list to buffer and return buffer, a file will be downloaded
byte[] buffer = Write(ListData, true, "AttendenceSummary"); return File(buffer, "application/excel", reportTitle + ".xlsx");

      public static byte[] Write<T>(IEnumerable<T> list, bool xlsxExtension, string sheetName = "ExportData")
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            XSSFWorkbook hssfworkbook = new XSSFWorkbook();
            int Rowspersheet = 15000;
            int TotalRows = list.Count();
            int TotalSheets = TotalRows / Rowspersheet;

            for (int i = 0; i <= TotalSheets; i++)
            {
                ISheet sheet1 = hssfworkbook.CreateSheet(sheetName + "_" + i);
                IRow row = sheet1.CreateRow(0);
                int index = 0;
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
                    IFont cellFont = hssfworkbook.CreateFont();

                    cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                    cellStyle.SetFont(cellFont);

                    ICell cell = row.CreateCell(index++);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(property.Name);
                }

                int rowIndex = 1;
                // int rowIndex2 = 1;

                foreach (T obj in list.Skip(Rowspersheet * i).Take(Rowspersheet))
                {

                    row = sheet1.CreateRow(rowIndex++);
                    index = 0;

                    foreach (PropertyInfo property in typeof(T).GetProperties())
                    {
                        ICell cell = row.CreateCell(index++);
                        cell.SetCellValue(Convert.ToString(property.GetValue(obj)));
                    }

                }
            }

            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file.ToArray();

        }


text:
Q: MySQL Error, what does it mean I am trying to update two columns in a xref database. I am getting this error message:
Cannot add or update a child row: a foreign key constraint fails (`globaldetroit`.`org_cult_xref`, CONSTRAINT `org_cult_xref_ibfk_1` FOREIGN KEY (`org_id`) REFERENCES `organization` (`org_id`) ON DELETE CASCADE ON UPDATE CASCADE)

I want to be able to have a many-many relationship, and these errors seem to prevent me from having one.
EDIT:
That is very odd! There most certainly is a column org_id with the value of "6" (as an integer) in the table organization! I just checked!

A: You are trying to set a value that has a foreign key constrant -- ie the key does not exist in the foreign table.
So globaldetroit's org_cult_xref references an org_id in organization that does not exist.

A: you're putting in field globaldetroit.org_cult_xref value not existing in organization.org_id

A: Many-many relationship is bad, don't go there.
Your error seems to be caused because the row you insert in org_cult_xref has a column org_id and the value you insert there cannot be found in the organization table.

A: You have a foreign key defined on the table you are trying to insert/update into, which basically says the value in org_id should exist in the organization  table, and it is not the case.


text:
Q: facebook comment box in asp.net using repeater I have a repeater which has two columns one column contains label and another has textbox.
on enter data in the text box it should show as label and another textbox in the same row should appear.i am getting a text box but not able to do as said above.Please help me.
 <asp:Repeater ID="RepDetails" runat="server" OnItemDataBound="RepDetails_ItemDataBound" >
    <HeaderTemplate>

                    Atrributes

    </HeaderTemplate>
    <ItemTemplate>

                            <asp:Label ID="lblAttributeName" runat="server" Text='<%#Eval("AttirbuteName") %>' Font-Bold="true" />

                            <asp:TextBox ID="txtAttributeNameDef" runat="server" ToolTip='<%#Eval("AttirbuteDefination") %>' Width="100%"></asp:TextBox>

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

A: You can do using repeater like this way DEMO

      Comment Box
        <button type="button" class="close" aria-hidden="true">×</button>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

        <asp:Repeater ID="RepDetails" runat="server"  >
            <ItemTemplate>

Hello this is a test comment.
 on March 5th, 2014

                </ItemTemplate>
            </asp:Repeater>

                <input class="form-control" type="text" id="txtcomment" placeholder="Your comments" />

                <button class="btn btn-default" id="postcomment">Add</button>


text:
Q: Spotify API Get user's queue endpoint I am trying to get the queue of the songs that are going to play of my account and use the "https://api.spotify.com/v1/me/player/queue" endpoint for my request. I keep getting only two songs and the other 18 songs I am supposed to get are undefined in the response. Does Spotify automatically shorten the response? How do I work around this?
const getRequest = {
        url: 'https://api.spotify.com/v1/me/player/queue',
        headers: {
            'Authorization': 'Bearer ' + token
        },
        json: true
    };

    request.get(getRequest, (error, response, body) => {
        if (body.queue === []) {
            res.send('Player is not playing and were not able to return queue');
        }
        let arr = [];
        var count = 0;
        for (let i = 0; i < 20; i++) {
            if (body.queue[i + ""] != undefined) {arr.push(body.queue[i + ""]);}
            else {count++;}
        }
        console.log(count);
        let newArr = [];
        for (let i = 0; i < arr.length; i++) {
            newArr.push(
                {
                    'id': arr[i].id,
                    'title': arr[i].name,
                    'icon': arr[i].album.images["0"].url,
                    'artist': arr[i].artists["0"].name,
                    'duration': arr[i].duration_ms,
                    'index': i+1
                });
        }
        console.log(newArr);
        res.send(newArr);
    });

I checked out the Spotify API Website but came to no conclusion.


text:
Q: How to create ssl context with HTTP Client with custom trust store and client store certificates? I am trying to create an SSL HTTP client (to send data over TLS) with custom trust store and client store certificates. I was able to do this in Java via OKHTTP, but I am confused how I can do this in C#/.net
Here is OKHTTP approach I used:
byte[] trustStoreBytes = ...
byte[] clientCertBytes = ...

TrustManagerFactory trustManagerFactory = null;
try
{
    trustManagerFactory = createTrustManagerFactory(trustStoreBytes, trustStorePass);
}
catch (Exception e)
{
    Log.e(TAG, "Exception initializing TrustManagerFactory.", e);
}
if (trustManagerFactory == null)
{
    Log.e(TAG, "TrustManagerFactory cannot be null.");
}

SSLContext sslContext = null;
try
{
    sslContext = createSSLContext(clientCertBytes, clientCertPass, trustManagerFactory);
}
catch (Exception e)
{
    Log.e(TAG, "Exception initializing SSLContext.", e);
}
if (sslContext == null)
{
    Log.e(TAG, "SSLContext cannot be null.");
}

SSLSocketFactory sslSocketFactory = null;
X509TrustManager trustManager = null;
try
{
    sslSocketFactory = sslContext.getSocketFactory();
    trustManager = getX509TrustManager(trustManagerFactory);

    Log.d(TAG, "newSecureWebSocketsClient: " + sslSocketFactory.getDefaultCipherSuites().toString());
}
catch (Exception e)
{
    Log.e(TAG, "Unable to create ssl socket factory or trust manager.", e);
}
if (sslSocketFactory == null)
{
    Log.e(TAG, "SSL Socket Factory cannot be null.");
}
if (trustManager == null)
{
    Log.e(TAG, "Trust manager cannot be null");
}

OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.sslSocketFactory(sslSocketFactory, trustManager);
clientBuilder.retryOnConnectionFailure(true);
clientBuilder.hostnameVerifier(new HostnameVerifier() {
                @Override

                public boolean verify(String hostname, SSLSession session)
{
    Log.i(TAG, "Hostname: " + hostname);
    Log.w(TAG, "Hostname verification is disabled. If you are using DNS," +
            " this could introduce security risks for you.");
    return true;
}
            });

return clientBuilder.build();

Here is my initial attempt with System.Net.Http.HTTPClient
HttpClient client = new HttpClient();
WebRequestHandler handler = new WebRequestHandler();

X509Certificate2 cert = new X509Certificate2(clientBytes, "password");
handler.ClientCertificates.Add(cert);
handler.ClientCertificates.Add( ??? );

I could add a trust store certificate to the ClientCertificates but that seems wrong. What is the right approach here? Thanks!


text:
Q: Handling a large ADODB record set in data table? I am loading a large result set of about 3 million rows (ADODB record set) into a data table. Its taking too long to even load the result set into a data table. I want to find out a way of extracting only part of a result set and then loading it into a DataTable. Alternatively, is there a way to directly read the recordset directly instead of loading it into a data table and then reading it ?
This is the code I use to fill my DataTable -
OleDbDataAdapter oleDA = new OleDbDataAdapter();
DataTable dt = new DataTable();
oleDA.Fill(dt, myADODBRecordset);

A: Here are some options to consider:

*

*Get only the rows and columns you really need to work with.

*Get some data and let the user ask for the next set of rows when they want to.

*Write optimized SQL queries

*Don't use a DataTable unless you have to because it contains more metadata information that other list-type objects.

*Consider using a managed .NET provider.

A: Why load so large data into memory? A large data transaction must comsume large resource, so optimize your code, or use EF.


text:
Q: Send email attachment from php and upload ftp Here I'm able to upload received file (file doesn't have known name, it was created with current date and time) into FTP. And in the same way I want to send that attachment as a mail.
The error I'm getting is (from the last statement in the below code):

file open error.

I was not able to select the file received into php while sending mail. can someone tell me why and how?
$destDir = 'myweb.net/name/' .$dir;
 $workDir = 'tmpfiles';// define this as per local system

 // get temporary file name for the uploaded file
$tmpName = basename($_FILES['uploadedfile']['tmp_name']);
$fileName = basename($_FILES['uploadedfile']['name']);

// copy uploaded file into current directory
move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$workDir."/".$tmpName)
 or die("Cannot move uploaded file to working directory");

// open connection
$conn = ftp_connect($ftp_server) or die ("Cannot initiate connection to host");

// send access parameters
ftp_login($conn, 'abcd', 'saddad') or die("Cannot login");

// perform file upload
$upload = ftp_put($conn, $destDir."/".$_FILES['uploadedfile']['name'],$workDir."/".$tmpName, FTP_BINARY);

// check upload status
// display message
if (!$upload) {
 echo "Cannot upload<br />\n";
} else {

 $to = $Remail;
 $subject = "This is subject";
 $message = "This is test message.";
// Open a file
 $file = fopen($_FILES['uploadedfile']['name'], "r" );
 if( $file == false )
  {
 echo "Error in opening file";
 exit();
 }

A: You're trying to open the ORIGINAL client-side filename, which has absolutely NO relationship to anything on your server. The only file that exists on your server is the one listed in ['tmp_name'], which you've now moved to $workdir.
Your fopen should be
$file = fopen($workDir . '/' . $tmpName, 'r');

Plus, you have absolutely NO error handling on the user->webserver upload stuff, and are simply ASSUMING that uploads could never fail. Bad assumption.


text:
Q: Search text with and without special characters in a column I am running the below query:
select *
from db.table
where text ilike '%driver needs car%'

I am returning the results with the exact given words 'This cool driver needs car now' but I want to include also special character if there are exist like this 'This cool driver, needs: car now'. Is it possible to search also for these special characters ?

A: You can use REGEXP_REPLACE to remove all non-alphanumeric characters.
select *
from db.table
where regexp_replace(text, '[^a-zA-Z0-9]', '') ilike '%driver needs car%'


text:
Q: How should I calculate the time that the player has spent away from the app? In the game I'm making in Android Studio, I want to have an object that erodes over time. Once the object is fully eroded, the player can bust it for points. I want this time value to be based on real world time so that the item continues to erode while the app is closed.
What would be the best way to accomplish this? Should I use Date variables, or can I get away with something simpler?

A: There is a pretty easy approach you can use via sharedprefrences and service, when app got killed save the time date variable and when user came back to your app, you can check the value against your saved key, if it is not null compare it with your current time and get the difference between both. That is how you can get that.

A: When the object starts eroding, save the time :
long startTime = SystemClock.elapsedRealtime();
In your onPause(), save this time:
public void onPause() {
    SharedPreferences.Editor editor = getSharedPreferences("myPrefs", MODE_PRIVATE).edit();
    editor.putLong("startTime", startTime );
    editor.commit();
    super.onPause();
}

In your onResume(), get the saved time and compare with current time:
public void onResume() {
    SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
    long startTime =  prefs.getLong("startTime", 0);
    long elapsedTime = SystemClock.elapsedRealtime() - startTime;

    if (elapsedTime > EROTION_TIME) {
        // Voila !! The object has eroded.
    }
}


text:
Q: value is neither an array nor a pointer I have this code:
int ID [STUDENTS];
int Scores [STUDENTS][GRADES];
int Hi [GRADES];
int Lo [GRADES];
double Avg [GRADES];
int numStudents;

/*getData function called*/
int getData(ID, Scores,  numStudents)
{
  int student_count;
  int quiz_count;

  FILE* spIn;

  spIn = fopen("myfile.dat", "r");
  student_count=0;
  while (fscanf (spIn, "%d", ID[student_count]) != EOF)
  {
     for (quiz_count = 0; quiz_count < GRADES; quiz_count++)
     {
        fscanf (spIn, "%d", Scores[student_count][quiz_count]);
     }
  }
}

I keep getting the error in title for the lines: while(fscanf (spIn, "%d", ID[student_count]) !=EOF) and fscanf (spIn, "%d", Scores[student_count][quiz_count]);
Please help I don't know what to do!

A: Both instances of fscanf() are incorrect. fscanf() needs pointers, not ints, to modify the memory at that location.
Your first call is this:
while (fscanf (spIn, "%d", ID[student_count]) != EOF)

When you index the variable ID you're passing the value of the student_count index to the function. Which fscanf() tries to interpret as a memory location(Not good)!
This:
while (fscanf (spIn, "%d", &ID[student_count]) != EOF)

passes the reference of the array at index student_count to fscanf().
The same is true of the other call to fscanf()!

A: The problem is with the scope of variables ID and Scores. Both variables are defined in two places -

*

*As a global variable at the top of the file, and

*As a named parameter to your function.

The named parameter is closer in scope to the place of use, hence it wins.
It looks like the use in the second place (i.e. as function parameter) is not intentional, because the declarations lack types*. Removing them will make your code compile.
* in which case C considers them ints, and issues a warning which should have explained the error to you: since the compiler thinks that the inner-scope ID and Score are ints, you cannot use index operator [] with them.


text:
Q: How can I write to a specific location in Windows Phone 8 When I press a button, I want it to overwrite a file to a specific folder.
I use this code:
private void btnArial_Click(object sender, RoutedEventArgs e)
    {
        string cssDocument = "body{font-family:\"Arial\";}";

        //I want to write file style.css to folder css inside html
        string path = Package.Current.InstalledLocation.Path + "\\Html\\css\\style.css";
        if (File.Exists(path))
        {
            StreamWriter writer = new StreamWriter(path);
            writer.Write(cssDocument);
            writer.Close();
        }
        changeStyle(new FontFamily("Arial"));
    }

When I tested on emulator and actual devide, it worked properly.
But when I submit app to store, it got error - the app exits when I press that button.

A: The install directory (Package.Current.InstalledLocation) is a read-only location. Unfortunately, due to the way that Visual Studio optimizes development-time deployment, it is set to read-write when the app is deployed from VS. That's why you see a difference in behavior after you submit the app to the store.
If you need to modify a file in your install directory, you must first copy it over to a writeable location - eg. your Local folder.

A: I prefer using Isolated storage in WP8 to write files and it never fails. Also you can use Windows.Storage apis.
    private async void MyButton_Click(object sender, RoutedEventArgs e)
    {
        string cssDocument = "body{font-family:\"Arial\";}";

        // using Windows.Storage
        StorageFolder folder = ApplicationData.Current.LocalFolder;

        folder = await folder.CreateFolderAsync("HTML", CreationCollisionOption.OpenIfExists);

        folder = await folder.CreateFolderAsync("CSS", CreationCollisionOption.OpenIfExists);

        StorageFile file = await folder.CreateFileAsync("style.css", CreationCollisionOption.ReplaceExisting);

        using (var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
        {
            writer.Write(cssDocument);
        }

        // using using System.IO.IsolatedStorage;
        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (!store.DirectoryExists("HTML/CSS"))
                store.CreateDirectory("HTML/CSS");

            using (var writer = new StreamWriter(store.OpenFile("HTML/CSS/style.css", FileMode.Create)))
            {
                writer.Write(cssDocument);
            }
        }

        changeStyle(new FontFamily("Arial"));
    }

A: Exactly..
Write the file in Isolated storage. Its easier and pretty straight forward. The files here can be accessed, viewed, modified, removed, replaced in a very clear way. I personally prefer the Isolated Storage.


text:
Q: Is there a server distro with the capability of syncing live data to multiple machines? Scenario: I have a main server that is used for pagebuilding/storing master data, and is accessed by a few clients on site. This company also has multiple branches with their own server that that connect to locally, but need to work with all the same data, and have it synchronized across all servers in real (or close) time. Is there a way/specific server OS that can sync live data across all of these servers? These servers would also need to be able to:

*

*Configure AFP, FTP, CIFS, SMB

*Continue to host their web server and database server in a Microsoft environment, but move the file server off to commodity hardware

Just wondering if this is even possible.

A: I believe this is something that Windows dfs can solve for you. I know you tagged this linux, but you also mention a Microsoft environment is available. Samba can be made to work with DFS if you still want a Linux environment for this role, but native Windows servers will be able to fulfill your requirements.

A: I think you're talking about (reasonably) static web pages. I can think of several ways to do file transfers, depending on your exact requirements and network environment. If you're really talking about database instances, my ideas would be different.

*

*If all of your servers can be fooled into thinking they're on the same LAN, consider setting up a shared NFS or GFS2 filesystem.

*If your servers are distant from each other and your synchronization doesn't need to be truly real-time, consider a cron job using wget -r.

*I can also think of several command sequences that could be automated to work in near real-time.
Having suggested those, your questions also implies you're looking for an OS that keeps itself backed up in real time? Then, maybe you do an automatic restore to the other hosts? I'm not aware of any simple ways to do that.
Good luck!


text:
Q: How can I get the "My Music" folder back in Windows 7 after deleting it? I don't know why, but I deleted the My Music folder in the My Documents directory  It's not in the Recycling Bin, and I didn't have anything in it as yet, but would like to get it back.
Does anyone have suggestions on how to get the folder back?

A: Amanda, you wrote:

I deleted the "my music" folder from
my documents. Its not in the recycling
bin.

You also say that you have Windows 7. This strikes me as a bit odd, as the "My Music" folder is not in the "My Documents" folder, but at the same level. In other words, assuming that your Windows username is amanda, then you should see two folders with the path:

C:\Users\amanda\Music
C:\Users\amanda\Documents

I suspect that what you've actually done is to remove the "My Music" entry from the Libraries hierarchy in the Windows Explorer. This doesn't put any folders into the Recycle Bin, it just deletes the entry from the Libraries.
To put it back, just right-click on the Music library icon, choose Properties, and in the Properties window click the "Include a folder..." button to include C:\Users\amanda\Music back into the Library view.


text:
Q: How to solve this Android SQLite Room DAO error message? I don't know what's wrong with below problem?
Code:
CategoryDAO.kt
@Dao
interface CategoryDAO {
    @Query("select * from CategoryDesign")
    suspend fun getCategory(): MutableLiveData<List<CategoryDesign>>

}

CategoryDesign.kt
@Entity
data class CategoryDesign (
    @PrimaryKey
    var categoryDesignID:String,
    var designImage:String,
    var designTitle:String){
    constructor() : this("","","")

    override fun toString(): String {
        return designTitle
    }
}

Press Run App button will show error like below:
error: Not sure how to convert a Cursor to this method's return type (androidx.lifecycle.MutableLiveData<java.util.List<com.squall.searchdesigner.model.CategoryDesign>>).
    public abstract java.lang.Object getCategory(@org.jetbrains.annotations.NotNull()

w: [kapt] Incremental annotation processing requested, but support is disabled because the following processors are not incremental: androidx.room.RoomProcessor (DYNAMIC), android.databinding.annotationprocessor.ProcessDataBinding (DYNAMIC).

dependencies:
dependencies {
    def room_version = "2.2.3"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
}

A: It's seems like you can use only LiveData return type. Maybe Room not allows you to use MutableLiveData?

A: Thank you all.
I used below code and rebuild project and invalidate caches seems solve this problem.
@Dao
interface CategoryDAO {
    @Query("select * from CategoryDesign")
    fun getCategory(): LiveData<MutableList<CategoryDesign>>

}