text:
Q: Random white column to the right of web page I am currently using HTML and CSS to modify my library's libguides2 homepage.  For some reason there is a phantom white column that is showing up on the right side of the page.  It's there in Chrome, Firefox, and Safari.  It does NOT show up on IE.  It doesn't show up when the page loads, but if you scroll to the right on desktop or zoom out on mobile, there it is.
Here's a screenshot:

Here's the live site:
http://nybg.beta.libguides.com/
And here's my fiddle:
https://jsfiddle.net/pjp5rxws/
The white space isn't in the fiddle, but Springshare support (the people who make and host libguides) says that it's not something in the code for the page that I can't get at.
Any ideas?  This issue is not the end of the world, but I would like to understand and fix it if possible!
And I know that my css should be in a separate document although it is not yet in a separate document--the site is set up in such a way that this is how I am managing my beta version for the time being. I do plan to move the css!
I'm not sure what of my code is helpful here, so here is my css:
* {
  margin: 0;
  padding: 0;
  outline: none;
  -webkit-box-sizing: border-box;
  - moz-box-sizing: border-box;
  box-sizing: border-box;
}
*:after,
*:before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
nav,
section {
  display: block;
}
html {
  font-size: 100%;
  height: auto !important;
  height: 100%;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
}
.clear {
  display: block;
}
.clear::after {
  clear: both;
  content: ".";
  display: block;
  height: 1px;
  visibility: hidden;
}
html,
body {
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}
mobilenav {
  display: none;
  width: 100%;
  z-index: 1000;
  background-color: #000000;
  text-align: center;
}
mobilenav div {
  width: 100%;
}
mobilenav a {
  color: #ffffff;
  letter-spacing: 0.0625em;
  font-weight: bold;
  text-transform: uppercase;
  display: block;
  text-decoration: none;
  text-align: center;
  padding: 1rem;
}
mobilenav a:hover {
  color: #DADADA;
  text-decoration: none;
}
mobilenav > nav > ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  list-style: none;
  margin: 0;
  padding: 0;
}
mobilenav > nav > ul:hover {
  background-color: #000000;
}
mobilenav > nav > ul > li {
  flex: 0 1 auto;
  margin: 0;
  padding: 0;
  position: relative;
  width: 100%;
  transition: all linear 0.1s;
}
mobilenav > nav > ul > li a + div {
  display: none;
  position: absolute;
}
mobilenav > nav > ul > li:hover a + div {
  display: block;
  background-color: #000000;
}
mobilenav > nav > ul > li a + div > ul {
  list-style-type: none;
}
mobilenav > nav > ul > li a + div > ul > li {
  margin: 0;
  padding: 0;
}
mobilenav > nav > ul > li a + div > ul > li > a {
  display: block;
  padding: .25rem 1.5rem;
  text-decoration: none;
}
mobilenav > nav > ul > li > a {
  align-items: flex-start;
  display: flex;
  padding: 1rem 1.5rem;
  text-decoration: none;
}
.container {
  display: flex;
  padding: 1% 0;
}
.headerimage {
  display: flex;
  align-content: center;
  align-items: center;
  padding: 0 2%;
}
.headerimage img {
  width: 100%;
  padding-right: 50px;
}
.logoname {
  text-transform: uppercase;
  flex-flow: row;
}
.fullpage {
  background-color: #ffffff;
}
.menu {
  background-color: #000000;
}
.site-navigation ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  flex-direction: row;
  flex-wrap: wrap;
}
.site-navigation a {
  color: #ffffff;
  letter-spacing: 0.0625em;
  font-weight: bold;
  text-transform: uppercase;
  display: block;
  text-decoration: none;
  text-align: center;
  padding: 1rem;
}
.site-navigation a:hover {
  color: #DADADA;
}
.fullpagesnh {
  background: url(https://s3.amazonaws.com/libapps/accounts/69823/images/IVO_2541_LARGE.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
.fullpagesnh h2 {
  color: #ffffff;
}
.fullpagesnh a {
  text-decoration: none;
  color: #ffffff;
}
.fullpagesnh a:hover {
  color: #ffffff;
  text-decoration: underline;
}
.snhcontainer {
  display: flex;
  justify-content: center;
}
.searchandhours {
  flex-direction: row;
  display: flex;
  align-items: center;
}
.librarysearch {
  margin: 100px 0 100px 0;
  padding: 20px;
}
.fullpagesnh form {
  padding: 20px;
  background-color: rgba(0, 0, 0, .75);
}
.hours ul {
  padding: 20px;
  margin-left: 50px;
  background-color: rgba(0, 0, 0, .75);
  color: #ffffff;
  list-style: none;
}
.contentcontainer {
  background-color: #ffffff;
  padding-top: 100px;
}
.row {
  display: inline-block;
}
.sideblack {
  margin: 5% 2.5%;
  margin-bottom: 50px;
  padding: 20px;
  background-color: #000000;
  color: #ffffff;
  text-transform: uppercase;
  text-align: center;
  font-size: larger;
  font-weight: bold;
}
.sideblack:hover {
  color: #000000;
  background-color: #ffffff;
}
.Special_box {
  margin: 5% 2.5%;
  border: 1px solid #CECECE;
  word-wrap: break-word;
}
.Special_box h2 {
  color: #000000;
}
.Special_box p {
  color: #999AA9;
  font-weight: bold;
}
.Special_box:hover {
  background-color: #CECECE;
}
.Special_box a {
  color: #ffffff;
}
.Special_box .bottom {
  padding: 10px;
}
.Special_box img {
  width: 100%;
  margin: 0;
  padding: 0;
}
.libguidescontent .row {
  padding: 0;
  margin: 0;
  width: 100%;
}
.nav.nav-pills button.btn {
  background-color: #ffffff !important;
  color: #000000 !important;
}
.libguidescontent .alert {
  background-color: #F5F5F5;
  border: none;
}
.libguidescontent h1 {
  padding-top: 50px;
  padding-bottom: 25px;
}
.libguidescontent a {
  color: #000000;
}
.libguidescontent strong {
  color: #26B56E;
}
.whitespace {
  height: 200px;
}
.footfoot {
  background-color: #000000;
}
.foot-navigation ul {
  display: flex;
  list-style: none;
  margin: 0;
  padding-bottom: 40px;
  display: flex;
  justify-content: center;
  flex-direction: row;
  flex-wrap: wrap;
}
.foot-navigation ul li {
  padding-right: 50px;
  color: #ffffff;
  font-weight: bold;
}
.foot-navigation ul li h3 {
  font-size: 16px;
  color: #ffffff;
  text-transform: uppercase;
  font-weight: bold;
  margin-bottom: 0;
}
@media only screen and (max-width: 1024px) {
  .Special_box img {
    display: none;
  }
  .sideblack {
    display: none;
  }
}
@media all and (max-width: 600px) {
  mobilenav {
    display: block;
  }
  .contentcontainer {
    padding: 0;
  }
  .headerimage img {
    width: 200px;
    padding-right: 30px;
  }
  .headerimage h1 {
    font-size: 14px;
    word-wrap: normal;
    font-weight: 600;
  }
  .site-navigation ul {
    flex-flow: column wrap;
    padding: 0;
  }
  .foot-navigation ul {
    flex-flow: column wrap;
    padding-left: 20px;
  }
  .searchandhours {
    flex-flow: column wrap;
    padding-left: 20px;
  }
  .librarysearch {
    margin: 0;
  }
  .libraryhours {
    display: none;
  }
  body {
    margin: 0;
  }
  .menu {
    display: none;
  }
}

A: In your .contentcontainer div, you have multiple .row elements with negative left and right margins :
.row {
    margin-right: -15px;
    margin-left: -15px;
}

You might want to give your .contentcontainer some padding of the opposite value :
.contentcontainer {
    padding-left: 15px;
    padding-right: 15px;
}

A: Removing the margin for row solved the issue.

See Attached for reference.

A: overflow-x: hidden;

add that to the css of the html
html, body {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    margin: 0px;
    padding: 0px;
}

A: Thank you so much, all!  Many good solutions.  Here is another I got back from the Springshare Lounge group:
Hi Esther,
It looks like the main section of your page is using Bootstrap columns (the part in ). However, it's not in a container or container-fluid, so the appropriate sizing isn't being applied. I'd suggest changing your code just a tiny bit:

That should do it!
Best,
Carrie, Springshare Support


text:
Q: retrieve password from Thunderbird 17 I'm using T-bird 17.0.8. I need to retrieve the password Thunderbird is using to
 connect to my email account because I have forgotten it. This link seems to
explain the solution, but that's for an older version of Thunderbird and I can't find
the 'option' link in the 'Tools' menu no more.

A: You'll find it under Edit -> Preferences -> Security -> Passwords -> Saved Passwords -> Show Passwords. Click Yes at the prompt to show the passwords.

A: The given menu path is probably valid for Thunderbird on Windows. There, the menu item for accessing the settings / options dialog is traditionally in the "Tools" menu. On Linux, this menu item is traditionally in the "Edit" menu. Don't ask me why, if I remember correctly this convention reaches back to the late 90s at least.
So just open Thunderbird's settings dialog, wherever the menu item may be found ;) From there, you can go as described in mozillaZine's forum.

A: Ubuntu 14.04
Thunderbird 60.6.1 (32-bit)
Very top menu bar on desktop -
Edit > Preferences
Pop-up appears - with Security (padlock icon) highlighted.  In same dialog box, click "Saved Passwords" - righthand side, about a quarter of the way down
"Saved logins" pop-up should appear.
Lower righthand corner - click "Show Passwords"
Dialog box should appear as pop-up - "Are you sure you wish to show your passwords?"
Above instructions tested 11 September 2019

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to represent fractional power in unicode? I want to represent a mathematical formula/equations in Unicode for my WPF Application. I am able to represent all sorts of mathematical symbol using only unicode but now one of my equation has a fractional power And I stuck because i am not able to find how to represent the Fraction in power.
9 X 3² + 3(8)^2/3

How 2/3 will be superscripted ? I want a pure UNICODE solution.

A: e.g. 8³ᐟ⁴
afaict, ᐟ is not "semantic", like ⁺ and ⁻ are, but it looks right.

The Unified Canadian Aboriginal Syllabics and its Extended blocks contain several mostly consonant-only letters to indicate syllable coda called Finals, along with some characters that indicate syllable medial known as Medials: Main block ᐜ ᐝ ᐞ ᐟ ᐠ ᐡ ᐢ ᐣ ᐤ ᐥ ᐦ ᐨ ᐩ ᐪ ᑉ ᑊ ᑋ ᒃ ᒄ ᒡ ᒢ ᒻ ᒼ ᒽ ᒾ ᓐ ᓑ ᓒ ᓪ ᓫ ᔅ ᔆ ᔇ ᔈ ᔉ ᔊ ᔋ ᔥ ᔾ ᔿ ᕐ ᕑ ᕝ ᕪ ᕻ ᕽ ᖅ ᖕ ᖖ ᖟ ᖦ ᖮ ᗮ ᘁ ᙆ ᙇ ᙚ ᙾ ᙿ, Extended block ᣔ ᣕ ᣖ ᣗ ᣘ ᣙ ᣚ ᣛ ᣜ ᣝ ᣞ ᣟ ᣳ ᣴ ᣵ. Additionally, there are two Finals, a Medial, and two punctuations written as raised characters in the main block: ᐀ ᐧ ᕀ ᕁ ᕯ.

https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts#Other_superscript_and_subscript_characters
https://en.wikipedia.org/wiki/Superscripts_and_Subscripts_(Unicode_block)#Block


text:
Q: Storing Settings for C#? I have looked at the other posts, but this question is different than them.
I want to store 3 values of data (Type, String, String), how would I be able to do this?
An example of it would be: String, "lol", "lol2".
I've tried both the resource settings and settings settings, but neither work. They both say the name can't be doubled.
This is for a Windows Form
Any help would be appreciated thanks.
And I HAVE to HAVE it in this order. Because when someone selects the method "String" from the drop-down list I have, it shows everything that has the type of String including "lol". And then lol2 should be put in a textbox after selecting the 'lol" string.

A: Search for the IsolatedStorage class. This one is sux =).
But if you are using Silverlight, then you may use IsolatedStorageSettings class which is awesome!

A: Settings.settings works. However it sounds like you would be better off making your own serialization format for this type of data. Keep in mind that the Settings.settings class is good for trivial user and application settings. Nested, complex, or large structures that can change should use an application specific format. Use settings.settings for window locations and color preferences (as an example).

A: Another option would be to create and manage your own settings file. Here is a sample to get you started. First you create a class to represent the data you want to store, CustomDataStoreItem. Then create another class to hold a collection of those CustomDataStoreItems:
[Serializable()]
class CustomDataStore
{
    public CustomDataStore()
    {
        //This is required by serialization
    }
    private List<CustomDataStoreItem> _items;

    public List<CustomDataStoreItem> Items
    {
        get
        {
            if (_items == null)
                _items = new List<CustomDataStoreItem>();
            return _items;
        }
        set { _items = value; }
    }

    public void LoadSettings(string SettingsFileName)
    {
        if (File.Exists(SettingsFileName))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream fs = File.OpenRead(SettingsFileName);
            CustomDataStore ds = (CustomDataStore)bf.Deserialize(fs);
            fs.Close();
            _items = ds.Items;
        }
    }
    public void SaveSettings(string SettingsFileName)
    {
        if (File.Exists(SettingsFileName))
            File.Delete(SettingsFileName);
        BinaryFormatter bf = new BinaryFormatter();
        FileStream fs = File.Create(SettingsFileName);
        bf.Serialize(fs, this);
        fs.Close();
    }
}
[Serializable()]
class CustomDataStoreItem
{
    public CustomDataStoreItem()
    {
        //This is required by serialization
    }
    public string Type { get; set; }
    public string String1 { get; set; }
    public string String2 { get; set; }
}

Now you can make use of this class like so:
To save settings add CustomDataStoreItems to the CustomDataStore.Items collection. Then call the SaveSettings method:
CustomDataStore ds = new CustomDataStore();
CustomDataStoreItem dsi = new CustomDataStoreItem();
dsi.Type = "String";
dsi.String1 = "lol";
dsi.String2 = "lol2";
ds.Items.Add(dsi);
ds.SaveSettings(@"C:\Users\Public\Test.bin");

You can load the settings back out like this:
CustomDataStore ds = new CustomDataStore();
ds.LoadSettings(@"C:\Users\Public\Test.bin");
foreach (CustomDataStoreItem dsi in ds.Items)
 {
  Console.WriteLine(string.Format("{0} {1} {2}", dsi.Type, dsi.String1, dsi.String2));
 }


text:
Q: How many terms in a linear polynomial?
A linear polynomial can have a maximum of two terms.

My textbook states this but I can find a linear polynomial of more than 2 terms.
Like $2x + \pi + \sqrt{2}$
Since there are infinite irrationals and we cannot simplify them by adding together then I can have polynomials of any type with as any terms as I like.
And if you say that constants can't be considered terms. Then it is also not the case :-
As $2x + 7$ is considered as a polynomial of 2 terms by the same book. I think it's the same in all books.
So is the statement that a polynomial can have a maximum of two terms. false?

A: It depends on what you define as term.
If one were to define it "naively" as number of occurring summands then this would not make a good definition, as
$$2x+4=x+x+1+1+2+0$$
and thus it's not clear if $2x+4$ would have $2$ or $5$ terms.
Here my best guess is that the number of terms is counted as usual: when the polynomial is represented canonically as
$$a_nx^n+a_{n-1}x^{n-1}+\dots+a_1x+a_0$$
then the number of non-zero $a_i$ is the number of terms.
In particular a linear polynomial, being of the form
$$a_1x+a_0$$
can have at most two terms.

A: A term in a polynomial is defined to be a non-negative power power of $x$ (i.e., $1$ or $x$ or $x^2$ etc.) multiplied by a constant.
What you are running into is an issue of whether you are referring to terms in a polynomial or terms in a representation of a polynomial.
So the representation $2x+\pi+\sqrt{2}$ has 3 terms ($2x$, $\pi$, and $\sqrt{2}$), but the constant part, $\pi+\sqrt{2}$, is just a real number and so the polynomial $Ax+B$ really only has 2 terms: $Ax=2x$ is a term and $B=(\pi+\sqrt{2})$ is its other term.
You could think of this as the difference between unsimplified vs. simplified answers.
While I can represent a linear polynomial with as many terms as a like, a linear polynomial has at most two terms. For example: The representation $5x+4x+3x+2+1$ has 5 terms, but this polynomial simplifies to $12x+3$ and as a polynomial only has two terms.
Language isn't already used in a precise way. Another example, akin to what you're dealing with is someone might say the fraction $6/12$ has the numerator $6$. But a fraction doesn't have a numerator. More precisely, a representation of a fraction has a numerator. The fraction $6/12=1/2$. Is this fraction's numerator $6$ or $1$? On the other hand, the representation $6/12$ has numerator $6$ and the representation $1/2$ has numerator $1$.


text:
Q: Why doesn't my procedure work? I can't figure out why :(
I have to update the table products when I call the the procedure with the parameters(reference_requested, quantity_requested) and "return" (I don't how to do it, i read about return and params in, out and inout, but i didn't understand very well) the value of units sold
delimiter &&
create procedure compra (@reference_requested varchar, @quantity_requested int)
begin
  if quantity >= quantity_requested then
    update products
    set quantity = quantity - quantity_requested
    where reference_requested = reference;
    return quantity_requested;
  else
    return quantity;
    update products
    set quantity = 0;
    where reference_requested = reference;
  end if;
end
&&

A: Edit: As was pointed out in the comments, you cannot return a value (or use a return statement) in a procedure. If you're looking to do that, then you should use "create function" and not "create procedure" and additionally specify a return data type.
In your "else" the "return quantity" statement should be last, right before "end if" or the update will not run.

A: *

*It is important to indicate the difference between 9.4. User-Defined
Variables (@quantity_requested) and routine parameters (quantity_requested) 13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax, are different   variables.
Try:
   ...
   create procedure compra(reference_requested varchar(50), quantity_requested int)
   ...

*

*Does the statement:

   ...
   where reference_requested = reference;
   ...

reference_requested refers to the parameter or column in the table?. Avoid the names of
   the parameters/variables are equal to the columns of the tables, this can lead
   to problems.

*

*The RETURN:

   ...
   return quantity;
   ...

is used in functions for stored procedure is not used.

A: *

*To return a value from a stored procedure use an OUT parameter.

*Besides issues that have been already mentioned you can't just arbitrarily address quantity column in products table. It should be used in a context of some statement (e.g. SELECT).

Now a streamlined version of your procedure might look something like
DELIMITER $$
CREATE PROCEDURE compra
(
  IN  _ref_requested VARCHAR(32),
  IN  _qty_requested INT,
  OUT _result INT
)
BEGIN
  DECLARE qty INT DEFAULT 0;

  SET qty =
  (
    SELECT quantity
      FROM products
     WHERE reference = _ref_requested
     LIMIT 1
  );

  SET qty = IF(qty > _qty_requested, _qty_requested, qty);

  UPDATE products
     SET quantity = quantity - qty
   WHERE reference = _ref_requested;

  SET _result = qty;
END$$
DELIMITER ;

To be able to get the value of an OUT parameter you have to use a user variable
SET @result = NULL;
CALL compra('REF001', 25, @result);
SELECT @result;

Here is SQLFiddle demo


text:
Q: Twillio Call Screening - Dial stops ringing I am using twilio's call screening / whisper example. So basically when we use the Dial verb to call the number, we want to play a message when the receiver picks up the phone and give them the option to accept/reject the call. While the caller should keep hearing the ringing tone until the receiver makes a choice.
Most of this works as expected if we follow what's described in the call screening example https://www.twilio.com/docs/howto/callscreening
The problem is as soon as the receiver picks the phone, the caller can no longer hear the ringing tone, and the call goes silence until we have a response back from the receiver. This is a huge problem, because the caller will probably hang up once the ringing tone stops and there is no answer.
I have already had a look at the following two answers.
Twillio Call Screening silence on answer
Detecting when call had been answered using Dial verb
I personally don't want to go down the conference route.
In Number verb's documentation its clearly mentioned that the caller will continue to hear ringing tone.
https://www.twilio.com/docs/api/twiml/number#attributes-url

The 'url' attribute allows you to specify a url for a TwiML document that will run on the called party's end, after she answers, but before the parties are connected. You can use this TwiML to privately play or say information to the called party, or provide a chance to decline the phone call using Gather and Hangup. The current caller will continue to hear ringing while the TwiML document executes on the other end. TwiML documents executed in this manner are not allowed to contain the Dial verb.

The same issue happens with the Find Me Twimlet as well.
twilio.com/labs/twimlets/findme

A: Contacted Twilio support, you'll need to set "ringTone" attribute on  like this:
<Dial answerOnBridge="true" ringTone="us">

I have tried that and it worked for me.


text:
Q: What is preferred for file I/O in Java? Of the three

* BufferedReader/Writer

* Binary Streams

* Channels
which is more preferred in real life for file I/O in Java and why?
I prefer channels for binary data to be put into file or read from and BufferedReader/Writer for String data

A:
which is more preferred in real life for file I/O in Java and why?

It should really be a matter of function rather than preference.

*

*You use Readers and Writers for character oriented data (which requires encoding and decoding), Input/OutputStreams for byte-oriented data, and Binary streams if the data encodes binary data.

*You use the BufferedXxx classes if you need to I/O at the granularity of a character or byte.  They are a simple way to avoid the serious performance problems that can occur if you do lots of byte-at-a-time read and write syscalls.

*If you only do I/O by reading / writing large chunks, then the BufferedXxx classes might might actually reduce throughput a bit.  You can either use plain readers/writers/streams (with big char[] or byte[] buffers), or Channels and XxxBuffers.  The latter are potentially faster, but the APIs are more awkward.

*You use Channels if you need low overheads, and/or do specialised things such as "selecting" from multiple streams, scatter / gather, and memory mapped file access.
As you can see, the different APIs is designed for different purposes.  In some use-cases there is overlap, in others only one API is fit for the purpose.

The problem with developing a "preference" for one style of I/O over another is that it leads to bad software; i.e. either code that is inefficient where I/O efficiency is needed, or overly complicated where I/O efficiency should not be a concern.

A: The answer is "It depends" - Buffered, Streaming, Blocking and Non-blocking I/O are all used for different purposes depending on what concurrency, throughput and other performance characteristics that you're after.

A: java.io uses Streams while java.nio use Channels and buffer, The most important distinction between java.io way and java.nio way is, how data is packaged and transmitted.java.io deals with data in streams (one byte at a time), whereas java.nio deals with data in blocks.
Processing data by the block can be much faster than processing it by the (streamed) byte but it is not as easy as streams.
In these situation, it is better to use java.io way:

*

*Files may be large but not huge. It's possible to read an entire file into memory.

*An application reads from or writes to only a few files or network connections at the same time, ideally using only one stream at a time.

*The application is sequential. It won't be able to do much until it's finished reading or writing a file.

In these situation, it is better to use java.nio way:

*

*An application that need to service hundreds or thousands of connections simultaneously.

You can see the following links for further information:
http://www.skill-guru.com/blog/2010/11/14/java-nio-vs-java-io-which-one-to-use/
http://blogs.oracle.com/slc/entry/javanio_vs_javaio
https://www.ibm.com/developerworks/java/tutorials/j-nio/
http://java.dzone.com/articles/java-nio-vs-io


text:
Q: Simple command-line loop in Linux shell I have identically named files in 4 subfolders of folder build named:

*

*release-iphoneos

*release-iphonesimulator

*debug-iphoneos

*debug-iphonesimulator

I want to copy these files to an identical directory structure in a folder sdk, on the command-line - but not using a script.
What I thought I should be able to do is something like:
for C in (release debug); for T in (iphoneos iphonesimulator); cp build/$C-$T/*.a sdk/$C-$T

But I'm not a Linux guy and I can't get it to work even after looking up for loops. Can it be done on a single line fairly easily?

A: Try:
cp -R build/{release-iphoneos,release-iphonesimulator,debug-iphoneos,debug-iphonesimulator} sdk/

A: There are a couple of problems with your approach:

*

*(A B) can only be used for array assignment (e.g., C=(A B)), not creating one on-the-fly.
However, for does not require an array, so for C in A B will work just fine.

*The proper syntax for for loops is for ... in ...; do ..., done.
This command should work just fine:
for C in release debug; do for T in iphoneos iphonesimulator; do cp build/$C-$T/*.a sdk/$C-$T; done; done

Note that this requires the proper folders in sdk to exist already.
However, as @Robertof already showed, there are ways to archive this without any loops at all.

If you want to copy all files from the directories (i.e., *.a matches all of them), yu can use his command or this slight simplification:
cp -R build/{release,debug}-iphone{os,simulator} sdk

How it works:

*

*The shell will perform brace expansion, so the command that will be actually executed is this one:
cp -r build/release-iphoneos build/release-iphonesimulator build/debug-iphoneos build/debug-iphonesimulator sdk

*The -r switch makes cp recursive, i.e., it will copy entire directories instead of just files.

If you want to copy only the `.a files (i.e., there are others), you're better of using these commands:
cd build
cp --parents {release,debug}-iphone{os,simulator}/*.a ../sdk

How it works:

*

*Again, brace expansion is performed as before.

*The --parents switch makes cp use the full source file name for the destination, i.e., files from release-iphoneos will be copied to ../sdk/release-iphoneos.

Finally, a word of advice:
When experimenting with cp commands, always use the -i switch. It make cp interactive, meaning that it will prompt before overwriting anything.


text:
Q: In Flutter, getting URL but not able to display video on VideoPlayer and getting Error I am not able to display the video in UI but I am getting URL and it showing some "Unhandled Exception: Bad state: Future already completed"
   List<String> videoList = [];

   VideoPlayerController _controller;

    @override
   void initState() {
super.initState();
getVideos(context);
  }

  @override
  Future<void> dispose() async {
  super.dispose();
  if (videoList != null && mounted) {
  await _controller.dispose();

   }
}

The code where I want to display the video:
        Container(
              height: 200.0,
              padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 15.0),
              child: ListView(
                //shrinkWrap: true,
                scrollDirection: Axis.horizontal,
                children: [
                  FutureBuilder (
                      future: hasInitialized,
                      builder: (context, snapshot){
                        if (snapshot.connectionState == ConnectionState.done) {
                          return new ListView.builder(
                            shrinkWrap: true,
                            scrollDirection: Axis.horizontal,
                              itemCount:videoList.length,
                              itemBuilder: (BuildContext context,int index){
                              return Container(
                                height: 180,
                                width: 180,
                                padding: EdgeInsets.all(10),
                                child: _controller.value.isInitialized ?

                                    Stack(
                                      children: [
                                        VideoPlayer(_controller),
                                        _ControlsOverlay(_controller),
                                        // AspectRatioVideo(_controller),
                                      ],
                                    )
                                    :Container()
                              );
                            }
                            );
                        } else {
                          return
                            //Text("No video");
                          Center(child: CircularProgressIndicator(),);
                        }
                      }
                  )
                ],
              ),

            ),

The code from where I am getting the video url:
                Future  hasInitialized;
         Future<List<String>> getVideos(context) async {
       var document = await          FirebaseFirestore.instance.collection("users").
         doc(auth.currentUser.uid).get();
        List<String> videos = [];
      for (var item in document.data()['videos']) {
        videos.add(item);
             }
       setState(() {
         _controller =    VideoPlayerController.network(videoList.toString());
        // _controller =  VideoPlayerController.network(videoList[videos]);
       _controller.addListener(() {
          setState(() {});
         });
       hasInitialized = _controller.initialize();
       _controller.setLooping(false);
         _controller.initialize();
        });

      videoList= videos;
     print(videoList.length);
    print(videoList);
     return videos;
      }

The error I am getting:
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Bad state: Future already completed
E/flutter ( 9697): #0      _AsyncCompleter.complete (dart:async/future_impl.dart:45:31)
E/flutter ( 9697): #1      VideoPlayerController.initialize (package:video_player/video_player.dart:310:25)
E/flutter ( 9697):
E/flutter ( 9697):
E/ExoPlayerImplInternal( 9697): Playback error
E/ExoPlayerImplInternal( 9697):   com.google.android.exoplayer2.ExoPlaybackException: Source error
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:554)
E/ExoPlayerImplInternal( 9697):       at android.os.Handler.dispatchMessage(Handler.java:102)
E/ExoPlayerImplInternal( 9697):       at android.os.Looper.loop(Looper.java:223)
E/ExoPlayerImplInternal( 9697):       at android.os.HandlerThread.run(HandlerThread.java:67)
E/ExoPlayerImplInternal( 9697):   Caused by: com.google.android.exoplayer2.upstream.FileDataSource$FileDataSourceException: com.google.android.exoplayer2.upstream.FileDataSource$FileDataSourceException: java.io.FileNotFoundException: []: open failed: ENOENT (No such file or directory)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.FileDataSource.open(FileDataSource.java:97)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.DefaultDataSource.open(DefaultDataSource.java:199)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.StatsDataSource.open(StatsDataSource.java:84)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.source.ProgressiveMediaPeriod$ExtractingLoadable.load(ProgressiveMediaPeriod.java:1013)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:415)
E/ExoPlayerImplInternal( 9697):       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/ExoPlayerImplInternal( 9697):       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/ExoPlayerImplInternal( 9697):       at java.lang.Thread.run(Thread.java:923)
E/ExoPlayerImplInternal( 9697):   Caused by: com.google.android.exoplayer2.upstream.FileDataSource$FileDataSourceException: java.io.FileNotFoundException: []: open failed: ENOENT (No such file or directory)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.FileDataSource.openLocalFile(FileDataSource.java:166)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.FileDataSource.open(FileDataSource.java:89)
E/ExoPlayerImplInternal( 9697):       ... 7 more
E/ExoPlayerImplInternal( 9697):   Caused by: java.io.FileNotFoundException: []: open failed: ENOENT (No such file or directory)
E/ExoPlayerImplInternal( 9697):       at libcore.io.IoBridge.open(IoBridge.java:492)
E/ExoPlayerImplInternal( 9697):       at java.io.RandomAccessFile.(RandomAccessFile.java:289)
E/ExoPlayerImplInternal( 9697):       at java.io.RandomAccessFile.(RandomAccessFile.java:152)
E/ExoPlayerImplInternal( 9697):       at com.google.android.exoplayer2.upstream.FileDataSource.openLocalFile(FileDataSource.java:155)
E/ExoPlayerImplInternal( 9697):       ... 8 more
E/ExoPlayerImplInternal( 9697):   Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
E/ExoPlayerImplInternal( 9697):       at libcore.io.Linux.open(Native Method)
E/ExoPlayerImplInternal( 9697):       at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
E/ExoPlayerImplInternal( 9697):       at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
E/ExoPlayerImplInternal( 9697):       at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
E/ExoPlayerImplInternal( 9697):       at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
E/ExoPlayerImplInternal( 9697):       at libcore.io.IoBridge.open(IoBridge.java:478)
E/ExoPlayerImplInternal( 9697):       ... 11 more
E/ExoPlayerImplInternal( 9697): Playback error

A: _controller.initialize(); returns a Future i guess.
You are calling it twice:
hasInitialized = _controller.initialize();
_controller.setLooping(false);
_controller.initialize();

That's why you are getting: Future already completed


text:
Q: Find an example of a function $f(x)\neq-2x$ such that $\int_{0}^{1} \left[ -2x-f(x) \right]{\rm d}x = 0$ I'm having some trouble knowing where to start with this problem.
Find an example of a function $f(x)\neq-2x$ such that
$$\int_{0}^{1} \left[ -2x-f(x) \right]{\rm d}x = 0$$
I'm looking for a nudge in the right direction rather than a complete solution.

A: HINT: You can get one such $f(x)$ by using the fact $$\int_0^1 (1-2x) dx=0$$
Can you use it to find a suitable $f(x)$?
Again, rewrite the above as $$\int_0^1 (\frac{1}{2}-x) dx=0$$
Can you use this to find another suitable $f(x)$?

A: Well do a little bit of integration to show that
$$\int(-2x-f(x))dx=-x^2-\int f(x)dx$$
which means that
$$\int_{0}^{1}(-2x-f(x))dx=-1-\left. \int f(x)dx \right |_{x=1}+\left. \int f(x)dx \right |_{x=0}=0$$
Therefore
$$F(0)-F(1)=1$$
where
$$f(x)=\frac{d}{dx}F(x)$$
So if you can find a suitable $F$, which has a kinder looking requirement to satisfy. You can just take the derivative to get back $f$.

A: HINT:
$$\int_0^1\left[-2x-f(x)\right]\space\text{d}x=0\Longleftrightarrow$$
$$-2\int_0^1 x\space\text{d}x-\int_0^1 f(x)\space\text{d}x=0\Longleftrightarrow$$
$$-2\int_0^1 x\space\text{d}x-\int_0^1 f(x)\space\text{d}x=0\Longleftrightarrow$$
$$-2\left[\frac{x^2}{2}\right]_0^1-\int_0^1 f(x)\space\text{d}x=0\Longleftrightarrow$$
$$-\left[x^2\right]_0^1-\int_0^1 f(x)\space\text{d}x=0\Longleftrightarrow$$
$$-\left(1^2-0^2\right)-\int_0^1 f(x)\space\text{d}x=0\Longleftrightarrow$$
$$-1-\int_0^1 f(x)\space\text{d}x=0\Longleftrightarrow$$
$$-\int_0^1 f(x)\space\text{d}x=1\Longleftrightarrow$$
$$\int_0^1 f(x)\space\text{d}x=-1$$


text:
Q: Disable revers image scan in zxing app How to disable reverse image scan in zxing android app? Is it possible to do with app settings or modifying sources? I just want to scan code from left to the right direction (green line). And not to scan code from right to left direction (red line). There are some pseudo barcodes without error control (en.wikipedia.org/wiki/Pharmacode for example) which have different codes in two directions. Thanks for any help!

A: If the format isn't supported (and Pharmacode isn't on the list of ZXing barcodes: https://github.com/zxing/zxing/blob/master/README.md) you'll have to modify the ZXing code to support your specific format or find/buy/license a library that does. The fact that I can flip a UPC or Code128 barcode is embedded in the decode logic for that code type.
Honestly I believe it will take some effort to modify ZXing as you will need to modify a 1-D decoder to take in a orientation value or modify the decoding output to handle both orientation cases and separately parse out the correct orientation results.


text:
Q: How I can break two grid column using bootstrap and css? enter image description here
grid break space between 2 column.

Helo

Hello

Anyone help to break two grid column.

A: You need to use display inline-block for having the divs in a single row.
Try
.justify-content-around div {
display:inline-block
}

A: If you mean by " the space " the padding added to each div in your row.

Then you can remove it by adding the class no-gutters to the row div.

and the space between the two divs is now removed.

if that is not what you mean please provide a screenshot of your desired result.

A:

Helo

Hello


text:
Q: UICollectionViewCell Bad Access on NSMutableArray I am using a UICollectionView in an app where the cells of the collection view are based on data coming from a server.
When the app loads I download the data from the server and convert it into individual NSObjects which are stored in an NSMutableArray
@property (nonatomic, retain) NSMutableArray *dataArray;

The count of this dataArray is then used to determine the number of cells in the collection view.
The problem arises when I try and access this dataArray in the cellForItemAtIndexPath collection view delegate method:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"ReminderCard" forIndexPath:indexPath];

    GMReminderCard *reminderCard = (GMReminderCard *)cell;
    GMReminder *rem = [self.dataArray objectAtIndex:[indexPath row]];

    [reminderCard initialiseReminder:rem];

    cell.layer.cornerRadius     = 5;
    cell.layer.masksToBounds    = YES;
    return cell;
}

- (void)initialiseReminder:(GMReminder *)rem
{
    if(!loan)return;

    _thisReminder = rem;

    NSURL *imageURL = [NSURL URLWithString:_thisReminder.image relativeToURL:[NSURL    URLWithString:@"http://host.cloudfront.net/"]];

    [self.image setImageWithURL:[imageURL absoluteURL]
           placeholderImage:[UIImage imageNamed:@"973-user.png"]];

    [_title setText:[_thisReminder title]];
    [_description setText:[_thisReminder description]];
}

Here is my code for fetching the data from the server, the NSMutableArray returned contains GMReminder objects:
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self becomeFirstResponder];

    dataArray = [[NSMutableArray alloc] init];

    [GMReminders getCurrentReminders:^(NSMutableArray *rems, NSError *err){
        if (!err) {
            dataArray = [[NSMutableArray alloc] initWithArray:rems];
            [collectionView reloadData];
        }
    }];

    [self.view setBackgroundColor:[UIColor blackColor]];

    [self buildBackgroundSlider];
    [self buildLabel];
    [self buildCollectionView];
}

Initially the cells load as expected but when I attempt to scroll the collection view I get a bad access error thrown on the first attempt to use a GMReminder variable.
Any help would be greatly appreciated

A: In ViewDidload method make collectionview programmatically:-
UICollectionView *collection_view=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 320, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout];
    [collection_view setBackgroundColor:[UIColor colorWithRed:0.810746 green:0.764681 blue:0.764681 alpha:0.8]];
    collection_view.delegate = self;
    collection_view.dataSource = self;
    [collection_view registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [self.view addSubview:collection_view];

Define Delegate for cell of UicollectionView:-
- (UICollectionViewCell *) collectionView:(UICollectionView *) collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"cellIdentifier";

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    if (!cell)
    {
        cell = [[UICollectionViewCell alloc] initWithFrame:CGRectMake(1,0,cell.frame.size.width, cell.frame.size.height)];
    }
    return cell;
}

A: replace this
dataArray = [[NSMutableArray alloc] initWithArray:rems];

with
dataArray = [[NSMutableArray alloc] initWithArray:[rems copy]];


text:
Q: Using MongoDB for a Matchmaking Server I'm trying to make an external web server for matchmaking on Roblox using Node.js. I'm wanting to use MongoDB for a backend database, but with lobbies being made and deleted so quick, would that work? I have 2GB of RAM and 1 CPU core on a DigitalOcean droplet.

A: Using MongoDB for something such as match-making lobbies for Roblox seems very excessive, especially since Roblox provides DataStoreService for things such as this. I'm sure using DataStoreService should be able to fulfill your needs, even with the lobbies being created and deleted quickly. Many of the frequently played match-making games use it, and they don't have too many problems.
I'd even argue that using an external database such as MongoDB would be worse for your game. If lobbies are being created and removed as fast as you suggest, you'd surely hit the low request limit, which would create a lot of inconsistencies throughout your game servers, making it difficult to play.


text:
Q: BufferedImage + jPanel equivalent way to view an image in C++ using Qt I have a Java program that used a BufferedImage attached to a jPanel to display some image data that I am reading in from a byte array. I was getting a row of the Image at a time into the byte array, getting the WriteableRaster of the image, and calling the setDataElements() method of the raster, and then setData of the BufferedImage to get the new data in.
What is the equivalent way to do this in C++?
Edit: I have Qt, and thought I might try to build my UI using that

A: C++ doesn't have any UI framework built into its standard library like Java does.  You need to pick one, like GTK, QT, whatever.
Until you do, your question can't be answered because it's going to be different depending.

A: I think that QImage is the closest in concept to a BufferedImage.  It has a method loadFromData() which can load image data from an array.  You can then convert that into a QPixmap by calling QPixmap::fromImage() and display it in a QLabel or whatever.


text:
Q: Does probability change with change in information about event? For example in the Monty Hall problem, initial probability of choosing a car behind three doors is 1/3. But as more information is available regarding a door not containing a car, the probability of the car being behind chosen door is 1/3 and other door is 2/3.
But to look at it another way, if there was another person who knew before hand that one of the doors contain a goat. Then for him, the probability of a car being behind one of the doors is only 1/2.
So, is probability subjective based on information available? It might seem obvious, but when we are taught probability, none of the theory address this point. Sure, they talk about the abstract concepts like independence, conditional probability but how they are tied to real world and their implications are rarely discussed.

A: Probability is objective based on the information available.  As Bayes taught us, such information depends upon prior information as well as evidence that comes in later.  (Bayes teaches us the optimal method for incorporating both prior information and subsequent information.)
Indeed, if player 1 has no prior information, the probability of the car being behind each door is $1/3$.  But for the other person who knows which door already contains a goat, the probability the car is behind one of the other (closed) doors is of course $1/2$.
Of course, given perfect information (such as host Monty Hall has), the probability the car is behind a particular door is either 100% (for the special door) and 0% behind each of the other doors.
This doesn't mean probability is "subjective," but just that it depends upon one's state of knowledge.
(There is a different technical meaning to the term "subjective probability," though.  When you ask someone the chance of rain tomorrow and they say "30%," they are expressing a "subjective probability.")


text:
Q: Java ActionListener not working but no errors So, I have been trying to learn how to work with WindowBuilder for the last month. I have watched a few YouTube videos especially about CardLayout, but my buttons don't seem to change the panels.
I'm actually aiming for a runnable game, but since I don't know where exactly to start, I have decided to code the part of the changing panel first.(sb told me my code wasn't exactly good for a game)
I want the panel to change when the player clicks on "New Game". It gave me errors at first, but after a few changes, it doesn't even give errors.
So here is my code:
package halma.views;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Color;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MainFrame extends JFrame {

    private JPanel contentPane;
    private JPanel returnBar_panel;
    private JPanel gameBar_panel;
    private JPanel startupReturnBar_Panel;
    private JPanel returnGame_Panel;
    private JPanel gameGUI_Panel;
    private JPanel startupGameBar_Panel;
    private JButton playButton;
    private JButton highScoresButton;
    private JButton exitButton;
    private JPanel resumeReturn_Panel;

    static ActionListeners action = new ActionListeners();

    CardLayout cardLayout1;  //Used for the buttons' actionlistener.
    CardLayout cardLayout2;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

    }

    //The constructor method.
    public MainFrame() {
        createFrame();

        cardLayout1 = (CardLayout)(returnBar_panel.getLayout());
        cardLayout2 = (CardLayout)(gameBar_panel.getLayout());
    }

    //The getters and setters that are required for other classes to use the private variables in the "MainFrame" class.

    public JButton getPlayButton() {
        return playButton;
    }

    public JPanel getReturnBar_panel() {
        return returnBar_panel;
    }

    public void setReturnBar_panel(JPanel returnBar_panel) {
        this.returnBar_panel = returnBar_panel;
    }

    public JPanel getReturnGame_Panel() {
        return returnGame_Panel;
    }

    public void setReturnGame_Panel(JPanel returnGame_Panel) {
        this.returnGame_Panel = returnGame_Panel;
    }

    public JPanel getGameGUI_Panel() {
        return gameGUI_Panel;
    }

    public void setGameGUI_Panel(JPanel gameGUI_Panel) {
        this.gameGUI_Panel = gameGUI_Panel;
    }

    public void setPlayButton(JButton playButton) {
        this.playButton = playButton;
    }

    public JPanel getResumeReturn_Panel() {
        return resumeReturn_Panel;
    }

    public void setResumeReturn_Panel(JPanel resumeReturn_Panel) {
        this.resumeReturn_Panel = resumeReturn_Panel;
    }

    //Runs the game.
    public static void runGame() {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //Creating the frame.

    public void createFrame() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 527, 374);
        setSize(800, 600);
        contentPane = new JPanel();
        contentPane.setBackground(new Color(255, 192, 203));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        returnBar_panel = new JPanel();
        returnBar_panel.setBackground(new Color(255, 192, 203));

        gameBar_panel = new JPanel();
        gameBar_panel.setBackground(new Color(255, 192, 203));
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(returnBar_panel, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(gameBar_panel, GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
                    .addContainerGap())
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addComponent(returnBar_panel, GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
                .addComponent(gameBar_panel, GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
        );
        gameBar_panel.setLayout(new CardLayout(0, 0));

        startupGameBar_Panel = new JPanel();

        startupGameBar_Panel.setBackground(new Color(255, 192, 203));
        gameBar_panel.add(startupGameBar_Panel, "name_328512842567600");

        playButton = new JButton("New Game");
        playButton.setFocusable(false);
        playButton.setBackground(new Color(255, 160, 122));
        playButton.setForeground(new Color(0, 0, 0));
        playButton.setFont(new Font("Comic Sans MS", Font.ITALIC, 12));
        playButton.addActionListener(action);

        highScoresButton = new JButton("Records");
        highScoresButton.setForeground(new Color(0, 0, 0));
        highScoresButton.setFocusable(false);
        highScoresButton.setFont(new Font("Comic Sans MS", Font.ITALIC, 12));
        highScoresButton.setBackground(new Color(255, 160, 122));

        exitButton = new JButton("Exit");
        exitButton.setForeground(new Color(0, 0, 0));
        exitButton.setFocusable(false);
        exitButton.setFont(new Font("Comic Sans MS", Font.ITALIC, 12));
        exitButton.setBackground(new Color(255, 160, 122));
        GroupLayout gl_startupGameBar_Panel = new GroupLayout(startupGameBar_Panel);
        gl_startupGameBar_Panel.setHorizontalGroup(
            gl_startupGameBar_Panel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_startupGameBar_Panel.createSequentialGroup()
                    .addContainerGap(490, Short.MAX_VALUE)
                    .addGroup(gl_startupGameBar_Panel.createParallelGroup(Alignment.TRAILING, false)
                        .addComponent(exitButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(highScoresButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(playButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(24))
        );
        gl_startupGameBar_Panel.setVerticalGroup(
            gl_startupGameBar_Panel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_startupGameBar_Panel.createSequentialGroup()
                    .addContainerGap(341, Short.MAX_VALUE)
                    .addComponent(playButton)
                    .addGap(18)
                    .addComponent(highScoresButton)
                    .addGap(18)
                    .addComponent(exitButton)
                    .addGap(105))
        );
        startupGameBar_Panel.setLayout(gl_startupGameBar_Panel);

        gameGUI_Panel = new JPanel();
        gameGUI_Panel.setBackground(Color.RED);
        gameBar_panel.add(gameGUI_Panel, "name_328347141657400");
        gameGUI_Panel.setLayout(new CardLayout(0, 0));
        returnBar_panel.setLayout(new CardLayout(0, 0));

        setStartupReturnBar_Panel(new JPanel());
        getStartupReturnBar_Panel().setBackground(new Color(255, 192, 203));
        returnBar_panel.add(getStartupReturnBar_Panel(), "name_328000881526100");

        returnGame_Panel = new JPanel();
        returnGame_Panel.setBackground(new Color(255, 192, 203));
        returnBar_panel.add(returnGame_Panel, "name_328006822278900");

        resumeReturn_Panel = new JPanel();
        resumeReturn_Panel.setBackground(Color.PINK);
        returnBar_panel.add(resumeReturn_Panel, "name_331156929215800");
        resumeReturn_Panel.setLayout(new CardLayout(0, 0));
        JPanel panel2 = new JPanel();
        contentPane.setLayout(gl_contentPane);
    }

    public JPanel getStartupReturnBar_Panel() {
        return startupReturnBar_Panel;
    }

    public void setStartupReturnBar_Panel(JPanel startupReturnBar_Panel) {
        this.startupReturnBar_Panel = startupReturnBar_Panel;
    }

package halma.views;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionListeners extends MainFrame implements ActionListener {
    /**
     *
     */
    private static final long serialVersionUID = 814839576128286295L;
    MainFrame frame = new MainFrame();

    public ActionListeners() {

        frame.runGame();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("meow!");
        frame.cardLayout1.show(frame.getReturnBar_panel(), "resumeReturn_Panel");

        if(e.getSource() == frame.getPlayButton()) {
            System.out.println("T");
            frame.cardLayout1.show(frame.getReturnBar_panel(), "resumeReturn_Panel");
            frame.cardLayout2.show(frame.getGameGUI_Panel(), "Playing");
        }
    }
}

In the Second class, the word "Meow" gets printed, but the panel doesn't change even if I put it out of the if-statement. And the letter T doesn't get printed.

A: Why would you want an ActionListener to have a Frame? Wouldn't it it make more sense for a Frame to have an ActionListener? Even for a frame to have an action listener makes little sense. You want the component receiving the user action (the source object) to contain the listener. For example, if a user clicks on a button, you want that button to react to the action initiated by the user. For instance, if you have a button that should display "hello" in the console when clicked by the user, you would do something like this:
helloBtn.addActionListener(listener);

Then, your listener should look something like this:
public class HelloMsgListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Hello!");
    }
}

When your listener is this simple, it might make more sense to add it as an anonymous entity.
The code you wrote is very messy. You created a listener that has a frame, but that frame is not the instance that has the component that contains the listener with the frame.
The way to fix this is to create a class that creates the frame and runs your application
public class MyApp {

    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run () {
                createAndShowGUI();
            }

            private void createAndShowGUI () {
                JFrame frame = new JFrame();
                ...
                frame.setVisible(true);
                // Create the rest of the components and add to frame
                playButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed (ActionEvent e) {
                        System.out.println("meow!");
                        frame.cardLayout1.show(frame.getReturnBar_panel(),
                            "resumeReturn_Panel");

                        if (e.getSource() == frame.getPlayButton()) {
                            System.out.println("T");
                            frame.cardLayout1.show(frame.getReturnBar_panel(),
                                "resumeReturn_Panel");
                            frame.cardLayout2.show(frame.getGameGUI_Panel(), "Playing");
                        }
                    }
                });
            }
        });
    }
}

Then, you create your button


text:
Q: Printing square using specified character and multiplying chars
Write a programme that prints a square pattern of side length M of any single character specified by the user using a single for loop and a single if else statement. You should define both M and the character constant C as preprocessor statements.

I actually did that but I wonder is there any easier way to solve this problem. Here's my code:
#include <stdio.h>
#include <string.h>

int
main()
{

    int M, i = 1;
    char C, G[1000];

    printf("Input a value for side length:\n");
    scanf("%d", &M);

    printf("Input a character for pattern:\n");
    scanf(" %c", &C);

    for (; i <= M; i++) {
        printf("%c", C);

        if (i <= M) {
            memset(G, C, (M - 1));
            G[M - 1] = '\0';
            puts(G);
        }

    }

    return 0;
}

A: You can do the memset outside of the loop once.
You can just do puts inside the loop:
#include <stdio.h>
#include <string.h>

int
main()
{

    int M, i = 1;
    char C, G[1000];

    printf("Input a value for side length:\n");
    scanf("%d", &M);

    printf("Input a character for pattern:\n");
    scanf(" %c", &C);

    memset(G, C, M);
    G[M] = '\0';

    for (; i <= M; i++)
        puts(G);

    return 0;
}

For an input of 8 rows and a char of *, the output is:
Input a value for side length:
8
Input a character for pattern:
*
********
********
********
********
********
********
********
********

UPDATE:
After rereading the requirements, if C and M must be macros, the code should be:
#include <stdio.h>
#include <string.h>

#ifndef M
#error M not defined
#endif

#ifndef C
#error C not defined
#endif

int
main()
{

    int i = 1;
    char G[1000];

    memset(G, C, M);
    G[M] = '\0';

    for (; i <= M; i++)
        puts(G);

    return 0;
}

And, the program should be compiled with:
cc -o program -DM=8 -DC="'*'" program.c

A: Something along these lines, perhaps:
int M1 = M + 1;
for (int i = 0; i < M*M1; ++i) {
  if (i % M1 == M) putchar('\n');
  else putchar(C);
}


text:
Q: How To Remove an Element from a List Using Another List's Placeholder in Python I need to remove a certain element from a list of dictionaries. Unfortunately, the only reference to the object needing removal is a place in another list:
enemy_list[num]

I need to take out enemy_list[num] from everyone.
ii = 0
for i in enemy_list:
  print(ii, ':', enemy_list[ii])
  ii += 1
num = input("Which of your opponents would you like to eliminate? ")
num = int(num)
del everyone[enemy_list[num]]

I cannot remove it from only enemy_list because it is reset multiple times as everyone in list everyone takes a turn.
I tried this question, but it only worked from removing entire lists from eachother. Is there a way I could change it to work for this case?
Thanks for your time!

A: everyone.remove(enemy_list[num])


text:
Q: How can I show drafts in wp_dropdown_pages list? I am using wp_dropdown_pages in the backend of my site to generate a list of pages according to a specific set of criteria.
The list only shows published posts where I would like it to show both published posts and drafts.
I have found other Stack Exchange threads which show how to accomplish this in the standard wordpress dropdowns, but this does not seem to extend to wp_dropdown_pages.
What I am using to show drafts in the standard dropdowns is this:
<?php
    /* Show drafts in dropdown lists */
    add_filter('page_attributes_dropdown_pages_args', 'my_attributes_dropdown_pages_args', 1, 1);
    add_filter('quick_edit_dropdown_pages_args', 'my_attributes_dropdown_pages_args', 1, 1);

    function my_attributes_dropdown_pages_args($dropdown_args) {
        $dropdown_args['post_status'] = array('publish','draft');
        return $dropdown_args;
    }
?>

The above works great. I would like to do exactly the same thing for custom fields generated using wp_dropdown_pages. To clarify, in the backend, I am generating a dropdown list using the following code:
<?php
    $dropdown_args_food = array(
        'depth'         => '2',
        'selected'      => $selectedFoodType,
        'post_type'     => 'page',
        'name'          => 'selected-food-type',
        'id'            => 'selected-food-type',
        'echo'          => 1,
        'meta_key'      => 'category',
        'meta_value'    => 'food',
        'hierarchical'  => 1,
        'show_option_none'      => ' ',
    );
    wp_dropdown_pages( $dropdown_args_food );
?>

The above generates a dropdown list of pages exactly as I want it to be, only without drafts.

A: Update
It seems that you can do this directly with WP function wp_dropdown_pages() as birgire points out in his response below:
https://wordpress.stackexchange.com/a/240275/102371

This solution is longer, and uses get_posts() to fetch specific post statuses.
$pages = get_posts( array( 'post_type' => 'page', 'post_parent' => 0, 'post_status' => array( 'draft', 'publish' ) ) );

echo '<select name="selected-food-type" id="selected-food-type">';
foreach( $pages as $page ) {
    echo '<option value="' . $page->ID . '">' . get_the_title( $page->ID ) . '</option>';
    $children = get_children( 'post_parent='. $page->ID );
    foreach( $children as $subpage ) {
        echo '<option value="' . $subpage->ID . '">   ' . get_the_title( $subpage->ID ) . '</option>';
    }
}
echo '</select>';

A: You should be able to use
'post_status' => 'publish,draft',

in wp_dropdown_pages() since it's a wrapper for get_pages() that supports the post_status argument with comma separated list of post status types.
About the documentation of get_pages():
It looks like the documentation for the post_status argument of get_pages() isn't accurate enough. It says:
* @type string  $post_status  A comma-separated list of post statuses types to include.

But it does actually support an array as well, so we can write:
'post_status' => [ 'publish', 'draft' ],

I filed ticket #38136 to address that.


text:
Q: python interpreter throwing a type error where there is none i am trying to create a drop down like feature in pygame. The program consists of the "Drop" class which has texts on it and describes the general purpose of the drop down menu. Then there is the wrapper class which contains all the different labels on the drop down menu. The Child class is the label and can be added on to the wrapper class via the "add_child" function which is where the error is occurring.
import pygame as pg

doc = "c:/users/user/documents/code/py/pg/project/"
vec = pg.math.Vector2

class Drop(Sprite):
    def __init__(self, parent, **kwargs):
        self.parent = parent

        default = {
            "size":[100, 25],
            "pos":vec(0, 0),
            "bg":pg.Color("#ff0000"),
        }

        for key, value in default.items():
            if key not in kwargs:
                kwargs[key] = value

        self.size = kwargs["size"]
        self.pos = vec(kwargs["pos"])
        self.bg = kwargs["bg"]

        super().__init__()

        class Child(Sprite):
            def __init__(self, parent, **kwargs):
                self.parent = parent

                default = {
                    "size":[100, 25],
                    "pos":vec(0, 0),
                    "bg":pg.Color("#00ff00")
                }

                for key, value in default.items():
                    if key not in kwargs and key != "name":
                        kwargs[key] = value

                self.size = kwargs["size"]
                self.pos = vec(kwargs["pos"])
                self.bg = kwargs["bg"]
                self.name = kwargs["name"]

                super().__init__()

            def render(self):
                self.parent.image.blit(self.image, self.rect)

        class Wraper(Sprite):
            def __init__(self, parent, index=1):

                self.index = index
                self.children = [] # childs which are labels with texts on it

                self.parent = {
                    "0":parent.parent,
                    "1":parent.parent.parent
                }[str(self.index)]

                self.y = {
                    "0":parent.pos.y + parent.size[1],
                    "1":parent.parent.pos.y + parent.parent.size[1]
                }[str(self.index)]

                self.size = [100, 100]
                self.bg = pg.Color("#000000")

                self.x = self.parent.pos.x
                self.pos = vec(self.x, self.y)

                super().__init__()
                # this is a custom sprite initialization class i'ts not the problem

            def add_child(self, **kwargs):
                self.children.append(Child(self, kwargs))

                # this is where the interpreter throws the error
                # aperantly the child class takes 2 positional arguments
                # but i gave 3. but as you can see there are clearly only
                # two arguments given, the parent parameter and kwargs

            def render(self):
                if self.children:
                    for child in self.children:
                        child.render()

                if hasattr(self.parent, "image"):
                    self.parent.image.blit(self.image, self.rect)
                else:
                    self.parent.blit(self.image, self.rect)

        self.wraper = Wraper(self, 1)

    def render(self):
        self.wraper.render()
        self.parent.image.blit(self.image, self.rect)

the error:
152, in add_child
    self.children.append(Child(self, kwargs))
TypeError: init() takes 2 positional arguments but 3 were given

A: You want Child(self, **kwargs), not just Child(self, kwargs). It is trying to send it as an argument, when you want a keyword.


text:
Q: Regex to select the exact letter after an integer and avoid the proceeding comma of the selected text I have regex which recognized the letter d which is placed after an integer within an text (the d letter which is in the middle of the text). But at the moment it selects the next proceeding letter after letter d as well (whatever the letter it selected anyway). In this case it selects the proceeding comma as well (see the attached image)
Regex validation URL - https://regex101.com/r/ozlvQy/1

I just want the selection to be stopped if an comma is met (text without the comma should be selected). I guess that the current inserted regex can be altered to meet this.
I am very bad at regex calculations and will be great if anyone can help here ?


text:
Q: Word to describe the movement of a galloping horse's head I am looking for a word, an adjective, to substitute for 'back and forth' to describe the exerted forward reach then recoil action of a horse's head in a gallop.
'Reciprocate' and 'oscillate' are both problematic - one is precise, machine-like controlled, the other determined organically by gravity, or robotically like a metronome. 'Annuent' is an antiquated word for 'nod', as in a human head nod of assent (based on annuent muscles in head/neck) and fits nicely ... but is unconventional... e.g. "The annuent up-down motion of the horses' heads towards the finish post, ended when the camera froze the inside horse a nose in front".
Any thoughts on a better one?

A: "Bobbing" comes to mind (if specific to a head's motion).


text:
Q: How can I share one Information panel from Google Analytics? How can I share (most willingly by URL) one created Information panel with chosen informations set on filtered data? I need to share it to juz be just read and analysed (without editing and seeing others (not filtered) data).
If I can't achieve this using Information Panels - what is the best way to achieve that functionality?


text:
Q: ImportError: No module named _sqlite3 (even after doing eveything) i am using python 2.7.11 on virtualenv in lubuntu 12.04.(dont own a good laptop its dell latitude d600)
Python 2.7.11 (default, Mar  4 2016, 04:38:41)

[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import sqlite3
      Traceback (most recent call last):
        File "", line 1, in
        File "/home/maharshi/.localpython/lib/python2.7/sqlite3/init.py", line 24, in
          from dbapi2 import *
        File "/home/maharshi/.localpython/lib/python2.7/sqlite3/dbapi2.py", line 28, in
          from _sqlite3 import *
      ImportError: No module named _sqlite3

i have installed pysqlite using pip and it says successfull.
(p2.7) maharshi@maharshi-Latitude-D600:~/code$ which python
/home/maharshi/virtualenvs/p2.7/bin/python
(p2.7) maharshi@maharshi-Latitude-D600:~/code$ which pip
/home/maharshi/virtualenvs/p2.7/bin/pip
(p2.7) maharshi@maharshi-Latitude-D600:~/code$ pip install pysqlite
Requirement already satisfied (use --upgrade to upgrade): pysqlite in /home/maharshi/virtualenvs/p2.7/lib/python2.7/site-packages

i also installed it manually at both locations i.e
~/virtualenvs/p2.7/
~/.localpython/ (from where i created the virtualenv)

i also installed "libsqlite3-dev(as suggested by one of the posts)" i.e
sudo apt-get install libsqlite3-dev

Thank you in advance.

A: Try doing the whole process again installing python in virtualenv...as i understand when you add the libraries needed for SqlLite it wont affect the virtualenv python so you have to re-do all the steps and it will compile with the required libraries....


text:
Q: Build Eclipse C++ Docfrac project using Visual Studio 2012 Can someone please help me understand how to build the open source Docfrac C++ Eclipse project with Visual Studio 2012?
Docfrac
UPDATE 1:
When building project in VS 2012, I get:
Unexpected end of file while looking for precompiled header. Did you forget to add '#include "pch.h"' to your source?
UPDATE 2: Got past above issues thanks to Rowland.
Now i get, could not open #include vcl.h. No such file or directory.
CLOSING COMMENTS:
Unfortunately, what I wanted to achieve is not directly possible. Thanks to Rowland for pointing me in the right direction.

A: For the error relating to precompiled headers, select the source code files (.cpp or .c) that you added to the project in the Solution Explorer. Then right-click, choose Properties. Then in the C/C++ section under Precompiled Headers, select the option that says "Not using precompiled headers". Rebuild and bingo.

Alternatively, you can right-click the project itself and set it for all files.


text:
Q: condition and loop: how can i don't resume the music when calling the function several times? i have this function to play music with web audio API:
function playMusic(){

 if(countPre<count ){
    audio0.play();
    audio0.src = '0.mp3';
    audio0.controls = true;
    audio0.autoplay = true;
    audio0.loop = true;
    source = context.createBufferSource();
    source.connect(analyser);
    analyser.connect(context.destination);
    }
 else{audio0.pause();}

 }

However, the value of count and countPre are generated in a loop that runs 10 times per second.
I have to put the function playMusic inside that loop in order to update the values.
And here comes the problem:
I call playMusic 10 times per second! Every time, the music resumes.
I don't want it resumes, i want it plays continuously as long as the play condition is matched.
So is there any solution?

A: You have to check that music is not already playing in your condition.
Don't think there's an audio method for that.
You can do it by many ways, example :
function playMusic(){

if(countPre<count && !this.is_playing ){
    this.is_playing = true;
    audio0.play();
    audio0.src = '0.mp3';
    audio0.controls = true;
    audio0.autoplay = true;
    audio0.loop = true;
    source = context.createBufferSource();
    source.connect(analyser);
    analyser.connect(context.destination);
    }
 else{audio0.pause();
    this.is_playing = false}
 }


text:
Q: Borel subgroup is a semidirect product of the subgroup of all unitriangular matrices and the maximal split torus Suppose $G = GL(n,q)$ and $B\leqslant G$ is the Borel subgroup, $N \leqslant G$ is the subgroup of all monomial matrices and $T=B\cap N$ is a maximal split torus. I am trying to understand why $B=U \rtimes T$. It is clear that $T$ is a subgroup of diagonal matrices, so
$$T \cong \underbrace{C_{q-1} \times ... \times C_{q-1}}_n,$$
but don't understand, why any element of $B$ can be uniquely written as a product $ut$ for $u \in U$, $t \in T$. I understand this is stupid, but how do we show the uniqueness?


text:
Q: Probability - check if variables are independent Variables $X$ and $Y$ are indepedent and have the same exponential distribution, $\lambda=1$. Let $U=X+Y, V=X-Y$. Find density function of vector $(U,V)$. Are $U$ and $V$ independent?
My attempt:
Because $X$ and $Y$ are independt, thus
$f_{X,Y}(x,y)=f_X(x)\cdot f_Y(y)=\begin{cases} 0 &\text{ for } x,y \in (-\infty,0) \\ e^{-x-y} &\text{ for } x,y \in [0,\infty) \end{cases}$
Jacobian determinant:
$J=\left|\begin{smallmatrix} 1&1\\ 1&-1 \end{smallmatrix}\right|=-2$
$\begin{cases} U=X+Y \\ V=X-Y \end{cases}  \rightarrow  \begin{cases} X=\frac{U+V}{2} \\ Y=\frac{U-V}{2} \end{cases}$
Hence
$f_{U,V}(u,v)=\frac{\exp\left(-\frac{u+v}{2}\right)\cdot\exp\left(-\frac{u-v}{2}\right)}{|-2|}=\frac{\exp\left(-u\right)}{2}$
And now is the part where I have a problem.
$u\in [0,\infty)$
But what about the $v$?


text:
Q: CommunicationsException: Communications link failure Caused by: org.hibernate.exception.JDBCConnectionException: could not extract ResultSet When I am running multiple method concurrently then I am facing  Communications link failure with JDBCConnectionException.
Bellow code is causing this issue.
Stream<Supplier<List<?>>> tasks = Stream.of(() -> dashboardResultSDHDao.getMarketResult(),
            () -> dashboardResultSDHDao.getBatchResult(), () -> dashboardResultSDHDao.getModalityChatList(),
            () -> dashboardResultSDHDao.getCoadingTimeList(), () -> dashboardResultSDHDao.getCoderPerformersList());

lists = tasks
// Supply all the tasks for execution and collect CompletableFutures
.map(CompletableFuture::supplyAsync).collect(Collectors.toList())
// Join all the CompletableFutures to gather the results
.stream().map(CompletableFuture::join).collect(Collectors.toList());

Please let me know how we can resolve it.
[1;31mERROR[0;39m o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions - Communications link failure

The last packet successfully received from the server was 420,608 milliseconds ago.  The last packet sent successfully to the server was 19,142 milliseconds ago.
03-02-2018 19:32:02.277 [35m[http-nio-8099-exec-9][0;39m
[1;31mERROR[0;39m c.o.oscar.dao.impl.AccuracyDaoImpl.getAccuracyResult - Exception :org.hibernate.exception.JDBCConnectionException: could not extract ResultSet
javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: could not extract ResultSet
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:492)
at com.omega.oscar.dao.impl.AccuracyDaoImpl.getAccuracyResult(AccuracyDaoImpl.java:98)
at com.omega.oscar.dao.impl.AccuracyDaoImpl$$FastClassBySpringCGLIB$$9b8ed9bf.invoke(<generated>)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.JDBCConnectionException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
... 177 common frames omitted
Caused by: java.net.SocketTimeoutException: Read timed out


text:
Q: Time-series - data splitting and model evaluation I've tried to use machine learning to make prediction based on time-series data. In one of the stackoverflow question (createTimeSlices function in CARET package in R) is an example of using createTimeSlices to cross-validation for model training and parameter tuning:
    library(caret)
    library(ggplot2)
    library(pls)
    data(economics)
    myTimeControl <- trainControl(method = "timeslice",
                                  initialWindow = 36,
                                  horizon = 12,
                                  fixedWindow = TRUE)

    plsFitTime <- train(unemploy ~ pce + pop + psavert,
                        data = economics,
                        method = "pls",
                        preProc = c("center", "scale"),
                        trControl = myTimeControl)

My understanding is:

*

*I need to split may data to training and test set.

*Use training set for parameters tuning.

*Evaluate obtained model on the test set (using R2, RMSE, etc.)

Because my data is time-series, I suppose that I cannot use bootstraping for spliting data into training and test set. So, my questions are: Am I right? And If so - How to use createTimeSlices for model evaluation?

A: Shambho's answer provides decent example of how to use the caret package with TimeSlices, however, it can be misleading in terms of modelling technique. So in order not to misguide future readers that want to use the caret package for predictive modelling on time-series (and here I do not mean autoregressive models), I want to highlight a few things.
The problem with time-series data is that look-ahead bias is easy if one is not careful. In this case, the economics data set has aligned data at their economic reporting dates and not their release date, which is never the case in real live applications (economic data points have different time stamps). Unemployment data may be two months behind the other indicators in terms of release date, which would then introduce a model bias in Shambho's example.
Next, this example is only descriptive statistics and not predictive (forecasting) because the data we want to forecast (unemploy) is not lagged correctly. It merely trains a model to best explain the variation in unemployment (which also in this case is a stationary time-series creating all sorts of issues in modelling process) based on predictor variables at the same economic report dates.
Lastly, the 12-month horizon in this example is not a true multi-period forecasting as Hyndman does it in his examples.
Hyndman on cross-validation for time-series

A: Note that the original question that you have posted, takes care of the timeSlicing, and you don't have to create timeSlices by hand.
However, here is how to use createTimeSlices for splitting the data and then using it for training and testing a model.
Step 0: Setting up the data and trainControl:(from your question)
library(caret)
library(ggplot2)
library(pls)

data(economics)

Step 1: Creating the timeSlices for the index of the data:
timeSlices <- createTimeSlices(1:nrow(economics),
                   initialWindow = 36, horizon = 12, fixedWindow = TRUE)

This creates a list of training and testing timeSlices.
> str(timeSlices,max.level = 1)
## List of 2
## $ train:List of 431
##   .. [list output truncated]
## $ test :List of 431
##   .. [list output truncated]

For ease of understanding, I am saving them in separate variable:
trainSlices <- timeSlices[[1]]
testSlices <- timeSlices[[2]]

Step 2: Training on the first of the trainSlices:
plsFitTime <- train(unemploy ~ pce + pop + psavert,
                    data = economics[trainSlices[[1]],],
                    method = "pls",
                    preProc = c("center", "scale"))

Step 3: Testing on the first of the testSlices:
pred <- predict(plsFitTime,economics[testSlices[[1]],])

Step 4: Plotting:
true <- economics$unemploy[testSlices[[1]]]

plot(true, col = "red", ylab = "true (red) , pred (blue)", ylim = range(c(pred,true)))
points(pred, col = "blue")

You can then do this for all the slices:
for(i in 1:length(trainSlices)){
  plsFitTime <- train(unemploy ~ pce + pop + psavert,
                      data = economics[trainSlices[[i]],],
                      method = "pls",
                      preProc = c("center", "scale"))
  pred <- predict(plsFitTime,economics[testSlices[[i]],])

  true <- economics$unemploy[testSlices[[i]]]
  plot(true, col = "red", ylab = "true (red) , pred (blue)",
            main = i, ylim = range(c(pred,true)))
  points(pred, col = "blue")
}

As mentioned earlier, this sort of timeSlicing is done by your original function in one step:
> myTimeControl <- trainControl(method = "timeslice",
+                               initialWindow = 36,
+                               horizon = 12,
+                               fixedWindow = TRUE)
>
> plsFitTime <- train(unemploy ~ pce + pop + psavert,
+                     data = economics,
+                     method = "pls",
+                     preProc = c("center", "scale"),
+                     trControl = myTimeControl)
> plsFitTime
Partial Least Squares

478 samples
  5 predictors

Pre-processing: centered, scaled
Resampling: Rolling Forecasting Origin Resampling (12 held-out with a fixed window)

Summary of sample sizes: 36, 36, 36, 36, 36, 36, ...

Resampling results across tuning parameters:

  ncomp  RMSE  Rsquared  RMSE SD  Rsquared SD
  1      1080  0.443     796      0.297
  2      1090  0.43      845      0.295

RMSE was used to select the optimal model using  the smallest value.
The final value used for the model was ncomp = 1.

Hope this helps!!

A: Actually, you can!
First, let me give you a scholarly article on the topic.
In R:
Using the package caret, createResample can be used to make simple bootstrap samples and createFolds can be used to generate balanced cross–validation groupings from a set of data. So you'll probably want to use createResample. Here's an example of its usage:
data(oil)
createDataPartition(oilType, 2)

x <- rgamma(50, 3, .5)
inA <- createDataPartition(x, list = FALSE)

plot(density(x[inA]))
rug(x[inA])

points(density(x[-inA]), type = "l", col = 4)
rug(x[-inA], col = 4)

createResample(oilType, 2)

createFolds(oilType, 10)
createFolds(oilType, 5, FALSE)

createFolds(rnorm(21))

createTimeSlices(1:9, 5, 1, fixedWindow = FALSE)
createTimeSlices(1:9, 5, 1, fixedWindow = TRUE)
createTimeSlices(1:9, 5, 3, fixedWindow = TRUE)
createTimeSlices(1:9, 5, 3, fixedWindow = FALSE)

The values you see in the createResample function are the data and the number of partitions to create, in this case 2. You can additionally specify if the results should be stored as a list with list = TRUE or list = FALSE.
Additionally, caret contains a function called createTimeSlices that can create the indices for this type of splitting.
The three parameters for this type of splitting are:

*

*initialWindow: the initial number of consecutive values in each training set sample

*horizon: The number of consecutive values in test set sample

*fixedWindow: A logical: if FALSE, the training set always start at the first sample and the training set size will vary over data splits.

Usage:
createDataPartition(y,
                    times = 1,
                    p = 0.5,
                    list = TRUE,
                    groups = min(5, length(y)))
createResample(y, times = 10, list = TRUE)
createFolds(y, k = 10, list = TRUE, returnTrain = FALSE)
createMultiFolds(y, k = 10, times = 5)
createTimeSlices(y, initialWindow, horizon = 1, fixedWindow = TRUE)

Sources:
http://caret.r-forge.r-project.org/splitting.html
http://eranraviv.com/blog/bootstrapping-time-series-r-code/
http://rgm3.lab.nig.ac.jp/RGM/R_rdfile?f=caret/man/createDataPartition.Rd&d=R_CC
CARET. Relationship between data splitting and trainControl


text:
Q: Microsoft.SharePoint.SPContentTypeUsage does not contain a definition for GetUsages I'm trying to carry out this example for deleting a content type in sharepoint: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontenttypeusage.aspx
but I'm getting the error mentioned in the title of this question on the following line:
IList<SPContentTypeUsage> usages = SPContentTypeUsage.GetUsages(obsolete);

A: In my case I faced the same issue within a Sandboxed solution. So looks like it is a limitation for sandbox solution.


text:
Q: Training 1D CNN in Pytorch I want to train the model given below. I am developing 1D CNN model in PyTorch. Usually we use dataloaders in PyTorch. But I am not using dataloaders for my implementation. I need guidance on how i can train my model in pytorch.
import torch
import torch.nn as nn
import torch.nn.functional as F

class  CharCNN(nn.Module):
def __init__(self,num_labels=11):
    super(CharCNN, self).__init__()

    self.conv1 = nn.Sequential(
        nn.Conv1d(num_channels, depth_1, kernel_size=kernel_size_1, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_1, stride=stride_size),
        nn.Dropout(0.1),
    )

    self.conv2 = nn.Sequential(
        nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_2, stride=stride_size),
        nn.Dropout(0.25)
    )

    self.fc1 = nn.Sequential(
        nn.Linear(depth_2*kernel_size_2, num_hidden),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

    self.fc2 = nn.Sequential(
        nn.Linear(num_hidden, num_labels),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

def forward(self, x):
    out = self.conv1(x)
    out = self.conv2(out)

    # collapse
    out = x.view(x.size(0), -1)
    # linear layer
    out = self.fc1(out)
    # output layer
    out = self.fc2(out)
    #out = self.log_softmax(x,dim=1)

    return out

I am training my network like this:
criterion = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(),lr=learning_rate)

for e in range(training_epochs):
  if(train_on_gpu):
     net.cuda()
    train_losses = []

   for batch in iterate_minibatches(train_x, train_y, batch_size):
      x, y = batch
      inputs, targets = torch.from_numpy(x), torch.from_numpy(y)
      if(train_on_gpu):
        inputs, targets = inputs.cuda(), targets.cuda()
      opt.zero_grad()
      output = model(inputs, batch_size)

    loss = criterion(output, targets.long())
    train_losses.append(loss.item())
    loss.backward()
    opt.step()
val_losses = []
accuracy=0
f1score=0
print("Epoch: {}/{}...".format(e+1, training_epochs),
              "Train Loss: {:.4f}...".format(np.mean(train_losses)))

But i am getting the following error
          TypeError                                 Traceback (most recent call last)
          <ipython-input-60-3a3df06ef2f8> in <module>
   14             inputs, targets = inputs.cuda(), targets.cuda()
   15         opt.zero_grad()
   ---> 16         output = model(inputs, batch_size)
   17
   18         loss = criterion(output, targets.long())

   ~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self,
   * input, **kwargs)
   530             result = self._slow_forward(*input, **kwargs)
   531         else:
   --> 532             result = self.forward(*input, **kwargs)
   533         for hook in self._forward_hooks.values():
   534             hook_result = hook(self, input, result)

   TypeError: forward() takes 2 positional arguments but 3 were given

Please guide me how i can resolve this issue.

A: The forward method of your model only takes one argument, but you are calling it with two arguments:
output = model(inputs, batch_size)

It should be:
output = model(inputs)

A: The time series data uses a 5 element window.  The target is a rolling window of 5.   The convolution 1d model receives a Sales tensor 3 dimensional structure containing all the sales for a certain duration of time  (https://krzjoa.github.io/2019/12/28/pytorch-ts-v1.html)  The kernel is set at 5 to match the moving window size.  input and output are 1.  The loss function is calculated over 1000 epochs.  The prediction tensor is then converted to a numpy array and displayed comparing it to the actual moving average.  I did find iterate_minibatches code but it does not work with time series data because the dimensions are different (32 target vs 36 source)
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

df=pd.read_csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/shampoo.csv')

#created a three dimensional tensor
#1. number of samples
#2. number of channels
#3. -1 means infer value from dimension

X=data.Sales.copy()
y=data.Sales.rolling(5).mean().copy()

net = nn.Conv1d(1, 1, 5,  bias = False)
optimizer=optim.Adam(net.parameters(), lr=0.01) #l2
running_loss=0.0

X=data.Sales.copy()
y=data.Sales.rolling(5).mean().copy()

X_tensor = torch.Tensor(X).reshape(1, 1, -1)
print("Sales", X_tensor)
y=y[4:,].to_numpy()
y_tensor = torch.Tensor(y).reshape(1, 1, -1)
print("Avg", y_tensor)

ts_tensor = torch.Tensor(X).reshape(1, 1, -1)
kernel = [0.5, 0.5]
kernel_tensor = torch.Tensor(kernel).reshape(1, 1, -1)
print("Kernel", F.conv1d(ts_tensor, kernel_tensor))

for epoch in range(1000):
    optimizer.zero_grad()
    outputs=net(X_tensor)
    #print("Outputs",outputs)
    loss_value = torch.mean((outputs - y_tensor)**2)
    loss_value.backward()
    optimizer.step()

    running_loss += loss_value.item()

    if epoch % 100 == 0:
        print('[%d] loss: %.3f' % (epoch, loss_value.item()))
        print(net.weight.data.numpy())

prediction = (net(X_tensor).data).float()
prediction=(prediction.numpy().flatten())
data.Sales.plot()
plt.plot(prediction)

#actual moving average
data.Sales.plot()
plt.plot(y)


text:
Q: Linear algebra for modern differential geometry( and other types of modern geometry, like analytic, complex and algebraic) I wish to study real and complex analysis(for example, Pugh "Real Mathematical Analysis" and Cartan "Elementary theory of analytic functions of one and several complex variables") and modern differential and riemannian geometry(for example, Jeffrey Lee "Manifolds and differential geometry").
I would like to chose a book on theoretical linear algebra to cover prerequisites for these.
That is, I don't need a linear algebra for applications in science. I don't need it for its own sake or history of mathematics. I want to study modern geometry and analysis - real and complex analysis, analysis on manifolds, differential geometry, riemannian geometry, complex algebraic and analytic geometry.
I came across a few books on my search, but I'm not sure if they are the best option for my goals.
Axler "Linear Algebra Done Right" - this book seems to have a different goal in mind. It avoid determinants as well as works only over $\mathbb{R}$ and $\mathbb{C}$. Do you need linear algebra over an arbitrary field $F$ for study of smooth manifolds?
Roman "Advanced Linear Algebra". Isn't it an overkill for my goals? What do you think of this book?
Any other recommendations will be considered, of course. I would prefer modern books over likes of Hoffman-Kunze or Halmos, but if you know any old gems, feel free to tell.

A: The topics that you want to study use mostly the very essential ideas from Linear Algebra. Yes, over $\mathbb{R}$ and $\mathbb{C}$ is all you need. Since you seem to be a theoretically minded person with interest in geometry related subjects, I would recommend Gelfand's "Lectures on Linear Algebra". Strang's textbook is excellent, but probably not the style you are looking for.
My area of research is differential geometry (moving surfaces) and my favorite subjects to teach are Linear Algebra and Tensor Analysis. My advice would be to not treat Linear Algebra merely a means to studying the topics that you listed. Linear Algebra is the language and the framework for dealing with all branches of applied mathematics where physics, algebra and geometry meet. I would therefore recommend to study Linear Algebra thoroughly and, in fact, to give it several passes following a few different sources.
In case you want to learn my personal perspective on Linear Algebra and Differential Geometry, check out the Linear Algebra course on Lemma (http://lem.ma) and my Tensor Calculus videos on YouTube.
When Niels Henrik Abel was asked how he acquired his expertise, we replied "By studying the masters and not their pupils." Just one of my reactions to your desire to read a modern textbook.


text:
Q: Ajax ModalPopupExtender - Set scrollbars if the browser is too small
Possible Duplicate:
asp.net ModalPopupExtender : need to show scroll bar when overflow

All,
     I have been searching on Google for 3-4 hours already but none of the answers really helps.
     What I need to do is when the browser is too small and the modal popup is shown, the scroll bar on the browser will be set for the modal window instead of the background (main window).
Can anyone help?
Many thanks.


text:
Q: Oozie: Launch Map-Reduce from Oozie  action? I am trying to execute a Map-Reduce task in an Oozie workflow using a <java> action.
O'Reilley's Apache Oozie (Islam and Srinivasan 2015) notes that:

While it's not recommended, Java action can be used to run Hadoop MapReduce jobs because MapReduce jobs are nothing but Java programs after all. The main class invoked can be a Hadoop MapReduce driver and can call Hadoop APIs to run a MapReduce job. In that mode, Hadoop spawns more mappers and reducers as required and runs them on the cluster.

However, I'm not having success using this approach.
The action definition in the workflow looks like this:
<java>
    <!-- Namenode etc. in global configuration -->
    <prepare>
      <delete path="${transformOut}" />
    </prepare>
    <configuration>
        <property>
            <name>mapreduce.job.queuename</name>
            <value>default</value>
        </property>
    </configuration>
    <main-class>package.containing.TransformTool</main-class>
    <arg>${transformIn}</arg>
    <arg>${transformOut}</arg>
    <file>${avroJar}</file>
    <file>${avroMapReduceJar}</file>
</java>

The Tool implementation's main() implementation looks like this:
public static void main(String[] args) throws Exception {
    int res = ToolRunner.run(new TransformTool(), args);
    if (res != 0) {
        throw new Exception("Error running MapReduce.");
    }
}

The workflow will crash with the "Error running MapReduce" exception above every time; how do I get the output of the MapReduce to diagnose the problem? Is there a problem with using this Tool to run a MapReduce application? Am I using the wrong API calls?
I am extremely disinclined to use the Oozie <map-reduce> action, as each action in the workflow relies on several separately versioned AVRO schemas.
What's the issue here? I am using the 'new' mapreduce API for the task.
Thanks for any help.

A: > how do I get the output of the MapReduce...
Back to the basics.
Since you don't care to mention which version of Hadoop and which version of Oozie you are using, I will assume a "recent" setup (e.g. Hadoop 2.7 w/ TimelineServer and Oozie 4.2). And since you don't mention which kind of interface you use (command-line? native Oozie/Yarn UI? Hue?) I will give a few examples using good'old'CLI.
> oozie jobs -localtime -len 10 -filter name=CrazyExperiment
Shows the last 10 executions of "CrazyExperiment" workflow, so that you can inject the appropriate "Job ID" in next commands.
> oozie job -info 0000005-151217173344062-oozie-oozi-W
Shows the status of that execution, from Oozie point of view. If your Java action is stuck in PREP mode, then Oozie failed to submit it to YARN; otherwise you will find something like job_1449681681381_5858 under "External ID". But beware! The job prefix is a legacy thing; the actual YARN ID is application_1449681681381_5858.
> oozie job -log 0000005-151217173344062-oozie-oozi-W
Shows the Oozie log, as could be expected.
> yarn logs -applicationId application_1449681681381_5858
Shows the consolidated logs for AppMaster (container #1) and Java action Launcher (container #2) -- after execution is over. The stdout log for Launcher contains a whole shitload of Oozie debug stuff, the real stdout is at the very bottom.
In case your Java action successfully spawned another YARN job, and you were careful to display the child "application ID", you should be able to retrieve it there and run another yarn logs command against it.
Enjoy your next 5 days of debugging ;-)


text:
Q: MacPorts 2.1.2 git and libsndfile installation I try to install git and libsndfile with port, but I get this messages.
MacPorts 2.1.2
Error: Port git not found
Error: Port libsndfile not found

What is the problem?

A: You can try port search git to search for the right port.
This article will show you how to install the Version Control Git :
Installing git with MacPorts
Do a sudo port selfupdate to updating the MacPorts base sources
then do a sudo port install libsndfile.
You may want to perform a sudo port upgrade outdated to upgrade your installed ports first.


text:
Q: Fourier transform of $e^{it\sqrt{a^2+x^2}}$ The question is clear, I came up with this Fourier transform to calculate while searching explicit solutions for a PDE, but I don't even know if it is feasible.
$
\mathcal{F}_x(e^{it\sqrt{a^2+x^2}})
$
with $x\in \mathbb{R}^n$ if possible. I would really appreciate some help, or references for this kind of transforms.


text:
Q: Get client IP in shared hosting web server I am using HttpContext.Current.Request.UserHostName and HttpContext.Current.Request.UserHostAddress to get client machine name and IP. But it giving me server machine name and IP.
Also, is there any steps to get client local machine IP (Not proxy IP) through JavaScript or jQuery?