Find a system of recurrence relations

Question: Find a system of recurrence relations for the number of $n$-digit binary sequences with $k$ adjacent pairs of $1$s and no adjacent pairs of $0$s.
Any help on how to go about doing this would be appreciated. I'm new to the topic of recursive relations.
Comment: Just want to clarify. You can have as many singletons of 0's and 1's as you like? And 1111 counts as three adjacent pairs of 1's?
Comment: @Brian: $1111$ has three pairs of adjacent $1$s: $\color{red}{11}11$, $1\color{red}{11}1$, and $11\color{red}{11}$. Of more interest to me is whether this is supposed to be a recurrence in both indices, just in $n$ for a fixed $k$, or just in $k$ for a fixed $n$.
Comment: @BrianM.Scott I believe that it is supposed to be a recurrence in both indices, because the range of problems that this one is in is described at the beginning of the section as "requiring multiple indices and equations."
Comment: @Brian: Thanks; I suspected as much, but it's nice to have confirmation.
Answer: Let $S(n,k)$ be the set of $n$-bit binary sequences with $k$ pairs of adjacent ones, and let $$a_{n,k}=|S(n,k)|\;;$$ we want recurrences for $a_{n,k}$.
Suppose that $\sigma\in S(n,k)$. If $\sigma$ ends in $1$, we can append $0$ to get the sequence $\sigma^{\frown}0\in S(n+1,k)$, or we can append a $1$ to get the sequence $\sigma^{\frown}1\in S(n+1,k+1)$. If $\sigma$ ends in $0$, we can only append a $1$ to get $\sigma^{\frown}1\in S(n+1,k)$. This suggests that we may want to keep track separately of sequences ending in $1$ and sequences ending in $0$, so for $i\in\{0,1\}$ let $S_i(n,k)$ be the set of $\sigma\in S(n,k)$ that end in $i$, and let
$$a_{n,k}^{(i)}=\left|S_i(n,k)\right|\;;$$
clearly $a_{n,k}=a_{n,k}^{(0)}+a_{n,k}^{(1)}$.
Now work backwards.

If $\sigma\in S_0(n,k)$, then $\sigma=\tau^{\frown}0$ for some $\tau\in S_1(n-1,k)$, so $$a_{n,k}^{(0)}=a_{n-1,k}^{(1)}\tag{A}\;.$$
If $\sigma\in S_1(n,k)$, then either $\sigma=\tau^{\frown}1$ for some $\tau\in S_1(n-1,k-1)$, or $\sigma=\tau^{\frown}1$ for some $\tau\in S_0(n-1,k)$, and $$a_{n,k}^{(1)}=a_{n-1,k-1}^{(1)}+a_{n-1,k}^{(0)}\;.\tag{B}$$

It follows that
$$\begin{align*}
a_{n,k}&=a_{n,k}^{(0)}+a_{n,k}^{(1)}\\
&\overset{(1)}=a_{n-1,k}^{(1)}+a_{n-1,k-1}^{(1)}+a_{n-1,k}^{(0)}\\
&\overset{(2)}=a_{n-1,k}^{(1)}+a_{n-1,k-1}^{(1)}+a_{n-2,k}^{(1)}\\
&\overset{(3)}=a_{n-2,k-1}^{(1)}+a_{n-2,k}^{(0)}+a_{n-1,k-1}^{(1)}+a_{n-2,k}^{(1)}\\
&\overset{(4)}=a_{n-2,k-1}^{(1)}+a_{n-1,k-1}^{(1)}+a_{n-2,k}\\
&\overset{(5)}=a_{n-1,k-1}^{(0)}+a_{n-1,k-1}^{(1)}+a_{n-2,k}\\
&\overset{(6)}=a_{n-1,k-1}+a_{n-2,k}\;;
\end{align*}$$
step $(1)$ uses both recurrences (A) and (B), step $(2)$ applies (A) to the last term, step $(3)$ applies (B) to the first term, step $(4)$ combines the second and fourth terms to get rid of the superscripts, step $(5)$ applies (A) to the first term, and step $(6)$ combines the two superscripted terms.
An easier way to discover this recurrence, though not to derive it, is to calculate $a_{n,k}$ for $1\le n\le 5$ and $0\le k\le n-1$:
$$\begin{array}{c|cc}
n\backslash k&0&1&2&3&4\\ \hline
1&2\\
2&2&1\\
3&2&2&1\\
4&2&3&2&1\\
5&2&4&4&2&1
\end{array}$$
You can now enter enter the table by rows into The On-Line Encyclopedia of Integer Sequences (OEIS) as
$$2,2,1,2,2,1,2,3,2,1,2,4,4,2,1$$
and get a single return: this matches OEIS A073044. Better yet, the description of this entry reads:

Triangle read by rows: T(n,k) (n>=1, k>=0) = number of n-sequences of 0's and 1's with no pair of adjacent 0's and exactly k pairs of adjacent 1's.

Plainly this is exactly what we want, and the only formulas given are the recurrence above and a generating function
$$G(z,t)=\frac{z(2+2z-tz)}{1-tz-z^2}=\sum_{n\ge 1}\sum_{k=0}^{n-1}a_{n,k}z^nt^k\;.$$

Find a system of recurrence relations


g++ error unrecognized command line option

Question: I'm trying make Makefile.
I get error:
<code>g++: error: unrecognized command line option '-Wl'
g++: error: unrecognized command line option '--out-implib'
</code>
Can someone please explain what's the problem and how can I fix it?
Thanks.
Answer: Please show the entire command line, or nobody is going to be able to help you.
The GCC compiler driver can be called as either "gcc" or "g++" (and on many systems "cc" or "c++").  The -Wl command-line option tells the compiler driver to pass the following comma-separated options to the linker.
You'll want to verify that g++ is in fact the GNU compiler on your system, and not something that pretends to be the GNU compiler.
Note that --out-implib as a linker flag is only applicable on systems that use the PE binary format (that is, Microsoft Windows, ReactOS, older versions of BeOS, and a largely-forgotten operating system called SkyOS).  If you're building software for any other platform, the linker will reject that option.
Anyway, need to see the whole command-line.  If you're using "make" to build the software in question, paste the command line immediately proceededing the error message.  If you're using a "-j" option to make, remove it so as to ensure that you're finding the correct failing invocation.


Replacing rotted out window sill in basement block wall

Question: Long story short - the previous owner hired a crackhead to pave over the dirt driveway. The guy ended up raising the grade beyond the basement window sills on one corner of the house, and here's what it looks like now:
The bottom casings, and sills appear to be completely rotted out at this point:
Rot #1:
Rot #2:
Rot #3:
The basement is finished, and there does not appear to be any water damage inside... yet. I would certainly like to keep it that way.
From inside #1:
From inside #2:
Obviously the first issue that needs to be addressed is drainage around the windows - I have a pretty good plan in place for this which I will be posting separately for critique. What I'm looking for is the best way to replace just the sills without tearing out the whole window.
This is what I was thinking to do:

Cutting the sill on the inside, flush with the window using a toe kick saw / osciliating tool.
Dig/cut/remove any trace of the cut off sill piece from outside.
Rip a 2*2? (not sure the windows frame thickness) and liquid nail it into place.
Attach new casing.
Caulk inside and out.

-Is this the correct approach?
-What about flashing - what is the correct way to use flashing and which flashing to use in this situation?
-Should the replacement sill piece be from pressure treated wood?
Answer: Think about replacing the sill and the casing with some of the PVC or composition boards that are available in the home stores. Any wood you put down there will be rotten again in 5 years.


Where is media folder Id stored in Umbraco database?

Question: URL for an image in Umbraco looks like /media/[Media Folder ID]/[Image name].[Image extension]
Where can I find this [Media Folder ID] in the database?
Comment: Not sure where in the database it is stored but anything created in umbraco has an ID field in Properties Tab which gets used everywhere.
Comment: Why do you need to find the ID in the database?...
Comment: I needed SQL script to export all information about uCommerce products including URLs of their images.
I've already found that URLs of the images from Media library Umbraco stores in dataNtext field of cmsPropertyData table.
Answer: As far as I am aware, Umbraco doesn't store media image folder in the DB.
You can refer to this post to find out where the default media folder is defined:
https://our.umbraco.org/forum/using-umbraco-and-getting-started/77409-upload-media-files-to-folder-extend
The 4 digit ID media folder names found in the "Media" folder are referenced in the various content parts in the DB depending where you have added the particular images (as properties on the nodes).


Load block's content with AJAX

Question: What is the best way, installing as few modules as possible, to load content into a custom block?
My understanding is that an easy way to do it is by creating a page callback that calls drupal_json_output() and then add a Drupal JavaScript behavior to query that page and receive the JSON content.
Are there better ways? Is there any already built-in functionality?
Answer: It looks like the Ajax Blocks module might do what you're looking for.

Load block's content with AJAX


Logical error in comparing character recieved in USART

Question: I Want to compare the character recieved via RX pin of ATMEGA 8. WHy doesn't the comparison work?
<code>int main()
{
   DDRB = 0XFF;
   UCSRB = (1<<RXEN);
   UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
   UBRRL = 0X33;
   char r;
   while (1)
   {
      while(!(UCSRA&(1<<RXC)));
      r = UDR;
      if(r=='r') PORTB = 0XFF;
   }
   return 0;
 }
</code>
Comment: Maybe you are just not receiving the correct char :) What do you have connected to the PORTB? LEDs? Suggestions: 1. Toggle PORTB regardless of what type of char you receive to see if you receive something at all 2. Write the content of UDR to PORTB (both are 8 bit) to verify what you actually received 3. Double check baud rate (UBRRL/H) and terminal settings.
Comment: Thanks a lot. There was actually a problem in baud rates.
Answer: Sample code for easy setting baud_rate
<code>#define F_CPU 8000000UL         // Chip CPU frequency here, prevents default 1MHz
#define USART_BAUDRATE 19200UL  // Baud_rate here, baudrates: 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

#include <avr/io.h>

int main(void) {
    DDRB = 0XFF;
    UBRRL = BAUD_PRESCALE;          // baud to  low byte of the UBRR register
    UBRRH = (BAUD_PRESCALE >> 8);   // baud to high byte of the UBRR register
    UCSRB = (1<<RXEN);
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
    char r;
    while(1) {
        //TODO:: Please write your application code
        while(!(UCSRA&(1<<RXC)));
        r = UDR;
        if(r=='r') PORTB = 0XFF;
    }
   return 0;
}
</code>


Response from database is not received to php file

Question: I have been trying to build a register and login android app using php and mysql with android studio. It appears that the values are being entered to the databse but it is not giving a response back. Table name is harry and  php file is:
<?php
define('DBUSER', 'id650955_gokulm100');
define('DBPASS', 'gokulm100');
define('DBHOST', 'localhost');
define('DBNAME', 'id650955_harry');

$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);

if (!$conn) {
    die('error connecting to database');
}

echo 'you have created case';

if(isset($_POST["username"]) && isset($_POST["email"]) && isset($_POST["phone"]) && isset($_POST["password"]))
{
    $username = $_POST["username"];
    $email = $_POST["email"];
    $phone = $_POST["phone"];
    $password = $_POST["password"];

    $statement = mysqli_prepare($conn, "INSERT INTO harry (username, email, phone, password) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "ssis", $username, $email, $phone, $password);
    mysqli_stmt_execute($statement);
    $response = array();
    $response["success"] = 1;

    echo json_encode($response);
}

else{
    echo "not set";
}
?>

Comment: Your `echo 'you have created case';` would be part of the output. This would corrupt your json string.
Answer: assuming that the data is inserted to the database you need to look at your output, it looks like you're sending json text via json_encode and in the same time echo a string "you have created case"
so your output will be a mix of simple characters and some json string. which probably send a parsing error to the callback in the android side of the code.
first you should add a header that indicates the you will be returning json code  at the top of the file
header("Content-Type: application/json",true);
then change all your output to be json , any
echo "str";
should be
echo json_encode(array("message"=>"str"));
then see if you still don't get any message back.


change date format to dd-mm-yyyy

Question: the current date is showing in dd-mm-yyyy format but when i select the pop up showing in mm-dd-yyyy,after selecting also same thing
i want to change that to dd-mm-yyyy
const today = new Date();
    var journeyDate = new Date(),
        returnDate = new Date();

    journeyDate.setDate(today.getDate() );
    returnDate.setDate(today.getDate() );

    $(".journey-date").val(journeyDate.toLocaleDateString());
    $(".return-date").val(returnDate.toLocaleDateString());

    $(".journey-day-name").html(journeyDate.toLocaleString('en-us', { weekday: 'long' }));
    $(".return-day-name").html(returnDate.toLocaleString('en-us', { weekday: 'long' }));

    $(".journey-date").change(function () {
        var ojd = $(this).closest(".search-form-date").find(".journey-date").val();
        const journeyDayName = new Date(ojd).toLocaleString('en-us', { weekday: 'long' });
        $(this).closest(".search-form-date").find(".journey-day-name").html(journeyDayName);
    });

    $(".return-date").change(function () {
        var rd = $(this).closest(".search-form-date").find(".return-date").val();
        const returnDayName = new Date(rd).toLocaleString('en-us', { weekday: 'long' });
        $(this).closest(".search-form-date").find(".return-day-name").html(returnDayName);
    });

Comment: We are going to need more context to be able to help you.
Comment: Please add enough code to create a [mre]
Answer: First ;
npm install moment --save
you can switch to any format;
moment().format('MMMM Do YYYY, h:mm:ss a'); // February 12th 2024, 10:51:07 am
moment().format('dddd');                    // Monday
moment().format("MMM Do YY");               // Feb 12th 24
moment().format('YYYY [escaped] YYYY');     // 2024 escaped 2024
moment().format();                          // 2024-02-12T10:51:07+03:00

see the docs;  https://momentjs.com/
Comment: How does this address the issue?
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

change date format to dd-mm-yyyy


PowerShell's '-Version' parameter and CLR versions

Question: I have installed the release version of PowerShell v3 and am having some trouble getting the -Version parameter to work. I have quite a few modules that require .NET 4.0, and I have been using PowerShell v2 without issue using the following powershell.exe.config file:
<?xml version="1.0"?>
<configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0.30319"/>
        <supportedRuntime version="v2.0.50727"/>
    </startup>
    <runtime>
        <loadFromRemoteSources enabled="true"/>
    </runtime>
</configuration>

This would allow me to run PowerShell v2 with the .NET 4.0 CLR. Everything worked without issue.
I have now installed the release version of PowerShell v3, and anytime I use the command 'powershell -version 2' and check the $PSVersionTable variable, it shows that it has loaded PowerShell v3 (with .NET 4.0). If I remove the powershell.exe.config file above and run the same command, it shows that PowerShell v2 is loaded but is using .NET 2.0.
So my question is this: Is there a way to load PowerShell v2 and have it use the .NET 4.0 CLR like I used to do before installing PowerShell v3? Or does PowerShell v3 not allow this?
Also, I should mention why I'm trying to do this - mainly in case there are any incompatibility issues that might crop up when we switch to V3. I plan to test everything with V3, but having the ability to drop back to V2 can save us from a lot of headaches.
Answer: What's happening is the following:

Start with -Version 2
Powershell starts, beings to bind to v2 runtime/assemblies.  So far so good.
App.config indicates that .NET 4 runtime should be loaded
As assembly binding progresses, there is a .NET publisher policy that automatically redirects any app built against v2 to v3 when possible

This is normally what you want - if new version is available, automatically use it

Result is v3 runtime/assemblies are loaded, despite your original intention (and Powershell's) to run v2.

This does not happen without the .NET 4 workaround, since v2 will load under .NET 2 by default, and thus it cannot be redirected by the publisher policy onto v3, which requires .NET 4.

Simple, right?!
So what you need to do, if you want to keep PSv2 on .NET 4, is manually disable the publisher policy.  This can be done in the app.config file, see a related post here.
Answer: I don't understand why you want to use v2 with CLR 4 if you have v3 installed. If your modules require .NET 4, use PowerShell v3: It uses CLR 4 already.
Comment: I'm doing it mainly in case there are any incompatibility issues that might crop up when we switch to V3.  I plan to test everything with V3, but having the ability to drop back to V2 can save us from a lot of headaches.
Comment: That's ironic given that running powershell 2.0 on CLR4 is entirely unsupported.
Comment: Unsupported, yet many many people used it. PowerGUI even came configured that way after installation by default.


Using Minecraft execute command to test for players near coordinates

Question: I have been trying to test if a player is at specific coordinates using this command in a command block:
execute as @a[x=-166,y=4,z=-120,distance=3] run say cool

But nothing happens when I trigger it. If I take the distance=3 part out it works even if I'm not at the coordinates stated.
What I'm doing wrong?
Answer: So I did some research, and it turns out that the way [x=X,y=Y,z=Z] works without a distance selector is different than what it used to be:

Selects targets based on distance to that exact position. Combine with
selecting by radius to select only targets at that specific position.

Basically, distance is being automatically filled with the distance from the executing position (in this case, the command block) to the coordinates supplied.
When you use the selector form of distance=3, you're saying you want players that are exactly 3 metres away from the coordinates specified, and given that coordinates are floating point values, that's basically impossible without teleporting them to a specific position.  Instead, you want to use a range, such as distance=2..3 (2 to 3 metres away), distance=..3 (less than/equal to 3 metres away), or distance=3.. (greater than/equal to 3 metres away).
Answer: You can use the positioned component to specify the executing position and then use distance to specify the distance from that position, in your case [distance=0..1].
Unfortunately typing distance=1 or [distance=0] doesn't work, because you have to be EXACTLY at one of these two distances, like millimetres-exact, so you have to use a range of 0 block distance and 1 block distance. And if the execution succeeds when you're still a few steps away from that block, you can change the value of '1' to a number between '0' and '1' like '0.8', which means [distance=0..0.8] (note that the two dots are max/min selectors: if you type any number before the two dots, that's the minimum value, and the one after the two dots is the maximum value).
Comment: You should add an example of a full row of command. Btw, as it is, it looks like your answer haven't brought much more than the one already existing.


having trouble placing a table in a JScrollPane

Question: I have a main class that uses a swing interface. There is a JScrollPane that i can get to show up. I have an actionlistener that fills the table and is supposed to add the table to the JScrollPane. however when i initialize the scrollPane i need to declare (table example) as an argument...cant figure out how to reference it after its been populated. heres the code:
JScrollPane callsScroll = new JScrollPane();
JPanel callsArea = new JPanel();
....
callsArea.add(callsScroll);

callsScroll.setPreferredSize(new Dimension(570, 400));
...
        while (rs.next()) {
        String columns[] = {"Employee ID", "Date", "Billing Type", "DR", "Call Time", "Trouble Code", "Invoice Amount", "Invoice Number"};
        Object data[][]={
             {rs.getString("EmployeeID"),rs.getString("Date"),rs.getString("BillingType"),
                 rs.getString("DR"),rs.getString("CallTime"),rs.getString("TroubleCode"),
                 rs.getString("InvoiceAmount"),rs.getString("InvoiceNumber")
             },
             };

    JTable table = new JTable(data,columns);

            gui.callsScroll.add(table);
            gui.callsArea.add(gui.callsScroll);

    }

i know the table is being populated because i can add it straight to the JFrame. but i cannot get it into the table first. i need to be able to reference the instance of the table after its been populated here JScrollPane callsScroll = new JScrollPane(right here);
******EDIT**************
Object[][] data=null;
     while (rs.next()) {

        data[][]={
             {rs.getString("EmployeeID"),rs.getString("Date"),rs.getString("BillingType"),
                 rs.getString("DR"),rs.getString("CallTime"),rs.getString("TroubleCode"),
                 rs.getString("InvoiceAmount"),rs.getString("InvoiceNumber")},
             };

    }

Answer: Don't add components directly to the JScrollPane as you will replace the scrollpane's viewport, an essential component for scrollpane functionality. Instead you should add the JTable to the scrollpane's viewport:
myScrollpane.setViewportView(myJTable);

Note that when you add a component to a JScrollPane via its constructor, you're actually adding it to the viewport, and this can confuse folks who are starting out working with JScrollPanes.
Also, no need to re-add a component that's already been added to the GUI.
Comment: @derek: As an aside, don't call `setPreferredSize()`; override `getPreferredScrollableViewportSize()`,as suggested [here](http://stackoverflow.com/a/16070046/230513).
Comment: i figured the redundancy was unnecessary but i was just hoping to get something to work. Thank you for your response. That worked. however now i am having trouble referencing the 2d Object array created in the while loop. i tried initializing the variable prior to the loop but then it says illegal start of expression in the loop? ill append my OP to show.
Comment: thank you trashgod. i am now on my third/fourth week learning java, im still learning all the recommended practices
Comment: @derek: your object reference is a distinct and unrelated problem and probably should be asked in a new question. Quite possibly you have a problem of scope, where the 2D array is declared inside of a method or other block and thus is only visible within that method or block.


How to import private network repository into Azure Devops

Question: I have a gitlab was called URL https://gitlab.organization-name.com/ that is a my private network for internal access only. And I have a Azure DevOps account, I wanna import my private network repo in https://gitlab.organization-name.com/username/test-ci-cd.git to my Azure account. Does is it possible for importing? And, How should I do?
*Note: for public network repo like https://gitlab.com/username/test-ci-cd.git, It is work fine.
Comment: Did you try already wth Basic Authentication? https://learn.microsoft.com/en-us/azure/devops/repos/git/import-git-repository?view=azure-devops#import-into-a-new-repo
Comment: Why can't you do a mirror clone to a local computer, add a new remote, and then push it to Azure DevOps?
Comment: @KrzysztofMadej, I have already try, It is not work.
Comment: @DanielMann, I can not do that, because my organization is not allow to store source in public network.
Comment: Azure DevOps is a "public network" (i.e. a cloud-hosted service). So if you can't put your code into Azure DevOps because it's a cloud-hosted service, then what are you trying to do?
Answer: After I contact to support Azure DevOps Enginner Team. He siad "I can not do that Unless I changed my private to public network"


Strings and variables

Question: My Code:
var nameOfMc:String = "";

function moverMc(nameOfMc:String):void {
    nameOfMc.play();
}

function handleCollision( e:Event ):void{
    var _point:Point = localToGlobal(new Point(mouseX,mouseY));

    if(bigCircle_mc.hitTestPoint(_point.x,_point.y,true)){
           output_txt.text = "BIGCIRCLE"
           nameOfMc = "bigCircle_mc";
           moverMc(nameOfMc);
    }else{
        if(circle_mc.hitTestPoint(_point.x,_point.y,true)){
               output_txt.text = "CIRCLE"
               nameOfMc = "circle_mc";
               moverMc(nameOfMc);
        }else{
            if(rect_mc.hitTestPoint(_point.x,_point.y,true)){
                output_txt.text = "RECT"
                nameOfMc = "rect_mc"
                moverMc(nameOfMc);
            }else{
                output_txt.text = ""
                stopAll();
                nameOfMc = ""
            }
        }
    }

My Problem:
In function moverMc I want Flash to do the same as "bigCircle_mc.play();" if the mouse is over the big circle for example, "rect_mc.play();" if mouse over rectangle...
Thanks for help
Answer: Your moverMc function is wrong: nameOfMc is a string, not a display object so you cannot play it: the String type doesn't have a play() method.
What you need to do is find the DisplayObject instance that has the name contained in the nameOfMc variable. (Movie clips are display objects.)
To find a DisplayObject by its name, you can use the getChildByName() function on the container that contains the movie clip that you're looking for. (For example, the Stage can be this container but it can be any other DisplayObjectContainer in the display chain - if your clip is nested inside several other clips, you'll have several DisplayObjectContainer instances in the display chain.)
So your function would be something like this:
function moverMc(nameOfMc:String):void
{
    var oClip:DisplayObject = theStage.getChildByName(nameOfMc);

    if((oClip != null) && (oClip is MovieClip))
    {
        // You need to cast oClip to MovieClip because getChildByName()
        // returns DisplayObject (the base type of MovieClip) but
        // not all DisplayObjects have a timeline.
        (oClip as MovieClip).play();
    }
}

The theStage variable is a global variable (of type Stage) that you have to set to the stage of your Flash movie when it starts. See this SO question for more details on how to do it.
Edit: after the OP's comment I added a version that doesn't need the stage; this just uses the current DisplayObjectContainer to search for children. (Stage is just the top-level display object container but all display objects that can have nested display objects are display object containers.)
function moverMc(parentOfMc:DisplayObject, nameOfMc:String):void
{
    var oClip:DisplayObject = parentOfMc.getChildByName(nameOfMc);

    if((oClip != null) && (oClip is MovieClip))
    {
        // You need to cast oClip to MovieClip because getChildByName()
        // returns DisplayObject (the base type of MovieClip) but
        // not all DisplayObjects have a timeline.
        (oClip as MovieClip).play();
    }
}

You'd call this version like so:
nameOfMc = "circle_mc";
moverMc(this, nameOfMc);

this in the current context refers to the current display object container - this could be the stage or it could be a display object on the stage. You're already using this in your code (perhaps without realizing): the localToGlobal call is really this.localToGlobal.
Comment: Could you explain this theStage variable? I created a new class (according to this page: https://github.com/inruntime/AS3-Global-Object) but I really don't know how things will join together.
Comment: @as3learner I updated my answer with a version of the function that doesn't rely on the stage.

Strings and variables


How to set build variant config fields and resource values in Android Studio 3.0?

Question: Android Studio 3.0 and the associated gradle plugin update have removed the gradle build variant API. Does anyone know how to achieve functionality similar to what i've written below with AS 3.0 and gradle 4.0?
<code>applicationVariants.all { variant ->
   variant.buildConfigField "String", "SEARCH_SUGGESTION_PROVIDER_AUTHORITY", "\"" + variant.applicationId + ".providers.SearchSuggestionProvider\""
   variant.resValue "string", "account_type", "\"" + variant.applicationId + ".account\""
}
</code>
Answer: Read the documentation about flavors and flavor dimensions.
https://developer.android.com/studio/build/build-variants
https://proandroiddev.com/advanced-android-flavors-part-2-enter-flavor-dimensions-4ad7f486f6
it can look like this:
<code>    flavorDimensions "branding"

//
// For each app edition we need one explicit flavor that sets id and signingConfig
//
productFlavors {

    home {
        dimension "branding"
        applicationId "com.example.home"
        signingConfig signingConfigs.home
    }

    free {
        dimension "branding"
        applicationId "com.example.free"
        signingConfig signingConfigs.free
    }

    full {
        dimension "branding"
        applicationId "com.example.full"
        signingConfig signingConfigs.full
    }

}
</code>
There are almost all things possible for each flavor in each dimension.
Hope this helps.
Regarding the resource values:
We here solve this by creating source sets (home, full, free) and set the variant-specific resources in each of the source sets.


Can you splice wires in the middle of a wireless dog fence?

Question: I am trying to build a 'barrier' wireless dog fence.  I could simply run the wire around my whole yard and be done, but much of it is already fenced in and I do not want to restrict access to that fenced in area (Dog likes to meet dogs on other side of the fence.. running the wire would prevent the dog from doing so).
with my yard, I have to cross a driveway and on the outer edge of the driveway, there isn't enough space to loop the wire back (if I need ~6ft space when looping.. I only have about 3-4 ft).
I want to start at the first port, loop down around the front yard, cross the driveway and up the side of the yard to where the Chain link fence begins.  What I want to do there is to splice the wire into two (2) pieces of wire (so 3 way splice). Those 2 wires would then be twisted back close the second port, where I would splice the two back into a single wire.  This is still a continuous loop isn't it?  Why won't this work?  (Will this diminish the wire signal?  Do the wires have to be opposite traveling when twisted to effectively cancel the wire signal?  See attached diagram for a visual.  Any suggestions to accomplish that cancelation across the back part of the house?
Comment: If you can find these, they work great: https://www.gordonelectricsupply.com/p/3M-314-Bin-Self-Stripping-Conn/5761264?msclkid=fb0c2e5ea212108772794d8f3e646a1b  They are filled with grease.
Answer: I have had several wireless fences with one being several acres where I had gates I did splice and twist the wires to make the null signal area , adding the gate areas for horses I did need to turn up the power but it still worked fine with several changes including where the brush hog cut the fence in an area it was not buried even with splices at those points and new sections added of twisted wire the fence still worked well.
Where I spliced the fence I used butt splices and filled them with silicone sealer so the splice would be dry and not corrode when crimped some of the sealer is squeezed out but this makes a really well sealed splice for low voltage I also do this on my boat and the connections last.
Answer: This method will give the dog full access to the whole yard
Run the wire all the way around the back yard along the top of the fence and stone wall. When you get back to the "start" point on the right, you twist it with the wire leading away from the house.
With the proper "width" setting, this will allow the dog to get to the bottom of the fence for a meet & greet, but will prevent him from jumping the fence. He'll also have free reign all the way around the house and won't have to do the "back and forth" around the structure to avoid the one wire run through the middle of the yard (on the "east" side of the drawing).
We have a nice wooden fence in our back yard to contain the dog, but she's terrified of the rain and will jump the fence if it's raining when we're not home. We put the collar on her when we leave and the wire at the top of the fence prevents her from jumping, but gives her full access to run her fence line (as is evidenced by the dead grass at the bottom of the fence from her constant circling).
This method will give the dog a front yard and a back yard
Alternatively, continue the wire run "north" (north is up, right ;) along the driveway to the garage, up the wall of the garage, around the garage, back down to the ground, along the driveway to the house, then up the wall of the house, "east" to the corner, around the corner, then down the wall to the controller.
This will keep the dog from running across the driveway right in front of the car when you're backing out (flat dog = unhappy family). When the wire is up high, under the eaves of the house, it will be out of range of the collar so it won't trigger.
Another full yard method
Similar to the second method, but where you show the wire crossing the grass to the driveway, then from the driveway to the house, bury the wire deeper than the "width" setting so that it won't trigger when the dog crosses the wire. If you've got a 3' width setting, burying the wire 4-5' deep will prevent it from triggering, giving the pooch the full run of the front and back yards.


Can an ~/.ssh/config file use variables?

Question: I am writing an SSH config file and want to perform a bit of logic. For example:
Host myhost1
    ProxyCommand ssh -A {choose randomly between [bastion_host1] and [bastion_host2]} -W %h:%p

Is it possible to achieve the above using (bash?) variables? Thanks!
Answer: Your ProxyCommand can be a shell script.
host myhost1
    ProxyCommand $HOME/bin/selecthost %h %p

And then in ~/bin/selecthost:
#!/usr/bin/env bash

hosts=(bastion1 bastion2)

onehost=${hosts[$RANDOM % ${#hosts[@]}]}

ssh -x -a -q ${2:+-W $1:$2} $onehost

Untested. Your mileage may vary. May contain nuts.
Per comments, I've also tested the following, and it works nicely:
host myhost1 myhost2
    ProxyCommand bash -c 'hosts=(bastion1 bastion2); ssh -xaqW%h:22 ${hosts[$RANDOM % ${#hosts[@]}]}'

Of course, this method doesn't allow you to specify a custom port per host. You could add that to the logic of a separate shell script if your SSH config matches multiple hosts in the same host entry.
Comment: "May contain nuts" Gave me a laugh!
Comment: In this script, the `$onehost` variable is set by selecting a random array element from a bash array.  Your ProxyCommand is executed by your shell, so as long as your shell is bash, I don't see why you couldn't include the entire functionality of this script on a single line, though I haven't tried it.  I answered this way because I don't know that you're using bash as your default shell.  (On my system, I use bash for programming, but tcsh is my default shell.)
Comment: Upvoted for nut warnings too. Six year old answers still fresh!
Comment: Would you be able to point out [what I'm doing wrong here](https://stackoverflow.com/q/55579583/241211)?
Answer: In ~/.ssh/config you cannot have much logic, and no Bash. The manual for this file is in man ssh_config, and it makes no mention of such feature.
What you can do is create a script that will have the logic you need, and make your ssh configuration call that script.
Something along the lines of:
ProxyCommand ~/bin/ssh-randomly.sh [bastion_host1] [bastion_host2]

And write a Bash script ~/bin/ssh-randomly.sh to take two hostname parameters, select one of them randomly, and run the real ssh command with the appropriate parameters.
Answer: No; .ssh/config is not processed by any outside program. You'll need a shell function along the lines of
ssh () {
    (( $RANDOM % 2 )) && bastion=bastion_host1 || bastion=bastion_host2

    command ssh -A "$bastion" "$@"
}

Answer: This can be handled within ssh config by using a helper app.  For example,
Host myhost match exec "randprog"
     hostname host1
Host myhost
     hostname host2

and then randprog will randomly return 1 or 0 (0 will match the first line, giving host1).


I'm getting an error with nginx, php and wordpress - 502 Bad Gateway

Question: Using the sample recipe I am deploying a WordPress solution on EC2:
juju bootstrap --constraints "instance-type=t1.micro"
juju set-constraints instance-type=t1.micro
juju debug-log
juju deploy mysql wordpress-db
juju deploy wordpress
juju add-relation wordpress wordpress-db
juju expose wordpress

After this I point my browser to the public url and get the error:

502 Bad Gateway
  nginx/1.1.19

Looking at the debug log I see this error:
2012-11-10 20:08:19,083 unit:wordpress/0: hook.output INFO:  * Restarting PHP5 FastCGI Process Manager php5-fpm
2012-11-10 20:08:20,267 unit:wordpress/0: hook.output INFO:    ...fail!

sshing to the WordPress box, I tried restarting the php service but I get a seg fault:
ubuntu@ip-10-194-31-77:~$ sudo /etc/init.d/php5-fpm start
Segmentation fault (core dumped)

Anybody know the issue? Is there a problem with the php version and WordPress?
Answer: This is probably a problem with RAM. If you look on your wordpress hosts, they're likely running out of RAM quite quickly, and probably spraying 'out of memory' errors in dmesg. Thats because the default tuning setting of single does include a lot of plugins.
If you run juju set wp-service-name tuning=bare it will use less RAM and it might be able to survive on a t1.micro. If that still doesn't work, I'd recommend filing a bug against the charm here:
https://launchpad.net/charms/+source/wordpress/+filebug
And perhaps look into patching it to allow reducing the number of php5-fpm processes running or other things to save RAM in such a hyper-constrained environment.
Comment: Thanks that tuning trick seems to have fixed the issue!!!
Comment: Tyler, perhaps Accept the answer then, so this doesn't appear as an "unanswered" question?


- initWithCoder: when -decodeObjectOfClass:forKey: returns nil

Question: I'm wondering how to use NSSecureCoding when a given property was nil when encoded. Take the following example:
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    if (self) {

        _buffer = [aDecoder decodeObjectOfClass:[NSMutableData class] forKey:@"buffer"];

        if (_buffer == nil) {
            self = nil;
        }
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder setValue:_buffer forKey:@"buffer"];
}

I created the habit of setting self to nil whenever an allocation fails, as it seems like a correct pattern. However, in this case, if _buffer was nil when encoded, how can I tell that from allocation failure when decoding?
Comment: I don't think you should set self to nil. you create the object and one of its properties is nil. what's wrong about that?
Comment: It's wrong because it has not been properly initialised. For instance, lets say that I was initialising with data (`-initWithData:`). At some point, I would copy the data (`_buffer = [NSMutableData dataWithData:data]`). If after that `_buffer` is `nil` (allocation failed) the object has not been properly initialised. You shouldn't return `self` as if nothing happened, because something did happen. By return `self` (non `nil`) you would be telling the caller that everything wen't OK, and that's not true.
Answer: I'm not sure of the pattern you're trying to handle here, but using setValue: directly on the coder I suspect is odd. I've only ever used, and seen, the encode<SomeThing>: forKey: syntax used. And from what I'm looking at, then trying to decode for that same key is going to result in a bad output.
But you're saying you want to distinguish between a resulting decode that is actually null, and a failure state where you've chosen to return a null value? I'm still not sure why you are handling it that way, but the only way to distinguish would be to choose a different value to store like "The Buffer has a nil value" and then checking for that string on decode, or storing a second key on the coder that you would check against:
if(_buffer == nil){
  [aCoder encodeBool: true forKey: @"wasBufferNull"];
}

Comment: You are absolutely right! I didn't even notice I was using `-setValue:forKey:`. I usually use `-encodeObject:forKey:`, of course. It's a nice idea to encode a second key. It's just a bit unfortunate that `NSCoder` does not handle that, though. I'll give it a few more time before accepting, just in case there's a better alternative out there and somebody responds. Thank you!
Answer: It's been a while since you asked this question. But in case anyone else is still interested to find a solution…
For NSData / NSMutableData, one idea on how to differentiate whether nil as returned by decodeObjectOfClass:forKey: is a result of failing isKindOfClass: checks, versus whether it was actually nil when during  encodeWithCoder:, could be to encode [NSData data] if it was indeed nil during encoding.
For example:
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_buffer ?: [NSMutableData data] forKey:@"buffer"];
}


Can I use the pipe operator as an OR statement?

Question: Im reading an introductory book on shell commands and it suggests using a pipe command as an OR statement like below:
case "$1" in
  start|START)
    /usr/bin/sshd
    ;;
  stop|STOP)
    kill $(cat/var/run/sshd.pid)
    ;;
esac

Why does this work/what is the logic behind it?
Answer: Here it is not the pipe operator. It is within the case syntax. Read man bash and go to the "Compound Commands" sections and read about the case.
Here is the extract of what the bash manual has to say

case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
A case command first
  expands word, and tries to match it against each pattern in
  turn, using the same matching rules as for pathname expansion (see
  Pathname Expansion below). The word is expanded using  tilde
  expansion,  parameter  and  variable expansion, arithmetic
  substitution, command substitution, process substitution and quote
  removal. Each pattern examined is expanded using tilde expansion,
  parameter and variable expansion, arithmetic substitution, command
  substitution, and process substitution.  If the shell option
  nocasematch is enabled, the match is performed without regard to the
  case of alphabetic characters.  When a match  is found, the
  corresponding list is executed.  If the ;; operator is used, no
  subsequent matches are attempted after the first pattern match.  Using
  ;& in place of ;; causes execution to continue with the list
  associated with the next set of patterns.  Using ;;& in place of
  ;; causes the shell to test the next pattern list in the statement,
  if any, and execute any associated list on a successful match.
  The exit status is zero  if  no pattern matches.  Otherwise, it is the
  exit status of the last command executed in list.

This is the syntax
case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
Which is
case "$1" in
start|START)

matches the above syntax which tells at-least one pattern, or more than one separated by a | , a vertical bar.
Answer: As phoxis commented, while it is the same character as that used for pipes, in this context it is part of the special syntax of the case statement to define more than one value that will cause execution of the following statements (up to the ;; delimiter).


Using a FactoryGirl object id in another field?

Question: factory :foo do
  bar # want this to use foo's id in calculating bar's value

  # current solution
  # ugly because it requires an extra save
  after_create { |foo| foo.bar = foo.id; foo.save! }

  # tried this too but foo.id is still nil at this point
  # after_build { |foo| foo.bar = foo.id }
end

Is there a better way to work with the object's id during object creation? This has come up in the scenario outlined above.
It has also come up in another scenario where foo has an ActiveRecord before_create_callback which uses foo.id. With AR, the object has an id when the callback is called and the method does as expected. With FG, the object does not have an id when the callback is called and therefore the method does not behave as expected. Again, I resort to after_create with an extra explicit save.
Any suggestions/tips to working with object id's during FactoryGirl object creation would be greatly appreciated.
Answer: Here's a full example that works outside of rails in irb.  You have to have the proper gems installed however.
Create the tables in sqlite:
sqlite3 /tmp/development.db
> create table foos ( id int, name varchar(50), primary key(id));
> create table bars ( id int, name varchar(50), foo_id int, primary key(id));

Note that this is factory_girl 3.x syntax.
require 'factory_girl'
require 'active_record'
require 'active_support'

ActiveRecord::Base.establish_connection(
  :adapter => 'sqlite3', :database => '/tmp/development.db'
)

class Foo < ActiveRecord::Base
  attr_accessible :id, :name
  has_one :bar
end

class Bar < ActiveRecord::Base
  attr_accessible :id, :name
  belongs_to :foo
end

FactoryGirl.define do
  factory :foo do
    sequence :id do |n|
      n
    end
    name "Foo Name" # use Faker
  end
end

FactoryGirl.define do
  factory :bar do
    sequence(:id) {|n| n }
    association :foo, :factory => :foo
    name "Bar Name" # use Faker
  end
end

bar = FactoryGirl.build(:bar)
puts bar.inspect
# => #<Bar id: 1, name: "Bar Name", foo_id: 1>

You'll notice that you can only run this once because we don't rollback our tables after this runs.  That's because factory_girl figured out an association is needed and wrote the records to the DB even though all we did is a build call.  Normally build doesn't write to the DB.  You can rollback manually:
> delete from foos;
> delete from bars;

Sorry for the very un-railsy example but at least you can play with this on the side without messing with your project.


Evaluate integral using Fourier transform

Question: $\int_{0}^{+\infty }\frac{1}{1+x^{2}}$
using Fourier transform of
$$\mathfrak{F}\left \{ e^{-\left | x \right |} \right \}=\frac{2}{1+\omega ^{2}}$$
I am curious how to approach this. I am looking for hints only.
Answer: Hint
Well, $$ \int_{-\infty}^\infty \frac{2}{1+\omega^2}e^{i\omega x}\frac{d\omega}{2\pi}$$ is the inverse Fourier transform of $\frac{2}{1+\omega^2},$ isn't it? And this, evaluated at $x=0$ is pretty closely connected to what you want to calculate.
Answer: Notice that by evenness $$\int^\infty_0 \frac{d\omega}{1+\omega^2} = \frac 1 2 \int^\infty_{-\infty} \frac{d\omega}{1+\omega^2}.$$
It seems you're using the definition $$\hat f(\omega) = \int^\infty_{-\infty} f(x) e^{-i\omega x} dx$$ meaning that the inversion formula is $$f(x) = \frac 1 {2\pi} \int^\infty_{\infty} \hat f(\omega) e^{i\omega x} d\omega.$$ In your case, using the inversion formula gives $$e^{-\lvert x \rvert} = \frac{1}{2\pi} \int^\infty_{-\infty} \frac{2e^{i\omega x}}{1+\omega^2} d \omega.$$ Can you take it from here?
Comment: Yes.. both of your hints have helped me.


Finding the potential energy of a conservative force

Question:
My solution to show whether each of the forces is conservative is to check whether $\textrm{curl}\, \vec {F}$ is zero. It is $0$ if conservative and not $0$ if not conservative, which I have no problem with. But how can one find the potential energies of $\vec{F}$ from that relationship? I don't really have a clue, and any help would be highly appreciated.
Comment: I like the answers you are getting, but don't some of them have the sign wrong?  $\vec{F}=-\partial U / \partial{ \vec{r}}$ is what we use in physics.
Comment: @LouisB i think you are correct with that yes, thank you.
Answer: Compute the line integral $\int_{\mathbf{a}}^{\mathbf{x}} \mathbf{F} \cdot d\mathbf{r}$, where $\mathbf{a}$ is an arbitrary point. If $F$ is conservative, this is well-defined and has the right derivative (gradient), by the Fundamental Theorem of Calculus for line integrals, and hence it is $U$, up to a constant.
For example, the first one is conservative, and the integral can be computed as
$$ U(X,Y,Z) = \int_{0}^{(X,Y,Z)} x \, dx + 2y \, dy + 3z \, dz = \frac{1}{2}(X^2-0) + (Y^2-0) + \frac{3}{2}(Z^2-0). $$
The second one is also conservative, and $x\frac{dy}{dt} + y\frac{dx}{dt} = \frac{d}{dt}(xy), $
so the potential is $U(X,Y,Z)=XY$.
Answer: If $\bf F$ is conservative, it has some potential $U$, that is, a function for which ${\bf F} = -\nabla U$. Writing this equation in components gives thesystem
$$
\left\{
\begin{array}{rcl}
F_x &=& -\frac{\partial U}{\partial x}\\
F_y &=& -\frac{\partial U}{\partial y}\\
F_z &=& -\frac{\partial U}{\partial z}
\end{array}
\right.
$$
of partial differential equations. Finding a potential amounts to solving this system.
So, for example, for the field $\bf F$ in (a), the system is
$$-\frac{\partial U}{\partial x} = x, \qquad -\frac{\partial U}{\partial y} = 2 y, \qquad -\frac{\partial U}{\partial z} = 3 z .$$
Integrating the first equation gives that $U$ must have the form
$$U(x, y, z) = -\frac{1}{2} x^2 + A(y, z)$$
for some $A(y, z)$, and likewise integrating the second and third equations give respectively that $U$ can also be written as
$$U(x, y, z) = -y^2 + B(x, z) = -\frac{3}{2} z^2 + C(x, y) .$$
Putting these forms together gives that $f$ has the form
$$U(x, y, z) = -\frac{1}{2} x^2 - y^2 - \frac{3}{2} z^2 + K$$
for some constant $K$. We can check that all such functions are solutions, by the way, simply by computing $-\nabla U$ and checking that it coincides with the given $\bf F$.
Comment: should $${\bf F} = \nabla U$$  be$$={\bf F} = -\nabla U$$
Comment: @Gibberish This is a matter of convention. The *scalar potential* of a vector field $\bf F$ is a function that satisfies the first equation (with no minus sign), but when the vector field represents a force usually a negative is used, so that a the force pushes the object from a higher potential to a lower potential. I've changed the signs in my answer for your convenience.
Answer: As an example, if ${\bf F} = (y,x,0)$, then ${\bf F} = \nabla f$ where $f_x(x,y,z) = y$,  $f_y(x,y,z) = x$, and $f_z(x,y,z) = 0$. Now, an antiderivative of $f_x(x,y,z)$ with respect to $x$ is $xy$, an antiderivative of $f_y(x,y,z)$ with respect to $y$ is $xy$, and an antiderivative of $f_z(x,y,z)$ with respect to $z$ is $0$.  Adding together all unique terms of those antiderivatives gives us that $f(x,y,z) = xy + C$ where $C = 0$ in this case since $f(0,0,0) = 0$ by assumption. (Here I used $f$ instead of $U$; sorry).
Comment: May I ask why is it not $2xy$?
Comment: @Gibberish First, confirm that $2xy$ would give you the wrong answer by calculating $\nabla f$. The reason is that from $f_x(x,y,z) = y$, you know that $f(x,y,z) = xy + C_1(y,z)$; from $f_y(x,y,z) = x$, you know that $f(x,y,z) = xy + C_2(x,z)$; and from $f_z(x,y,a) = 0$, you know that $f(x,y,z) = 0 + C_3(x,y)$. Comparing these three expressions for $f$, you arrive at the realization that $f(x,y,z) = xy + C$ for some constant $C$.


using JaxB to unmarshall object which contains List field

Question: I have a Java class which contains a List field.
public class Machine{
    public int ID;

    public String Name;

    public String Status;

    public String Environment;

    public String Cluster;

    public List<String> SupportedLocales;
}

Below is an instance of the class in XML that I am trying to unmarshall.
<?xml version="1.0" encoding="utf-8"?>
<Machine xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <ID>27</ID>
    <Name>QA14ADMINOPM201</Name>
    <Status>Decom</Status>
    <Environment>QA14</Environment>
    <Cluster>ADMINOPM</Cluster>
    <SupportedLocales>
        <SupportedLocale>NA</SupportedLocale>
        <SupportedLocale>Global</SupportedLocale>
    </SupportedLocales>
</Machine>

When I unmarshall the Xml though, the resulting object has an empty SupportedLocales list, with no elements. Any reason why this might be happening or suggested fixes? All other fields are being unmarshalled correctly.
Answer: Annotate your field with an XmlElementWrapper annotation:
@XmlElementWrapper(name = "SupportedLocales")
@XmlElement(name = "SupportedLocale")
public List<String> SupportedLocales;

Also try to follow the convention of using variables that start with a lowercase (supportedLocales instead of SupportedLocales). This would need to map the XML element name for each field as follows:
@XmlElement(name="ID")
public int id;

@XmlElement(name="Name")
public String name;

@XmlElement(name="Status")
public String status;

@XmlElement(name="Environment")
public String environment;

@XmlElement(name="Cluster")
public String cluster;

@XmlElementWrapper(name = "SupportedLocales")
@XmlElement(name = "SupportedLocale")
public List<String> supportedLocales;

Comment: Yes you can specify the mapping for each field using annotations. Updated my answer.
Comment: Yes, and the conventions ;-)
Comment: @manouti thanks! And I would use camel case but the classes I'm creating are based on C# classes and the field names need to match the C# names so that objects gotten from the API can be deserialized into Java classes. I don't know a way around it.


How do I change the user home folder name?

Question: I have a buyer for my desktop PC with a fresh installation of Ubuntu 14.04.  I need to change the home folder name from robert to james.  I've managed the other tasks like hostname, user name, user password.   After attempting to change the home folder name:  grub/recovery/root shell:
mount -o remount,rw /
usermod -d /home/james -m robert
reboot

I can't get past the greeting screen login.  When I enter James' password, the screen blanks briefly then opens again at that same login screen.
Comment: Why renaming the user account? Are there any important settings or data files you really want to sell together with the computer hardware? If not, just delete the old user account after creating a new admin user. Or even better (I personally would never give any data storage away before that!) overwrite the entire disk with a special data shredding tool (like "Darik's Boot And Nuke" / DBAN) and reinstall a clean system to make sure the purchaser can't recover any sensitive data.
Comment: I set the robert desktop up with Docky and Mac themes, minimizing the unity panel.   The buyer likes it that way also.  Oh, I used BootitNG to wipe the HD.   Not worried about what might be left on the HD.   Came from an auction.
Comment: Ok, so I added James in system settings/user accounts, account type administrator, and a unique password.   At Greeting screen I can choose from robert or james.   But, I want the james desktop to look exactly like the robert desktop.   Can that be done ?
Comment: You should ask that in a comment below @Rinzwind's answer. I think he can help you better with that. However, I think simply setting that desktop configuration for the new user again could probably be faster, easier and more stable than figuring out what to copy...
Comment: Yep,  I re-worked the desktop for James like it was with Robert.   Took about 20 min. to do that.   No actual solution to my question, but I'm going with this now.   Thanks !!
Answer: I would have done it like this:

create user "james";
switch sudo account to "james";
move over personal files to "james". "chown"/"chgrp" them to "james";
check you can log into "james". If not and login is shown, check ~/xsession-errors for notices.
remove "robert".

When I enter James' password, the screen blanks briefly then opens again at that same login screen.

The answer to this problem is probably shown in ~/xsession.errors. You can also just remove ~./Xauthority. That one needs specific permissions for login to success (has to be rw- --- --- and owned and group set to the user.)
Comment: As the computer is to be sold, I don't really think that there would be any personal data that should stay on it. I personally would rather run a boot-and-nuke to securely overwrite the entire disk and then reinstall a fresh system before selling it. You know, simply deleted files can often easily be recovered and there's usually more data remaining on a system than you know of. For example one could see what pictures you had on your computer by looking at the thumbnail cache, and that's just one example. Just because you are not paranoid does not mean that they won't come for you. ;-D


Inequality problem

Question: How might one show that $1\over 2m$$[\sigma_p^2+\mathbb E(p)^2]$ +$m\omega^2\over2$$[\sigma_x^2+\mathbb E(x)^2]$ $\geq \omega \sigma_x\sigma_p$?
The immediate thing I think would help is $(\sigma_p-\sigma_x)^2\geq0 \implies\sigma_p^2+\sigma_x^2\geq 2\sigma_p\sigma_x$. But then...?
Added: $m,\omega$ are positive constants. $\sigma_x,\sigma_p$ are standard deviations of $x,p$ respectively.
Thanks.
Comment: What are $m$ and $\omega$?
Comment: Symbols defined. :)
Comment: @H.V. I think the connection to standard deviation is not that relevant as far as this question is concerned. So I removed the [standard-deviation] tag and added the [algebra-precalculus] tag. Hope that's ok.
Comment: @Srivatsan: Sure!
Answer: I assume this is taken from physics textbook or so. In particular, I assume $m$ (for mass),  $\omega$ (angular frequency?), as well as $\sigma_x$ and $\sigma_p$ (standard deviation terms) to be positive. The symbols are now defined.
Then the The given inequality follows by applying the AM-GM inequality to the nonnegative quantities $\frac{\sigma_p^2}{m}$ and $m \omega^2 \sigma_x^2$:
$$
\frac{1}{2} \left( \frac{\sigma_p^2}{m} + m \omega^2 \sigma_x^2 \right) \geq \sqrt{\frac{\sigma_p^2}{m} \times m \omega^2 \sigma_x^2} = \omega \sigma_p \sigma_x.
$$
Alternatively, you can also deduce this by expanding:
$$
\frac{1}{2} \left( \frac{\sigma_p}{\sqrt{m}} - \sqrt{m} \cdot \omega \sigma_x \right)^2 \geq 0.
$$
The two other terms involving $\mathrm{E}(x)^2$ and $\mathrm{E}(p)^2$ are nonnegative, so they do can be safely added to left hand side of the inequality.
Comment: You are very right, this indeed has a Physics context. :) Thanks for the enlightenment.

Inequality problem


Exit strategy: where would people go without Chess.SE?

Question: Just discovered that a good SE got shutdown recently due to "poor business": http://productivity.stackexchange.com
I expect it is only a matter of time before Chess.SE suffers the same fate. So, this is the place for remaining users to share their thoughts on this matter.
Comment: IIRC, the OP started projecting the doom of chess.SE at least 5 years ago. Is chess as well-suited to the SE format as, say, coding? I'd say obviously not, given the evidence. But chess.SE has grown over time, and clearly serves some purpose to some group; maybe that will be enough for SE to keep it going, maybe not. But I fail to see the point of this post, especially from one who's made a total of 16 posts on the main site in the span of almost 6 years. Chess.SE has never been what OP wants it to be; but the OP also doesn't seem to be a party genuinely interested in the success of the site.
Comment: success of what exactly? I fulfilled my commitment wrt to the SE as proposed, but it has nothing to do with the celebration of mediocrity or experts of trivia.
Answer: The lack of activity (in the form of questions and answers) wasn't the only reason Productivity (and another recent case, Startups) Stack Exchange were shut down. It also was because of the lack of moderation; Productivity had only one active ♦ moderator and Startups had none. A repeated call for help on the site's respective child metas didn't get a response.
A lack of ♦ moderator activity can be compensated by active regular users who perform moderation tasks like closing questions and deleting non-answers. (In fact, that's the preferred way of moderation; Stack Exchange is moderated by you !) The regulars here are doing (in my opinion, which should be taken with a grain of salt because I'm one of them) a decent job of keeping the site clean. But perhaps one of our moderators wants to chime in on this?
Comment: Not every Stack Exchange needs experts, sites like [cooking.se] and [astronomy.se] are mostly hobbyists.
Comment: "But perhaps one of our moderators wants to chime in on this?" I'll just second Glorfindel's point that the ideal is for the community to moderate itself. A few years back, I (and the other mods as well) was *much* more active on the site than I am now; I'd say I haven't needed to be, because there is indeed a current crop of seasoned regulars who keep things going the way an SE site generally should.
Comment: You cite numbers, but having good/adequate moderators to moderate bad/inconsequential content is a bad sign. Chess.SE does not meet the usual standards of expert participation, unless the site gets rescoped into NoviceChess.SE
Comment: As a side point: it might indeed be time for some new blood in the mods, especially since there are at this point plenty of folks who would handle the role well and who are much more active than the 3 of us at present. If someone were to advocate for such, I'd certainly support the notion.
Answer:
a good SE got shutdown recently due to "poor business"

This isn't an accurate representation of the position of SE overlords. See the full statement.
The reason for shutdown wasn't "no profit", "low traffic" or "few questions": there are SE sites with less traffic and fewer questions asked than Productivity, yet they remain. If the call for moderators was met with at least a bit of enthusiasm, the Productivity site would still be here. See Graduation, site closure, and a clearer outlook on the health of SE sites
Chess has three moderators (appointed back in 2012) who still visit regularly: two in last week, the third visited two weeks ago. Flags get handled  without unusual delays.  And looking at the list of active users I see some that would likely step up, should there be a call for additional moderators.
Exit preparedness
First, there is Board and Card Games site, where chess is on topic. If this site had to shut down, I expect its content would be migrated there.
Setting up a new site on another platform is a large task but not an unimaginably huge one: the new platform could be, for example, Discourse. There are weeks between shutdown notice and execution: (Productivity had 3 weeks).
Existing content is an issue.  Look for a Q&A platform able to digest SE content, including the chess notation parser. (I'm not sure one exists out of the box; one probably has to make modifications to open source Q&A software.)
Perhaps the most practical way is to set up a static site rendering the content of "Chess 2012-20xx" and start from scratch elsewhere. Jeremy Banks has an archival project for failed SE sites ("collapsed stacks"), for example Startups. If a static, browsable site exists, it can be used for references and also to draw some of the search engine traffic which can then be directed to  the new site.
Comment: Okay, we've established that you are unhappy here and the goal of this thread is to proclaim doom rather than learn anything about SE. I don't want to stand in the way of your pleasure, so go ahead: Chess.SE is doomed. __DOOMED__!
Comment: @prusswan: please add some cool questions yourself to raise the tone
Comment: Votes and traffic are quite different. Traffic comes mostly from random onlookers (90%). Voting requires participation. Example: [Android.se] has lots of traffic and little voting activity in comparison.  In any case, SE Community Team makes those decisions, and their goal is not having headaches due to non-moderated sites.  It's not like Productivity consumed a lot of electricity on its own. The marginal cost of carrying an existing site around is negligible __when__ that site moderates itself.
Comment: Productvitiy.SE has much better content quality, so citing lack of moderators is just an excuse. They point to vote activity, and that exactly is business/traffic for SE. The fact that they are putting moderation ahead of content, and that Chess.SE persists despite the poor content, should be cause for concern.
Comment: @prusswan some things can only be handled by diamond mods (e.g. comment flags, *need mod intervention* flag). Without those mods, a certain part of moderations basically die, and that will endanger the site's quality in the longer term.
Comment: Ironically, Productivity.SE has less moderation issue compared to Chess.SE (which is mostly reduced to haven for novices, their content gives "headaches" to experts). The question of relevance was never resolved, as there is not a single question from here that cannot be asked on a leading chess forum. These may not be final reasons that lead to site closure, but surely they explain why content quality will never get any higher.
Comment: Chess.SE is not serving its intended purpose when it is reduced to a "Beginners section". The quality of content here is so low that half its population do not even realize it and continue to pat each other on their backs.
Comment: @Laska it is pointless since I am expecting expert content. and the SE failed in its original purpose to curate expert content. I might as well browse it like a regular forum since the votes are useless in establishing authority. At least on playing sites, you can get a gauge of everyone's playing strength.


How to fix smashed wires in washing machine?

Question: I believe the motor capacitor with its bracket fell down and pinched two wires going to the motor. I spliced them back with two blue wire nuts. The motor works again.

However, this made me thinking, can I leave this as permanent solution or is there disaster going to happen if wire nuts come off (there were 2 14 or 16 awg wires that were rejoined)? Should I get Wago connectors instead? Solder? Crimp? Or change the whole harness? What's the best practice?
Comment: I'd suggest you add a little tape to the nuts, to keep them from vibrating loose.
Answer: The wire nuts will be fine. I do not like push in wago connectors but love lever locks. In high vibration equipment sometimes I will lock the wire nuts with some electrical tape but if properly installed with 2 twists of the wire I have not had them come loose , I just like the idea that the tape water proofs the connection.
Comment: i was thinking about the  waterproof connections but then figured none of the other connections under there were waterproof.+
Comment: I was thinking about wago 221 lever nuts as the wires I joined are stranded and not solid.
Comment: I found lever locks a few years back. At first I only used them on light fixtures but have branched out on some projects where a 5 position lever nut is faster than a small terminal strip and so far I have not had a failure so I would agree they would be a good choice here.
Answer: If you connected the right wires together and followed the directions on the wire nut package then you're good to go. They are as good as the spade connectors as far as connecting wires. If a wire nuts did come off, which would be no different than a wire coming off the capacitor, and come in contact with the frame, it would trip the breaker because the machine is grounded (should be). That's why grounding is so darn important.
Comment: We said similar at the same time +
Comment: Good point about grounding, but this is dryer+washer combo machine that operates on 240V, not 120v. I believe for 240V plugs there is no GFCI level protection as frame is connected to neutral, right? And the 240V ground protection is not that sensitive as more current has to go through before it trips compared to a 120V GFCI?
Comment: @HansSolo I'd have to see the name plate. Appliances that run on 240V often have 120V controls or motors. what part of the planet are you on? Yes, GFCI protection is much more responsive than tripping a breaker through  a grounded neutral fault. That's why it exists.
Comment: @JACK. This is US and the washer dryer combo is fex831fs4.
Answer: Make very sure that the wire insulation in other places has not been beaten thin, beaten hard, stretched thin, or cracked - such defects could, especially in a vibration-rich environment, lead to delayed insulation failure.
Comment: Yeah, there is another beaten wire that could be beaten. Would running washer and checking if the beaten area gets hot be a good test if I need to splice it too?
Comment: No, this would be a very evil test, and it could destroy more. Best to get an assortment of good quality hookup wire (mind that you get the same wire gauge and voltage rating!!), and replace ANY suspect wire.


How to loop ArrayList and send each value to Download Manager?

Question: I am trying to send ArrayList(VideoUrlArrayList) values inside a for loop to Android Download Manager but i keep getting following error:
error: incompatible types: String cannot be converted to Uri

and pointing to this line:
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
fileName = VideoUrlArrayList.get(i).substring(VideoUrlArrayList.get(i).lastIndexOf("/"));

if i remove the part of code that sends urls to Download Manager the toast displays the arrayList(VideoUrlArrayList) values correctly !
Could you guys help me fix this problem and successfully send values of my ArrayList to Download Manager?(Furthermore, I want to use the original file names from urls stored in VideoUrlArrayList).Thanks
MainAcitivty.java:
public class MainActivity extends AppCompatActivity {

    private DownloadManager downloadManager;
    private long refid;
    private String fileName;
    ArrayList<Long> list = new ArrayList<>();
    ArrayList<String> VideoUrlArrayList =new ArrayList<String>();

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

        registerReceiver(onComplete,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        TextView btnMultiple = (TextView) findViewById(R.id.multiple);

        if(!isStoragePermissionGranted())
        {

        }

btnMultiple.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                list.clear();

                EditText editText1 = (EditText) findViewById(R.id.editText);
                String linesArray[] = editText1.getText().toString().split("\n");

                for (int i = 0; i < linesArray.length; i++) {
                    String currLine = linesArray[i];

                    VideoUrlArrayList.add(currLine);

                }

                for (int i = 0; i < VideoUrlArrayList.size(); i++) {

                    //Toast.makeText(getApplicationContext(), "Array Text: " + VideoUrlArrayList.get(i), Toast.LENGTH_LONG).show();

                    DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));
                    fileName = VideoUrlArrayList.get(i).substring(VideoUrlArrayList.get(i).lastIndexOf("/"));

                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                    request.setAllowedOverRoaming(false);

                    //Set the title of this download, to be displayed in notifications (if enabled).
                    request.setTitle("Demo Downloading " + fileName);

                    //Set a description of this download, to be displayed in notifications (if enabled)
                    request.setDescription("Downloading " + fileName);

                    //Set whether this download should be displayed in the system's Downloads UI. True by default.
                    request.setVisibleInDownloadsUi(true);

                    //Set the local destination for the downloaded file to a path within the public external storage directory (as returned by getExternalStoragePublicDirectory(String)).
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);

                    refid = downloadManager.enqueue(request);

                    Log.e("OUTNM", "" + refid);

                    list.add(refid);

                }

            }
        });

                   //the rest of code after this

}

Answer: Make this line:
DownloadManager.Request request = new DownloadManager.Request(VideoUrlArrayList.get(i));

to:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(VideoUrlArrayList.get(i)));

DoesnloadManager.Request() accepts Uri not String. So you need to parse it to Uri.
Comment: Thanks for reply. I tried it and i get this error: error: Uri is abstract; cannot be instantiated
Comment: Now i don't get error while compiling but when i run the program and enter some urls to textbox and press button the program closes!(Unfortunately demoApp has stopped).Even the toast doesn't display the arrayList data!
Comment: This is now a different problem, you should provide a code and logcat for this or raise it as another question. And please trim down your question to the specific problem you're encountering.


How can I tell which street crimes I have solved?

Question: Related to my other question about street crimes in Free Play mode - how can I see my progress on street crimes for each desk? I couldn't see anything in the Free Play menu when I chose a desk, and the in-game statistics just show a total out of 40.
I was wondering if there was a way to double-check that I was indeed being given the same street crimes a second times, rather than, say, a bug/other issue where my progress wasn't saved.
Answer: I don't know if you can tell from the case selection screen, but when you're in Free Play mode, you can check the map.  Street crimes you've solved are shown as gray icons (I believe they look like a person walking) on the map.  If all you see is gray icons, you've done all the street crimes for that desk.
If you see one you haven't done, you can set it as your waypoint, and then you'll get that crime immediately - without having to wait for the dispatcher to work its way around to that one.  This really helps if there's just one or two crimes left to go on a desk, or if there's a set of them close together that you'd like to tackle as a group.
This guide seems to back me up, and also makes note of a couple of other caveats:

How do you know which ones you have completed?
The ones you've completed show up as grey on the map and the ones you havent will be red. Free roam shows all available street crimes at that time frame [whereas] in-story only shows when [you're] in the vicinity.
Comment: I also had [Rockstar Social Club](http://socialclub.rockstargames.com/) interaction turned on (which I highly recommend if you're going for 100% completion in this game), which may have been a factor.
Comment: As far as I can remember, the little running man icons don't show up on the map until central dispatch calls you about them. So this would probably work for crimes you've already been called about, but not the rest. I will double-check my map, though.
Comment: I feel like when I went back to the "free play" map, I could see *all* of the crimes, even ones that I'd never gotten a call about.  I don't have my copy handy to check at this point, though.
Comment: You're right - I checked my map and there were a bunch of icons there.


Where should RBAC be implemented?

Question: To give you some background, I have frequently worked with RBAC implemented on the SQL level, but I read in some articles that it might not be very scalable.
Should RBAC be implemented on, say:

On the Database level (i.e. row or column based access control)
On the Application level (i.e. logic in the code) perhaps with some document storage support
On some other level

What are the pros and cons of each approach in terms of scalability and what is the gold industry standard?
Comment: I don't think there is a gold standard, it would depend on your application, but generally speaking RBAC becomes a problem when your app has too many roles, because you'd have to fetch the user's roles prior to doing anything, which would impact performance (if you care about that)
Answer: As  per my experience RBAC in case of B2B and B2C apps,
Application level is widely implemented and accepted.
on same note
if you like  you could  give below a shot

The above RBAC is part of current ongoing boilerplate platform below
Nodejs_Postgresql_VanillaJS_Fastify

Where should RBAC be implemented?


foreground color wont be changed in controlTemplate

Question: I am using WPF. Please look at comment related to Foreground in code. When the textbox gets focused, the font should be changed to white but it is not working. Why?
<code> <ControlTemplate TargetType="{x:Type TextBox}">
                <Border x:Name="bg" BorderBrush="#FFDCDCC9" Background="#FFDCDCC9" BorderThickness="1">
                    <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                </Border>
                <ControlTemplate.Triggers>

                    <Trigger  Property="IsMouseOver" Value="True">
                        <Setter  Property="BorderBrush" TargetName="bg" Value="#FFEC94C0"/>
                        <Setter  Property="Background" TargetName="bg" Value="#FFEC94C0"/>
                        <Setter Property="BorderThickness" TargetName="bg" Value="2"/>
                        <Setter Property="Cursor" Value="Hand"/>
                    </Trigger>

                    <Trigger Property="IsFocused" Value="True" >
                        <Setter Property="BorderBrush" TargetName="bg" Value="#FFB5266E"/>
                        <Setter  Property="Background" TargetName="bg" Value="#FFEC94C0"/>
                        <!-- foreground is invalid -->
                        <Setter  Property="Foreground" TargetName="bg" Value="white"/>
                        <Setter Property="BorderThickness" TargetName="bg" Value="2"/>
                        <Setter Property="Cursor" Value="Hand"/>
                    </Trigger>

                </ControlTemplate.Triggers>
            </ControlTemplate>
</code>
Comment: Is your `IsMouseOver` trigger overriding the `IsFocused` Trigger?
Comment: The TargetName="bg" looks like it is targeting the Border element. What happens when you remove the TargetName="bg" designation?
Comment: @Evanlewis yes correct
Comment: @KristianK if TargetName is removed, color background and borderbrush of IsMouseOver and IsFocused is gone....
Answer: Border does not have a foreground.  Remove TargetName from the equation... I believe it will work then.  It should look like below (also if this is a resource itt will need a key).  This worked fine my end.
<code><ControlTemplate x:Key="a" TargetType="{x:Type TextBox}">
        <Border x:Name="bg" BorderBrush="#FFDCDCC9" Background="#FFDCDCC9" BorderThickness="1">
            <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Border>
        <ControlTemplate.Triggers>

            <Trigger  Property="IsMouseOver" Value="True">
                <Setter  Property="BorderBrush" TargetName="bg" Value="#FFEC94C0"/>
                <Setter  Property="Background" TargetName="bg" Value="#FFEC94C0"/>
                <Setter Property="BorderThickness" TargetName="bg" Value="2"/>
                <Setter Property="Cursor" Value="Hand"/>
            </Trigger>

            <Trigger Property="IsFocused" Value="True" >
                <Setter Property="BorderBrush" TargetName="bg" Value="#FFB5266E"/>
                <Setter  Property="Background" TargetName="bg" Value="#FFEC94C0"/>
                <!-- foreground is invalid -->
                <Setter  Property="Foreground"  Value="white"/>
                <Setter Property="BorderThickness" TargetName="bg" Value="2"/>
                <Setter Property="Cursor" Value="Hand"/>
            </Trigger>

        </ControlTemplate.Triggers>
    </ControlTemplate>
</code>
Comment: No look at 6th row from bottom... Target Name is remove... DO NOT remove x:Name of the border.  If you remove the TargetName from the Setter item you XAML then looks at the control itself which is a TextBox.  Textbox has a foreground property.  Border does not
Comment: you can also set multi triggers if your problem is that "mouse over and IsFocused interfere with each other.  Obviously it will not interfere if there is no mouseover when textbox has focus etc.  But you can have MouseOver + Focus setters and MouseOver + Unfocus setters through multi triggers.
Comment: If I bind Textbox's Template to this control template and I run the project with exactly the same code as what I gave you.  When I "enter" the textbox to "type" the text is white.  What color is your text come up as?... does the other properties change when textbox has focus?  is there perhaps somewhere in code behind that you override this?
Comment: okay let me look at my code that probably overrides it. thanks for ur advice :)
Comment: For future FYI, it worked for me,
``


Specify from what index to start looping in a foreach loop

Question: The content if pulled from a while loop that I used to fetch a query. I need to sort the content from different starting point of the array, let's say results from indexes 5to 8 and ignore 0 to 4 or 9 to 12.
<?php
$i='0';
foreach($articulos as $articdos){
?>

  <a href="efecto.php?libelula=noticias&artic=<?= $articdos['id']; ?>&gen=<?= $articdos['genero']; ?>&id=<?= $articdos['id'] ?>">

    <img src="img/chica/<?= $articdos['foto']; ?>" alt="" />

      <?= $articdos['titulo']; ?>

<?php
if ($i++ == 3) break;
} ?>

As it is right now it all starts from index 0 and I want it to start after the 6th index... Can this be done?
Comment: In a foreach loop, it's got to start at the beginning since it's not using specific indexes.  The only way around that would be to use a different query to get only the results you actually want to loop through.  However, by using a counter, you could check your counter and only perform actions once your counter is from 5-8 or whatever you want.  The foreach loop would still loop through all results, but would only perform specified actions on the counted iterations you wanted it to.
Comment: The thing is I don't want to use more than one query to minimize db connections.  I know I can put in practice your suggestion for the while loop but I would have to generate more than one query, Am I on the wrong track?
Comment: There's more than one way to accomplish this, but you could keep your single query and just use the counter like I said above.  Having the foreach loop run through iterations in which it does nothing while waiting for the counter to indicate the iteration you want will take very little time while doing exactly what you want to do here.
Comment: Is it better to use a for loop then?
Answer: Here's how you could do this using a counter:
<?php
    $i = 0;
    foreach($articulos as $articdos){
        if ($i >= 5 && $i <= 8) {
?>
    //Your HTML code here
<?php
        } // end if block
        $++i;
    } // end foreach loop
?>

During the loops where the if statement is false, no HTML code will be executed or output, and unless you're looping through thousands of records, the time taken during those loops where nothing is done will be negligible.
Instead of testing for a number, you could also test the data inside $articdos if you were only looking for specific records with specific data in them.
Comment: I see, instead of using break to end the loop you specified the start and end on an if. Love it.
Thank you Sgt AJ.


TVOS: UIButton action not working in subview

Question: in the TVOS Application storyboard mainview I added a subview.
Within the subview there are 3 button created in the very same way (the code here belongs to the subview)
<code>UIButton *b = [UIButton buttonWithType:UIButtonTypeSystem];
b.frame = CGRectMake(left, top,     400, size);
[b setTitle:@"Click Me" forState:UIControlStateNormal];
[b addTarget:self action:@selector(Action_Up) forControlEvents:UIControlEventPrimaryActionTriggered];
[self.view addSubview:b];
...
-(void)Action_Up {
    [self ShowData];
}
</code>
in the simulator and on the real device I can select the button and press it, but the action is never fired.
Could you help ?
Comment: Pretty much the same problem here, can't even solve it using pressesBegan:WithEvent:
Comment: Who has the focus? the button or the view ?
Comment: I guess the button, because it can be selected by the remote.
Comment: Check whether the button frame is inside the view's frame. In some case, if the view's frame is smaller than the button's position, then everything works fine except the user interaction. You can easily find this easily by adding bg color to the view.
Answer: Try this.. it worked for me
<code>        button.addTarget(self, action: "someMethodName:", forControlEvents: .PrimaryActionTriggered)
</code>


Representing duplicate values in a chart

Question: I'm working with a basic chart in c# and I have come across a problem in my code whereby if I have a duplicate category in my table, with a different date, the category is duplicated in my table.
I think this could be solved in SQL rather than C# but i'm a bit stumped.
Here is my table:

Here is my code:
if (selectedLocation == "All")
{

string selectAllQuery = "SELECT category, counter, date, locationName FROM categoryData WHERE locationName IN (@location, @location2, @location3) AND date BETWEEN @startDate AND @endDate ORDER BY locationName, category";
SqlCommand cmd = new SqlCommand(selectAllQuery, con);
cmd.Parameters.AddWithValue("@startDate", startDate);
cmd.Parameters.AddWithValue("@endDate", endDate);
cmd.Parameters.AddWithValue("@location", "Front Desk");
cmd.Parameters.AddWithValue("@location2", "Harold Cohen");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    this.resultChart.Series["Footfall"].Points.AddXY(reader.GetString(0), reader.GetInt32(1));
    resultChart.ChartAreas["main"].AxisX.Interval = 1;

As you can see, if I have a duplicate category with a different date, the category is duplicated.  I'm trying to sum the values of rows two of which have duplicate values.
Edit:  Ive got a bit further and now I ca aggregate rows with common category but I want to add the counter up for each aggregated column.
SELECT category, COUNT(id) as count, locationName FROM categoryData WHERE locationName IN (@location, @location2, @location3) AND date BETWEEN @startDate AND @endDate GROUP BY locationName, category ORDER BY locationName, category

Comment: You should probably use a GROUP BY in your select, on the field "category", and then select the SUM() of "counter". But doing so, you can't extract the fields "date" and "locationName" as is. If you don't need them though, you can omit them
Comment: Ive found the solution and edited my code to reflect.
Comment: You should add: "SUM(counter) as Counter" in the Select list. That sums the counters for all elements in the group
Answer: Agreeing with Alex Zen.
Your query should return all values, but each row in the DB will be returned as its own result, because the program does not know what you consider the 'same category'. You can either add a GROUP BY in code (with linq) or in T-SQL and specify what you consider the same (in this case Category) and you should be able to sum up your totals for that category.
Comment: can you give me an example of using the group by statement, i cant get it to work.  Thanks.


Auto drop down change based from previous selection

Question: I am wanting to change a drop-down selection based on a selection from the previous selection. So I have a database for to store the values which is for a car make and model. The structure is id, make, model
Currently, I have a function to get the make and then get the model and then call the function for the Make selection and then the Model selection but it shows all of them and I do not want that.
So how would I do this?
I have searched around on here and have seen stuff but I am still confused and inexperienced on doing this.
Don't really think you need any of my current code but if you do please let me know.
Comment: You need to use `ajax` and `jquery` or `javascript`. Check this [link](https://stackoverflow.com/questions/11237900/first-drop-down-menu-to-auto-change-the-options-of-a-second-dropdown)
Comment: Ok, I will take a good at it thanks.
Comment: Possible duplicate of [Selected drop down dynamically using javascript when page reload and will change another dropdown and so on](https://stackoverflow.com/questions/45705095/selected-drop-down-dynamically-using-javascript-when-page-reload-and-will-change)
Answer: Im not so sure what you mean, but based on my understanding,
You have two dropdown selects,
one as the parent select and the second is the child select,
the child select dropdown values depends on the parent select,
is that what you meant?
if it is,
a simple way to do this, is to use jquery and ajax,
You have to read basic ajax and event listeners to do this,
1st select dropdown,
<code><select id="parent_select">
</select>

<select id="child_select">
</select>
</code>
/* This will populate your parent select */
<code>$.ajax({
    url: 'url that will display all list'
    dataType: 'json',
    type: 'get',
    success: function(data){
      var output = "";
       $.each(data, function(a,b){
          output += "<option value='"+b.id+"'>"+b.parent_select_name+"  </option>"
        $("#parent_select").append(output);
       });
    }
})
</code>
/* This will populate your child select upon changing the values of your parent */
<code>$(document).on("change", "#parent_select", function(){
  var parent_id = $(this).attr("id");

     $.ajax({
         url: 'url that will display child data where parent_id = parent_id ',
         type: 'POST',
         dataType: 'json',
         data: { 'parent_id' : parent_id } /* you are passing parent_id*/
         success: function(data){
              $("#child_select").empty();
              var output = "";
              $.each(data, function(a,b){
                  output += "<option id="+b.child_id+">"+b.child_desc+"</option>";
              })
              $("#child_select").append(output);
         }
     })
})
</code>


How to select specific column from parent and child in laravel

Question: Please see my code below.
Controller
$orders = Order::with('product:id,name')
    ->select([
            'id',
            'order_number',
            'ordered_on',
            'status',
            'total'
        ])
        ->where('customer_id', session('customer_id'))
    ->orderBy('ordered_on', 'DESC')
        ->paginate(6);
    dd($orders);

Order model
public function product()
{
  return $this->belongsTo(Product::class);
}

The result above returns null when you check the product relationship data.
What I need
Select specific columns from Order model, then select specific columns from product relationship.
Comment: inside the `->select()` u have to include the foreign key `product_id`
Comment: @ericmp woow, any reference with that? it is working now.
Comment: im hardly trying to find the docs on this but cant find it lol
Answer: You need to add the foreign key that you are referencing:
->select([
    'product_id'
    ...
])
...

When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.

Docs: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading-specific-columns


Need to have 2 different div stretched to the screen with one div in center

Question: I want to achieve following structure.
http://s15.postimg.org/aeno9dpmz/screen_shot.jpg
What I have done so far is this.
I have tried to set the two div's on the side with width in % and middle div with width: 300px all three div have float:left
The issue I am facing is

space on the right for large screen
last div falls down for small screen.

I would only prefer
 not

Answer: You need to Add few more div's inside right and left div
and set the outer div to width: 50%;
And keep the middle content in center with margin: 0 auto
and pulling it down with minus margin

.container {
  background: #ccc;
}

.outerWrap {
  background: #dfdfdf;
  padding: 20px 0;
}

.rightCnt,
.leftCnt {
  width: 50%
}

.innerCnt {
  background: #2a4675;
  color: #fff;
}

.leftCnt .innerCnt {
  text-align: right
}

.rightCnt .innerCnt {
  background: #072a26;
}

.rightCnt .innerCnt {
  margin-left: 170px
}

.leftCnt .innerCnt {
  margin-right: 170px
}

.txtCnt {
  min-height: 60px;
  padding: 10px;
  width: 280px
}

.midCnt {
  width: 300px;
  margin: -10px auto -90px;
  background: #fff;
  padding: 10px;
  border: 1px solid #ccc;
  min-height: 80px
}
<link href="https://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

Aliquam tincidunt mauris eu risus.

Vestibulum auctor dapibus neque.

Aliquam tincidunt mauris eu risus.

Vestibulum auctor dapibus neque.

Vestibulum auctor dapibus neque.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

Aliquam tincidunt mauris eu risus.

Vestibulum auctor dapibus neque.

Answer: keeping the rules in percent seems to work for me:
.midCnt {
  width: 36%;
  background: #fff;
  padding: 2%;
  border: 1px solid #ccc;
  min-height: 80px;
  box-sizing:border-box;
}

UPDATED CODE
is this what you're looking for?
Answer: By using CSS3 Flex method you can achieve the desire result. See the DEMO First.
HTML Code is like this.

uno

due

tre

CSS Code is here
.flex
   {
      /* basic styling */
      width: 100%;
      height: 200px;
      border: 1px solid #555;
      font: 14px Arial;
      /* flexbox setup */
      display: -webkit-flex;
      -webkit-flex-direction: row;
justify-content: center;
      display: flex;
      flex-direction: row;
   }
   .flex > div
   {
      -webkit-flex: 1 1 auto;
      flex: 1 1 auto;
      width: 30px;
   }

   /* colors */
   .flex > div:nth-child(1){ background : #009246; }
   .flex > div:nth-child(2){ background : #F1F2F1; }
   .flex > div:nth-child(3){ background : #CE2B37; }


What would be the cost of bandwidth on google cloud platforms if i make a video calling app?

Question: Zoom provides video streaming services, and I made one of my own and considering deploying it on google compute, it says the bandwidth will cost $110 for 1TB if I use it in a month. The cost is pretty much high if we charge a fee like zoom.
If I want to deploy such service it would cost very high considering only bandwidth. What will be an estimate if i had 100 meetings rooms open and in each meeting room 50 participants are there , What would be the estimated cost if they are active for 8 hours per day?
What will be approximate bandwidth they would use considering variable quality of stream, may be 240p, 360p or 720p, considering on the user side they are able to receive the full quality of stream?
Is google calculates egress on the basis of computed data or the amount of data sent to the user regardless of computation of data or a direct download of file?
Person having a good knowledge of google compute please answer.
Thanks in advance.
Comment: This question seeks opinions that will vary and is off topic. I voted to close. Read this link https://stackoverflow.com/help/on-topic
Answer: Google simply calculates the egress or the data sent from the VM considering what goes out of the VM whether it is processed or not.
The price of egress is roughly $0.12/GB, for latest rates visit gcloud pricing calculator.
The egress totally depends upon the number of users downloading or accessing the data on the VM.
So suppose at 240p 40kbps of data is needed on the client side, so
considering 100 rooms with 50 persons each comes to be 5000 clients connected to the VM at an instance.
So, conducting a meeting which lasts 8 hours a day, the egress from the VM would be
5000*(40kbps)*(8*3600 seconds)
= 5*40*8*3600 MB
= 5760000 MB
= 5760 GB

And the cost of such egress would be
5760 GB * $0.12/GB
= $691.2

So, if you have such high bandwidth usage and you want a cheaper option try using digital ocean, their bandwidth is cheaper than gcloud and AWS
Answer: There are to many variables to be able to calculate a price, or even egress, however there is a tool available for platform pricing that you can use based on estimates. Cloud Platform Pricing Calculator Hopefully this will be able to give you the information you are seeking
Comment: I tried that but my question is egress is what goes out simply, or it is cpu computed data which goes out.
Comment: As I have mentioned before, there are to many variables, costs are calculated depending on how your deployment is made. The best recommendation I can give is to use the free trail and attempt small scale tests, and this will give you a good idea of exactly how deployment plays a role in costs. https://cloud.google.com/free


How to execute a JS Script stored in a string on Html code stored in a string

Question: I don't even know if what I'm asking is possible or not, I'm fairly new to web development.
Here is what I'd like to achieve:
I need to execute a JS script on a web page. The script returns some keywords related to that page.
I get the JS script from a remote server and I store it in a string.
The only thing I know about the web page is its url, so I get the content of the page with jQuery.
Here is what I tried (I know it looks stupid, but it illustrates what I'm trying to achieve):
// Let's say I want to execute that script on www.google.com's page
$.get("www.google.com", null, function(data) {

    let myScript = localStorage.getItem('my_script')

    // What I tried so far (it doesn't work, of course)
    var temp = document.createElement('div')
    temp.innerHTML = data
    var resultsOfMyScript = temp.firstChild.eval(myScript) // not a function
})

Do you have any idea on how I could do that?
Comment: Why not create a script element?
Comment: What do you mean?
Answer: Try this:
const script = document.createElement('script')

script.type = 'text/javascript'
script.charset = 'utf-8'
script.text = "console.log('this is my script')"

document.body.appendChild(script)

Substitute .text for the string you mentioned.
Comment: Do you mean `.textContent`?
Comment: No, that wouldn't work. Setting `textContent` will insert the tag but won't execute the script. Setting the `text` property will :) try it in DevTools or see https://developer.mozilla.org/en/docs/Web/HTML/Element/script
Comment: Thanks slezica, but that would not take care of the remote page I'm trying to execute the script on (c.f. `data`in my code sample)
Comment: `.text` and `.textContent` appear to return same result http://plnkr.co/edit/WFbJpymutLKQqC2NvRRv?p=preview