text:
Q: How to add angular velocity vectors? I was reading David Morin's mechanics book and came across this problem.

And here is the solution provided:

I am just wondering why you can express the total angular velocity of the coin with respect to the lab frame by simply adding the different angular velocity vectors. In the earlier part of the book, there's is a theorem:

Clearly in this case, angular velocity vector from the rotation about the centre of the contact-point circle ($\mathbf{\Omega}\mathbf{\hat{z}}$)and the angular velocity vector from  the rotation about $\mathbf{\hat{x_3}}$ do not share a common origin (if you extend a line from the centre of the coin perpendicular to the surface of the coin, it clearly will not always pass through the centre of the contact-point circle).
I think my understanding is flawed. Why can you add angular velocities in this case?

A: Starting with the rotations matrix
\begin{align*}
  &[\,_1^3\,\mathbf S\,]=[\,_1^2\,\mathbf S\,]\,[\,_2^3\,\mathbf S\,]\quad\Rightarrow\quad
  [\,_1^3\,\mathbf{\dot{S}}\,]=[\,_1^2\,\mathbf{\dot{S}}\,]\,[\,_2^3\,\mathbf S\,]+
  [\,_1^2\,\mathbf S\,]\,[\,_2^3\,\mathbf{\dot{S}}\,]\\
  &\text{with}\quad \mathbf{\dot{S}}=\mathbf{\tilde{\omega}}\,\mathbf S\quad
  \mathbf{\tilde{\omega}}= \left[ \begin {array}{ccc} 0&-\omega_{{z}}&\omega_{{y}}
\\  \omega_{{z}}&0&-\omega_{{x}}\\
-\omega_{{y}}&\omega_{{x}}&0\end {array} \right]\quad\Rightarrow
\\\\
  &\mathbf{\tilde{\omega}}_{13}[\,_1^3\,\mathbf{{S}}\,]=
  \mathbf{\tilde{\omega}}_{12}[\,_1^2\,\mathbf{{S}}\,]\,[\,_2^3\,\mathbf S\,]+
  [\,_1^2\,\mathbf S\,]\,\mathbf{\tilde{\omega}}_{23}[\,_2^3\,\mathbf{{S}}\,]\\\\
  &\text{multiply from the right with}\quad [\,_3^1\,\mathbf{{S}}\,]\\\\
  &\mathbf{\tilde{\omega}}_{13}=
  \mathbf{\tilde{\omega}}_{12}\underbrace{[\,_1^2\,\mathbf{{S}}\,]\,[\,_2^3\,\mathbf S\,][\,_3^1\,\mathbf{{S}}\,]}_{I_3}+
  [\,_1^2\,\mathbf S\,]\,\mathbf{\tilde{\omega}}_{23}\underbrace{[\,_2^3\,\mathbf{{S}}\,][\,_3^1\,\mathbf{{S}}\,]}
  _{ [\,_2^1\,\mathbf S\,]}\\
  &\text{thus the angular velocity vector}\\
  &\mathbf\omega_{13}=\mathbf\omega_{12}+[\,_1^2\,\mathbf S\,]\mathbf\omega_{23}
\end{align*}
\begin{align*}
 &\text{with}\\
 &[\,_1^2\,\mathbf S\,]=\left[ \begin {array}{ccc} \cos \left( \psi \right) &-\sin \left(
\psi \right) &0\\  \sin \left( \psi \right) &\cos
 \left( \psi \right) &0\\  0&0&1\end {array} \right]
\quad,
[\,_2^3\,\mathbf S\,]=\left[ \begin {array}{ccc} 1&0&0\\ 0&\cos \left(
\phi  \right) &-\sin \left( \phi  \right) \\  0
&\sin \left( \phi  \right) &\cos \left( \phi  \right)
\end {array} \right]
\\
&\mathbf\omega_{12}=\begin{bmatrix}
               0 \\
               0 \\
               \omega_\psi \\
             \end{bmatrix}\quad
 \mathbf\omega_{23}=\begin{bmatrix}
                \omega_\phi \\
                0 \\
                0 \\
              \end{bmatrix}
\end{align*}


text:
Q: Localstorage in array What I'm trying to do is get the user's email and name input and .push it into the array emailbook, it does push the .values of the email and name into the array but whenever I store it into the localstorage, it replaces the existing array. Help please thank you!!
<script>
        document.addEventListener("DOMContentLoaded",docIsReady);
        var emailbook;
        function docIsReady(){

            emailbook=localStorage.getItem("emailbook");

            if (emailbook==null){
                emailbook=[];
                console.log(emailbook)
            }
            else {
                emailbook=JSON.parse(emailbook);
                console.log(emailbook)
            }
        }
        function store() {
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var obj = {"name": name, "email": email};
            emailbook.push(obj);
            localStorage.setItem("email", JSON.stringify(emailbook));
        }
        console.log(localStorage);
        //var storedemail = JSON.parse(localStorage.getItem("email"));
    </script>

A: How about reading localStorage in store() method, pushing everything to emailbook array, pushing obj and saving it in localStorage?
Something like this:
var name = "foobar";
var email = "mail";
var emailbook = [];
var obj = {"name": name, "email": email};
if(localStorage.getItem('email') != null) {
    var tmp = JSON.parse(localStorage.getItem('email'));
    for(let i = 0;i<tmp.length;i++) {
        emailbook.push(tmp[i]);
    }

}
emailbook.push(obj);
localStorage.setItem("email", JSON.stringify(emailbook));

redpajama_set_name: RedPajamaStackExchange


text:
Q: access denied exception using connector/j mysql I am using mysql and connector/j, trying to connect to the database on my localhost, following this tutorial.
Here is a part of the code I am using:
String url = "jdbc:mysql://localhost:3306/mysql";
Connection con = DriverManager.getConnection(url,"root", "");

And I am always getting this exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO)
There is no default password for the root, and I did not changed it. I can connect to the db from the mysql prompt with the same parameters. I added a new database and user from prompt, tried to connect with that user and pwd, and still get the access denied exception. Do somebody know what could be the problem?

A: seems like you got the problem describe in this thread

A:
There is no default password for the root, and I did not changed it.

Perhaps someone or something else did!
I suggest that you go through the procedure of resetting the MySQL root account's password ... and this time set it to something.
The instructions for resetting the root password are in Appendix C 5.4.1 of the manual (MySQL 5.0 and later).  For example, here.

A: Looking at what you have done everything seems correct.
String url = "jdbc:mysql://localhost:3306/mysql";
Is the name of your database mysql? I feel that is where you are making the mistake. Change the mysql after localhost:3306/ to the name of your db


text:
Q: Unable to set QQmlApplicationEngine rootContext Property I've got the following code that I thought should make a "backend" C++ object available in QML elements of my GUI, but seems to be failing, resulting in a property of my QML objects that is null.
    //Initialize the engine, register the Data_Client object and set the "client" property
    QQmlApplicationEngine engine;
    QQmlContext *context = engine.rootContext();
    const QUrl url(QStringLiteral("qrc:/qml/gui.qml"));

    qmlRegisterType<Data_Client>("uri", 1, 0, "Data_Client");
    qmlRegisterType<StatusObject>("uri", 1, 0, "StatusObject");

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    Data_Client client();
    //Make the Data_Client accessible in the engine root context so its available to all component instances
    context->setContextProperty("client", &client);
    return app.exec();

In the ApplicationWindow item of the gui.qml file, the client property is declared and various connections are declared with the "client" as the target:
property Data_Client client
//...
Connections {
        target: client
        onNew_data:{
        //...
        }

In the Data_Client C++, I call emit new_data(QString("test")); but never trigger the handler in the QML.  This formerly worked and I thought was so fundamentally simple that I was good to go, so I haven't determined what I may have broken.  My operating theory right now is that this is not setting the client property of the rootContext, but there's no check I can make at runtime, is there?  Is there something obvious that I'm missing?

A: In theory, setContextProperty can be called at any time, but any QML files that are already loaded at that time probably will not see that new property. QML files loaded after that point will see it. So calling setContextProperty before you call engine.load() should fix the problem for you.


text:
Q: How can I delete my account? How can I delete my Stack Exchange account(s)? Also,

*

*What happens to my content? Can I request it be deleted as well?

*What if I'm suspended, rate-limited, or banned from posting questions or answers?

*What will happen to my votes? Will other users be impacted?

*Why wasn't my account deleted immediately after the timer expiring?

*What will happen to my pending bounties and close, reopen, delete, or undelete votes?

*I want my account deleted on all Stack Exchange sites. How do I do this?

*Will my profile on chat be removed once I delete my site account?

For more information, see "How do I delete my account?" in the Help Center.

Return to FAQ index

A: If you want to delete your profile on a single site, the Help Center explains how.

*

*On your user page (on the main, not child meta, site), click "Settings".

*Click the "Delete Profile" link:

*Read the page that will appear carefully. If you're sure you still want to delete, mark the checkbox.

*Click the Delete Profile button:

The page can be immediately accessed with sitename.com/users/delete/current
After doing this, one of these two things will happen:

*

*If you have never made any posts using your profile, and have 101 or less reputation, your account will be immediately deleted.

*Otherwise, the account will be scheduled for deletion. During that time, you can cancel the deletion request by visiting your profile and clicking the cancel link in the banner at the top. Otherwise, it will be deleted after (approximately - see below) 24 hours.

Following this process on a single site will only delete your account on that site, and will not affect any other site accounts that are linked to your network profile. If you want your account deleted on all sites, see I want my account deleted on all Stack Exchange sites below.
I can't follow the above instructions to delete my account. What can I do?

*

*Suspended users: If you are suspended, you will get an error message when opening the Edit Profile page because you cannot edit your profile while suspended. You can still access the Delete Profile subpage though, either through the help center article, by selecting the "I need to delete my user profile" option on the contact page, or by navigating to /users/delete/current on the site you want to delete your account.

*Area 51 profiles: As Area 51 runs off a significantly older version of the Stack Exchange software, the ability to delete your own account is not implemented there. You may request deletion of your Area 51 account by using the contact form there. Choose "Other" and write that you want to delete your Area 51 account. Then, change your Area 51 username to "delete" and your Area 51 about me to "Please delete this profile."
Why is there a 24-hour timer for deletion?
The 24-hour waiting period exists to better emphasize that deleting your account is irreversible - you cannot later request that your account be restored (see the next section). To prevent people from "rage-quitting" and regretting it later, the system provides a final opportunity to decide against deleting one's account.
What happens to the reputation and badges I've earned? Can I request my account be restored?
All reputation and badges you've earned on your account will be erased. Posts will generally not be deleted, but will be dissociated - i.e. will no longer be "owned" by an account, so you will cease to have special privileges on them. Any votes on your posts will no longer earn reputation for any account, though other users can still start and award bounties on them.
You cannot later request that your account be restored - if you later decide to rejoin the site, you will start off as a brand new user. You will not be able to regain ownership or reputation of your prior posts; you must start building your privileges as a new user. (Do note that in most cases, if you've earned the network-wide association bonus rights, and you create an account with the same credentials you earned the association bonus on, your new account will start off with the bonus. This does not apply if your account was deleted in a way that erases all personal information, such as through a GDPR request.)
What happens to my content? Can I request it be deleted as well?
Content you've posted on the site is owned by you, but licensed to Stack Exchange, and you therefore cannot request that it be deleted with your account. Your posts will be effectively dissociated from your account; your username will no longer show on them, but it will instead show your denormalized username (e.g. "user123456" where 123456 was the user ID of your account).
However, certain posts you've made that have a score of -1 or lower will be deleted by the Community user immediately once your account is deleted: this includes answers, closed questions, and open questions with no positively-scored answers. Additionally, any questions you've asked that have a score of 1 and otherwise meet the automatic deletion criteria for "abandoned" questions (1 year old, no answers, low views, etc.) will be automatically deleted once the automated deletion script runs every week. These only apply on main Q&A sites; on meta sites, no posts are automatically deleted for any reason as a result of account deletion.
Will deleting my account clear any restrictions placed on my account?
No, it won't. Deleting your account while you are suspended by a moderator or rate-limited or banned by the automated quality filter will not remove any restrictions placed on your account. They will simply be re-applied to any new accounts you create.
What will happen to my votes? Will other users be impacted?
Unless you've cast a lot of votes, your votes on questions and answers will be invalidated and other users will have their reputation recalculated as if your votes were never cast. Additionally, other users will lose reputation from approved suggested edits where you were the final approver. (Bounties you awarded will be kept.)
If you did cast a lot of votes, your votes may be kept (or more accurately, moved to the Community user) to prevent high-impact, widespread changes to other users' reputation. See the next section for more info.
Why wasn't my account deleted immediately after the timer expiring?
Accounts are not deleted immediately after the timer expires, but by a scheduled task that runs once an hour. Thus, you may see a notice that says "this account is scheduled for deletion [x] minutes ago", e.g. "5 minutes ago". This is intentional and by design; your account will be deleted within an hour of the timer expiring provided you haven't cast a lot of votes.
If your account has cast a lot of votes, it will not be deleted approximately after the 24-hour timer expires, as above. Deletion will be held up while a Stack Exchange employee checks your account to determine if your votes should be preserved (in most cases, they are, but in some cases, such as your account having a history of voting fraud, they aren't). During this hold-up, you may see a deletion notice that says that your account is scheduled to be deleted for some date in the past; this is confusing, but not a sign of a bug.
The queue of accounts awaiting deletion is processed every Wednesday and Friday, excluding holidays. This means that if your account falls into this queue, it could take up to three business days for your deletion request to be processed. If you requested deletion during the annual winter holiday season (the second half of December plus the first week of January), your deletion will not be processed until well into January, due to the long holiday period and the backlog of accounts awaiting deletion.
If your account has not been deleted and it's been more than three business days (weekdays, excluding U.S. holidays) since the timer has expired, or if you requested deletion during the winter holiday period and the request hasn't been processed into the month of February, it's possible that your request may have slipped through the cracks somehow; send a contact request using the contact form to let the staff know.
What will happen to my pending bounties and close, reopen, delete, or undelete votes?
If you had any pending bounties or votes while your account is deleted, those will be moved to (owned by) the Community user. In the case of bounties, you can no longer manually award them and they will be awarded automatically at the end as they normally would.
I want my account deleted on all Stack Exchange sites. How do I do this?
There are two ways to do so:

*

*You can go to every single site on which you have a profile and request deletion on all those individually. (If you have an Area 51 profile, use the above procedure to request that just that profile be removed, and use the normal button to request deletion of your other accounts.) This will retain your association bonus rights on the network if you've earned it, should you later decide to rejoin the network under the same credentials.
Your network profile on stackexchange.com will be automatically deleted within 24 hours (whenever it attempts to sync again), unless you have ever manually logged in directly on stackexchange.com - in that case, you have a physical profile there and it will need to be deleted by staff. Contact us once all your account deletions have been fully processed, and we'll get it deleted.

*If you want to ensure that all your personal data is removed, you can submit a data request to erase your account. This will cleanly remove all your site profiles as well as your network profile and credentials. Note that if you use this option and you've earned the association bonus, your association bonus rights will be removed, as the credential information required to retain it is removed. Your network profile on stackexchange.com will also be removed as part of the process.
You may find some older posts that say that you must contact us to request deletion of all your site accounts, but we no longer accept such requests except under the specific form noted above.
Will my profile on chat be removed once I delete my site account?
Chat profiles are automatically deleted when the last qualifying site account is removed. This means that:

*

*On the sites with their own separate chat servers (Stack Overflow and Meta Stack Exchange), deleting your account on one of these sites will also delete your corresponding chat profile on the respective site-specific server (chat.stackoverflow.com or chat.meta.stackexchange.com).

*All other sites on the network have their chat rooms hosted on the general Stack Exchange chat server (chat.stackexchange.com), where if you've chatted in the past you'll have one profile that is shared with all sites. Your profile on that server will be automatically deleted once all of your site accounts are deleted (including accounts on Stack Overflow and Meta.SE).

Note that your chat profile on a given server will not be deleted if you've posted 1,000 or more messages in the past with your profile on that server, or if your (last) site account was deleted prior to August 2016. If you'd like your chat account deleted and it wasn't removed when you otherwise qualified under the above criteria, contact SE to request it.
Miscellaneous information

*

*Your old username will continue to be visible in comments that reply to you, as well as in the Stack Exchange Data Explorer until it gets updated at the end of the week and in monthly data dumps published when your account was active.

*Other users will lose the +2 rep awarded to them if you were the final user to approve one of their suggested edits. This is an anti-abuse feature. This applies regardless of whether your votes were preserved.

*If you've posted questions or answers that were later migrated to another site, and you delete and later recreate your account on the target site, those posts will be reattributed to your current account. (This is an exception to the normal rule that you can't reclaim ownership of your prior posts. This does not apply if your account was removed in a way that removes all personal information, such as through a data erasure request.)

*Any (current or past) moderator election nominations you have made are removed when you delete your account.
See also

*

*What does "user was removed" mean and why did my reputation change because of it?

*How can I delete my Stack Exchange Data Explorer account?


text:
Q: Checking registry value changes via modbus tcp I use the EasyModbus library to connect the computer with the microcontroller.
Problem:
I need to read global registers / variables on the microcontroller via ModbusTCP <> it is not a single reading, it must check the state whether the given register has changed and assign its value to the variable / field (close to real time)
I tried :
In any method I can read the registers via ReadHoldingRegisters, the class itself doesn't have this option anymore.
public static ModbusClient modbusClient = new ModbusClient();

void sth
{
 int[] registers = modbusClient.ReadHoldingRegisters(2500, 5);
}

Does anyone have any idea how to solve this / can someone direct me?

A: You'll need to poll the microcontroller, Modbus does not have support for events or similar features.


text:
Q: nodejs server - mac terminal crash every one hour I got  a live server running nodejs chat app. I connect to server using terminal on mac. I start the server by typing server.js.
the problem is, my terminal always hung after one hour running, and there are no error outputs. when it hangs, I press ctrl+c I got the message [process completed].
note: My terminal runs node apps locally without any problems.
And my current chat app run well when I initiate it with WinSCP in windows platform.

A: Try launching your node process on the remote server using a tool like nohup.
bash$ nohup /path/to/node server.js > out.txt 2> err.txt &
[1] 53032
# Now you can logout of the remote server without
#   killing the "node" process and chat server.

[Edit]
Note that the number printed by "nohup" (e.g. 53032) is the id of detached process, so if you need to terminate it you can do something like "kill -9 53032".  If you forgot to record that number then you'll have to find it by using a program such as "ps"; for example, you can run "ps auxwww | grep node" (the flags will vary depending on your system) and you'll see output similar to this:
maerics  81694   0.6  0.5  2543604  21216 s000  S+   10:34AM   0:09.45 /Users/maerics/opt/node/node server.js

In this example, on my system, the number in the second column is the process id.


text:
Q: How to convert a data frame from wide to long with multiple columns I have a data frame like this that was produced using the 'reshape' function. I was wondering whether there was an 'opposite' to the reshape function that allows me to turn a data frame from wide to long based on multiple columns?
I have this:
ID     Date.1       Site.1     Brand.1   Date.2      Site.2   Brand.2
A-001  2021-05-21   Place A    Brand A   2021-06-01  Place B  Brand C
A-002  2021-05-19   Place D    Brand A   2021-05-19  Place D  Brand D

But would like this:
ID    Seq   Date        Site     Brand
A-001 1     2021-05-21  Place A  Brand A
A-001 2     2021-06-01  Place B  Brand C
A-002 1     2021-05-19  Place D  Brand A
A-002 2     2021-05-19  Place D  Brand D

Thanks!

A: We can use pivot_longer
library(tdyr)
pivot_longer(df1, cols = -ID, names_to = c(".value", "Seq"), names_sep = "\\.")

-output
# A tibble: 4 x 5
#  ID    Seq   Date       Site    Brand
#  <chr> <chr> <chr>      <chr>   <chr>
#1 A-001 1     2021-05-21 Place A Brand A
#2 A-001 2     2021-06-01 Place B Brand C
#3 A-002 1     2021-05-19 Place D Brand A
#4 A-002 2     2021-05-19 Place D Brand D

Or using reshape from base R
reshape(df1, direction = 'long', varying = list(c(2, 5), c(3, 6), c(4, 7)))

data
df1 <- structure(list(ID = c("A-001", "A-002"), Date.1 = c("2021-05-21",
"2021-05-19"), Site.1 = c("Place A", "Place D"), Brand.1 = c("Brand A",
"Brand A"), Date.2 = c("2021-06-01", "2021-05-19"), Site.2 = c("Place B",
"Place D"), Brand.2 = c("Brand C", "Brand D")), class = "data.frame",
     row.names = c(NA,
-2L))


text:
Q: Prevent firebase test labs from clicking ads I used Firebase Test Lab to test my app before uploading it to Google Play.
Looking at the screenshots and video it looks like real ads are displayed from admob and then clicked on.
Now I know you can set test devices to show test ads but I cannot find any ids for firebase test devices, or can I in code somehow identify that this is a robo test so I can prevent real ads?
Also I wonder if google play pre launch report tests has the same issues?

A: You can detect if the device is running in Firebase Test Lab in your code by looking for the environment variable firebase.test.lab as documented in the official documentation.
String testLabSetting = Settings.System.getString(getContentResolver(), "firebase.test.lab");
if ("true".equals(testLabSetting)) {
    // Do something when running in Test Lab
}

The same will work for Google Play Pre Launch reports.

A: It is now being filtered
AdMob now ignores clicks which it receives from devices running inside our infrastructure.

You can read this article and the comment section.
https://danielvido.medium.com/be-extremely-careful-with-pre-launch-reports-on-android-9f43c090bf4d


text:
Q: Flutter textfield layout This is what I want:

And this is what I got:

Here is my code:
      Container(
          margin: EdgeInsets.only(top: 10, bottom: 5),
          decoration: BoxDecoration(
            color: Color(0xFFEEEEEE),
            borderRadius: BorderRadius.circular(12),
          ),
          constraints: BoxConstraints(
            minHeight: 25.0,
            maxHeight: 100,
            minWidth: MediaQuery.of(context).size.width,
            maxWidth: MediaQuery.of(context).size.width,
          ),
          child: Scrollbar(
            child: TextField(
              keyboardType: TextInputType.multiline,
              controller: inputTextController,
              maxLines: null,
              style: TextStyle(
                  color: Colors.black,
              ),
              decoration: InputDecoration(
                contentPadding: EdgeInsets.symmetric(horizontal: 13, vertical: 13),
                border: InputBorder.none,
                hintText: 'Type a message',
                  hintStyle: TextStyle(
                    color: Color(0xff99999B),
                  )
              ),
            ),
          ),
        ),

Tried wrapping the container with row but it overflows. Also tried wrapping the TextField with Row but the TextField disappear. Is there any solutions?

A: Wrapping your TextField Container with Flexible before you wrap it with Row, solves the problem mainly.
Here is the entire code:
Row(
      children: [
        Flexible(
          child: Container(
            margin: EdgeInsets.only(top: 10, bottom: 5),
            decoration: BoxDecoration(
              color: Color(0xFFEEEEEE),
              borderRadius: BorderRadius.circular(12),
            ),
            constraints: BoxConstraints(
              minHeight: 25.0,
              maxHeight: 100,
              minWidth: MediaQuery.of(context).size.width,
              maxWidth: MediaQuery.of(context).size.width,
            ),
            child: Scrollbar(
              child: TextField(
                keyboardType: TextInputType.multiline,
                // controller: inputTextController,
                maxLines: null,
                style: TextStyle(
                  color: Colors.black,
                ),
                decoration: InputDecoration(
                    prefixIcon: Icon(Icons.mood, color: Colors.black45),
                    suffixIcon: Icon(Icons.camera_alt, color: Colors.black45),
                    contentPadding: EdgeInsets.symmetric(horizontal: 13, vertical: 13),
                    border: InputBorder.none,
                    hintText: 'Type a message',
                    hintStyle: TextStyle(
                      color: Color(0xff99999B),
                    )
                ),
              ),
            ),
          ),
        ),
        Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.blue,
          ),
          margin: EdgeInsets.symmetric(horizontal: 8),
          child: IconButton(
            icon: Icon(Icons.send),
            onPressed: () => {},
            color: Colors.white,
          ),
        ),
      ],
    );

A: Ok so from the image that you have provided I have created and example for you which might be ok for your use case check the description below that for the UI implementation:

*

*So there is a row which has three widgets.

*In which First widget is a card with Expanded to scale as per the Device size then comes the child with another row which has the following widget :

*

*Icon button for emoji's stuff.

*TextField with expanded to scale for device sizes.

*And Next one comes the camera widget which is again a       IconButton.

*There is a Floating action button in the end.

*Container for right padding, you can use widget of your choice.
check the Git repo, this has a sample code:
https://github.com/sagaracharya24/chat_app_input_widget.git
This is the end output:

Let me know if this works for you.


text:
Q: Android text selection text color is off I have a toolbar whose text color should be white. However, I want my theme to be the Light theme.
Here's how I currently accomplish that:
activity_main.xml
<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/primary"
    android:theme="@style/ActionBar"/>

styles.xml
<style name="ActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:textColorPrimary">@color/abc_primary_text_material_dark</item>
    <item name="android:textColorPrimaryInverse">@color/abc_primary_text_material_dark</item>
    <item name="actionMenuTextColor">@color/abc_primary_text_material_light</item>
    <item name="android:textColorSecondary">@color/abc_primary_text_material_dark</item>
</style>

However, when I select text, the toolbar looks really weird:

As you can see, the topmost toolbar's color is white when it should be black.
So here's my question: How can I make the topmost Text selection toolbar look acceptable? Either the text color needs to change, or the background color needs to change. Either works for me.
I have tried this code:
styles.xml
<item name="actionModeStyle">@android:style/Theme.Black</item>
<item name="android:actionModeBackground">@android:color/black</item>

and this code:
styles.xml
<item name="actionModeStyle">@style/textSelection</item>
<style name="textSelection">
    <item name="textColorPrimary">@color/abc_primary_text_material_light</item>
</style>

but neither works.
What am I doing wrong?

A: You may have already solved this by now, but I got this working by creating a theme (in themes.xml) and setting the actionModeBackground, similar to what you were doing in your toolbar style.
<style name="LightTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    ...
    <!-- toolbar -->
    <item name="actionModeBackground">@color/themeActionMode_light</item>
    ...
</style>

Then, once the activity launches, I set the theme:
public class MyActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.setTheme(R.style.LightTheme)

        super.onCreate(savedInstanceState);

        setContentView(R.layout.foo);
    }
}


text:
Q: How do I create a hash in Ruby that compares strings, ignoring case? In Ruby, I want to store some stuff in a Hash, but I don't want it to be case-sensitive. So for example:
h = Hash.new
h["HELLO"] = 7
puts h["hello"]

This should output 7, even though the case is different. Can I just override the equality method of the hash or something similar?
Thanks.

A: Any reason for not just using string#upcase?
h = Hash.new

h["HELLO"] = 7

puts h["hello".upcase]

If you insist on modifying hash, you can do something like the following
class Hash
alias :oldIndexer :[]

def [](val)
   if val.respond_to? :upcase then oldIndexer(val.upcase) else oldIndexer(val) end
end
end

Since it was brought up, you can also do this to make setting case insensitive:
class Hash
alias :oldSetter :[]=
def []=(key, value)
    if key.respond_to? :upcase then oldSetter(key.upcase, value) else oldSetter(key, value) end
end
end

I also recommend doing this using module_eval.

A: require 'test/unit'
class TestCaseIndifferentHash < Test::Unit::TestCase
  def test_that_the_hash_matches_keys_case_indifferent
    def (hsh = {}).[](key) super(key.upcase) end

    hsh['HELLO'] = 7
    assert_equal 7, hsh['hello']
  end
end

A: To prevent this change from completely breaking independent parts of your program (such as other ruby gems you are using), make a separate class for your insensitive hash.
class HashClod < Hash
  def [](key)
    super _insensitive(key)
  end

  def []=(key, value)
    super _insensitive(key), value
  end

  # Keeping it DRY.
  protected

  def _insensitive(key)
    key.respond_to?(:upcase) ? key.upcase : key
  end
end

you_insensitive = HashClod.new

you_insensitive['clod'] = 1
puts you_insensitive['cLoD']  # => 1

you_insensitive['CLod'] = 5
puts you_insensitive['clod']  # => 5

After overriding the assignment and retrieval functions, it's pretty much cake. Creating a full replacement for Hash would require being more meticulous about handling the aliases and other functions (for example, #has_key? and #store) needed for a complete implementation. The pattern above can easily be extended to all these related methods.

A: If you really want to ignore case in both directions and handle all Hash methods like #has_key?, #fetch, #values_at, #delete, etc. , you'll need to do a little work if you want to build this from scratch, but if you create a new class that extends from class ActiveSupport::HashWithIndifferentAccess, you should be able to do it pretty easily like so:
require "active_support/hash_with_indifferent_access"

class CaseInsensitiveHash < HashWithIndifferentAccess
  # This method shouldn't need an override, but my tests say otherwise.
  def [](key)
    super convert_key(key)
  end

  protected

  def convert_key(key)
    key.respond_to?(:downcase) ? key.downcase : key
  end
end

Here's some example behavior:
h = CaseInsensitiveHash.new
h["HELLO"] = 7
h.fetch("HELLO")                # => 7
h.fetch("hello")                # => 7
h["HELLO"]                      # => 7
h["hello"]                      # => 7
h.has_key?("hello")             # => true
h.values_at("hello", "HELLO")   # => [7, 7]
h.delete("hello")               # => 7
h["HELLO"]                      # => nil

A: In general, I would say that this is a bad plan; however, if I were you, I'd create a subclass of hash that overrides the [] method:
class SpecialHash < Hash
  def [](search)
    # Do special code here
  end
end

A: While Ryan McGeary's approach works great and is almost certainly the correct way to do it, there is a bug that I haven't been able to discern the cause of, which breaks the Hash[] method.
For example:
r = CaseInsensitiveHash['ASDF', 1, 'QWER', 2]
=> {"ASDF"=>1, "QWER"=>2}
r['ASDF']
=> nil
ap r
{
    "ASDF" => nil,
    "QWER" => nil
}
=> {"ASDF"=>1, "QWER"=>2}

Although I've not been able to find or fix the underlying cause of the bug, the following hack does ameliorate the problem:
r = CaseInsensitiveHash.new(Hash['ASDF', 1, 'QWER', 2])
=> {"asdf"=>1, "qwer"=>2}
r['ASDF']
=> 1
ap r
{
    "asdf" => 1,
    "qwer" => 2
}
=> {"asdf"=>1, "qwer"=>2}


text:
Q: What method is required to find out "for what values of k is $4x^2+kx+\frac14$ a perfect square?"
For what values of $k$ is this expression a perfect square?
$$4x^2+kx+\frac14$$

I'm thinking maybe the perfect square trinomial is supposed to be used, as I had to use that formula on the problem prior to this one. However, I don't know how to apply it, since I don't know which of the above terms would be $a^2$, $2ab$ and $b^2$. How can one deduce what term corresponds to what term in the general formula? Or is this not the formula to use at all?
EDIT:
User Exodd showed a general formula that when I followed, gave the same answer as user Jitendra Singh, who answered this question with a different formula.
The general formula is this:
$$(ax+b)^2 = a^2x^2+2abx+b^2$$
Which is a variation on the simpler perfect square trinomial
$$(a+b)^2=a^2+2ab+b^2$$
Now, if one assumes that $4x^2$ is $a^2x^2$, $kx$ is $2abx$ and $\frac14$ is $b^2$, then the calculation is quite simple. $k$ is then equal to $2ab$, which is equal to $\pm 2$, the sign depending on whether the $4$, or $a^2$, is the product of $2 \times 2$ or $-2 \times -2$, which creates:
$$2 \times 2 \times \frac12 = 2$$
or
$$2 \times -2 \times \frac12 = -2$$
However, this is assuming the aforementioned correspondence. It could be that $4x^2$ is $a^2x^2$, $kx$ is $b^2$ and $\frac14$ is $2abx$. In that case:
$$\frac14 = 2 \times 2 \times \sqrt{kx} \times x$$
or
$$\frac14 = 2 \times -2 \times \sqrt{kx} \times x$$
Furthermore, there could be a different correspondence. What if $4x^2$ is $b^2$, $kx$ is $a^2x^2$ and $\frac14$ is $2abx$? There are other correspondences as well. What says that the first one, that gave the answer of $\pm2$, is correct?

A: According to this if $b^2=4ac$ then the expression is a perfect square.
So $$ k^2=4 (4) (\frac{1}{4}) $$
So $$ k=±2 $$
Edit:
See I am going to show you why we assume $4k^2$ as $x^2$ and $4$ as $x$.
So lets compare the $2$ expressions-
$$ a^2x^2+2abx+b^2=4x^2+kx+4 $$
Now see if we consider $4x^2$ as $b^2$ then notice this is wrong because $4x^2$ has $x^2$ sign which means $4x^2$ can only considered with a term having $x^2$. Thus we can say-
$$ a^2x^2=4x^2 , 2abx=kx, b^2=4$$
Now you can compare and find the answer like you did in question

A: We consider a polynomial in $x$
\begin{align*}
p(x)=4x^2+kx+\frac{1}{4}
\end{align*}
which has degree $2$, constant term $\frac{1}{4}$, linear term $kx$ and square term $4x^2$.
We are looking for a representation as perfect square
\begin{align*}
q(x)=(ax+b)^2
\end{align*}
We recall two polynomials are equal, i.e. $p=q$ if they have the same degree and the coefficients of like powers of $x$ are equal.
\begin{align*}
p(x)&=q(x)\\
4x^2+kx+\frac{1}{4}&=a^2x^2+2abx+b^2\tag{1}
\end{align*}
From (1) we see $\deg p = \deg q$ and we obtain by comparison of coefficients
\begin{align*}
4&=a^2\\
k&=2ab\\
\frac{1}{4}&=b^2
\end{align*}
Note: The equality of polynomials is based upon an identity theorem of polynomials which can be found for instance in this paper as theorem 4 and which is nicely answered by @IvesDaoust in this MSE post.


text:
Q: Using npm modules in Typescript I would like to use npm module in Typescript project but there is no typings or tsd for this module. When I try use import Module from 'module' I had an error : Cannot find module 'module'. Is there way to fix it?
[EDIT]
My tsconfig.json:
{
  "compilerOptions": {
    "target": "ES5",
    "moduleResolution": "node",
    "module": "commonjs",
    "noEmitOnError": true,
    "noImplicitAny": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "sourceRoot": "src",
    "outDir": "bld"
  },
  "exclude": [
    "bld"
  ]
}

A: In case you wish not to pollute your imports with requires, you can follow the following method.
You can create a module.d.ts definition file which contains the following
declare module Module {}

Your imports should work now.
If you wish to import something like
import { abc } from 'module';

just go ahead and add the following to module.d.ts
declare module Module {
    export let abc: any
}

A: I assume your question is related to importing the module
import Module from 'module'

And not exporting it as you stated. If this is the case your can fall back to plain javascript and require module like this:
var Module = require('module');

[EDIT]
Verify that in tsconfig.json you have the following lines in compiler options:
"compilerOptions": {
    "moduleResolution": "node",
    "module": "commonjs"
}

Hope this helps.

A: By example:
npm install numwords
Then added the import the .ts file:
import * as numwords from 'num-words';
And then the usage:
console.log((numwords(5));


text:
Q: arrays.aslist adding derived class java So I have this:
class A{}
class B extends A {}
class C extends B {
    public String toString(){ return new String("C"); }
    }
class D extends B {
    public String toString(){ return "D"; }
    }

And then in main
List<A> list = Arrays.asList(new C(), new D());
        for (A a : list) {
            System.out.println(a.toString());
        }

I can compile this code and it prints:
C
D
but on my friend's computer it won't compile.
It has to deal with the Java version I am using ?

A: That's right. You must be compiling on Java 8 while your friend is on Java 7.
In Java 7, the type of of the List returned by
Arrays.asList(new C(), new D());

would be inferred as List<B> and a List<B> cannot be assigned to a List<A>.
In Java 8, with some smarter generics, the compiler would infer a different type for the same expression, List<A>.
You can correct the Java 7 version with an explicit type argument
Arrays.<A>asList(new C(), new D());


text:
Q: jsf - facelets - pack library jar with *.xhtml-s and beans only I could read the tutorial which describes how to pack facelets to jar to reuse tags as library...
The thing is the instruction recommends using both JSP and JSF in manner as (see code snippet);
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jstl/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core" version="2.0">

    <ui:composition>
        ...
    </ui:composition>
</jsp:root>

...and using both .taglib.xml + .tld conf files... :(
So I don't get it may ui:composition in *.xhtml be started as usual by (see code snippet) ...
<ui:composition
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:c="http://java.sun.com/jstl/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core" version="2.0">

   ...
</ui:composition>

...not to deal with jsp at all? And if, yes, how this kind of library can be added to dynamic web project in eclipse for example?
So my question concerning the tutorial is...
A) is there a way to avoid using *.tld and use have *.taglib.xml only for the lib if the tag library will contain xhtml files only?
B) is there a way to  have xhtml-s in non META-INF sub-folder but in some random one?
C) How to automate this kind of library creation process? I mean should I create a project in eclipse (?project category) to have correct folders structure by default to make possible re-compile it and test it and only after that pack it as a jsf library?
I googled a lot but couldn't find solutions variations so please share your experience;
Thanks


text:
Q: Read a zipped file as a pandas DataFrame I'm trying to unzip a csv file and pass it into pandas so I can work on the file.
The code I have tried so far is:
import requests, zipfile, StringIO
r = requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip')
z = zipfile.ZipFile(StringIO.StringIO(r.content))
crime2013 = pandas.read_csv(z.read('crime_incidents_2013_CSV.csv'))

After the last line, although python is able to get the file, I get a "does not exist" at the end of the error.
Can someone tell me what I'm doing incorrectly?

A: I guess what your looking is the following
from io import BytesIO
import requests
import pandas as pd

result = requests.get("https://www.xxx.zzz/file.zip")
df = pd.read_csv(BytesIO(result.content),compression='zip', header=0, sep=',', quotechar='"')

Read these article to understand why: https://medium.com/dev-bits/ultimate-guide-for-working-with-i-o-streams-and-zip-archives-in-python-3-6f3cf96dca50

A: I think you want to open the ZipFile, which returns a file-like object,  rather than read:
In [11]: crime2013 = pd.read_csv(z.open('crime_incidents_2013_CSV.csv'))

In [12]: crime2013
Out[12]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 24567 entries, 0 to 24566
Data columns (total 15 columns):
CCN                            24567  non-null values
REPORTDATETIME                 24567  non-null values
SHIFT                          24567  non-null values
OFFENSE                        24567  non-null values
METHOD                         24567  non-null values
LASTMODIFIEDDATE               24567  non-null values
BLOCKSITEADDRESS               24567  non-null values
BLOCKXCOORD                    24567  non-null values
BLOCKYCOORD                    24567  non-null values
WARD                           24563  non-null values
ANC                            24567  non-null values
DISTRICT                       24567  non-null values
PSA                            24567  non-null values
NEIGHBORHOODCLUSTER            24263  non-null values
BUSINESSIMPROVEMENTDISTRICT    3613  non-null values
dtypes: float64(4), int64(1), object(10)

A: It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.
import pandas as pd
df = pd.read_csv('filename.zip')

(Of course you will need to specify separator, header, etc. if they are different from the defaults.)

A: If you want to read a zipped or a tar.gz file into pandas dataframe, the read_csv methods includes this particular implementation.
df = pd.read_csv('filename.zip')

Or the long form:
df = pd.read_csv('filename.zip', compression='zip', header=0, sep=',', quotechar='"')

Description of the compression argument from the docs:

compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
  For on-the-fly decompression of on-disk data. If 'infer' and filepath_or_buffer is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no decompression). If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression.
New in version 0.18.1: support for 'zip' and 'xz' compression.

A: For "zip" files, you can use import zipfile and your code will be working simply with these lines:
import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
   with z.open("Crime_Incidents_in_2013.csv") as f:
      train = pd.read_csv(f, header=0, delimiter="\t")
      print(train.head())    # print the first 5 rows

And the result will be:
X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0  -77.054968548763071,38.899775938598317,0925135...
1  -76.967309569035052,38.872119553647011,1003352...
2  -76.996184958456539,38.927921847721443,1101010...
3  -76.943077541353617,38.883686046653935,1104551...
4  -76.939209158039446,38.892278093281632,1125028...

A: https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial
Please follow this link.
import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
                                 header=1, sep='\t', quotechar='"')

#traffic_station_df['Address'] = 'address'

#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)


text:
Q: Why cannot I see all featured questions even if the questions don't have tags I ignore? Here's C++ Tag,
My ignored tags: facebook,visual-studio,visual-studio-2010,directx
I see the page like this:

And here is screenshot, how I see the page when I log out.
If you zoom in the image you'll see that no question has the tags I have ignored...
So why cannot I see them ?

A: The 'ignored tags' list in the right-hand side is elided. It only shows the first four tags.
Click on the little ... next to those four tags to see them all. You are ignoring more tags than you think.
You can also edit the full list in your preferences and either remove ignored tags, or uncheck the 'hide ignored tags checkbox.


text:
Q: Return pointer to any field in class/structure in C/C++ I have struct which contains a lot of fields with different types:
struct team_stats{
    char team_name[ TEAM_NAME_LEN ]; // Name of NFL team
    int games; // Number of games played in the season
    float pts_per_game; // Points per game
    ...
}

I create method that returns pointer to any field in my structure
It looks like:
template <class T>
T* getField (int fieldNum, team_stats &team) {
    if(fieldNum==0) return &team.team_name;
    if(fieldNum==1) return &team.games;
    if(fieldNum==2) return &team.pts_per_game;
    ...
}

For example I want to read some field :
template <class T>
void readTeam(team_stats &team) {
    for (int i = 0; i < NO_FIELDS; i++)
        cin >> *getField<T>(i,team);

Problem occurred:
As I have a template I need to pass some type when I invoke method - getField(i, team). But I have different types of my fields and compilator will say the message something like " can not convert type of field games to some type"
UPD:
But for outer function I need to specify the type T, how to make it dynamic?
UPD_2:
I found the great solution! I answered my question below!

A: So I wish answer this question by myself:

For each type lets create and overloaded getField method where
  first parameter is field number, second - considered class
  and third is  result pointer to considered field passed by reference,
  looks like:
void getField(int fieldNum, team_stats &team, int *& res) {
    if(fieldNum==1) res = &team.games;
    if(fieldNum==3) res = &team.total_points;
    if(fieldNum==4) res = &team.scrimmage_plays;
    ....
}
void getField(int fieldNum, team_stats &team, float *& res) {
    if(fieldNum==2) res = &team.pts_per_game;
    if(fieldNum==5) res = &team.yds_per_game;
    ....
}

void getField(int fieldNum, team_stats &team, char *& res) {
    if (fieldNum == 0) res = team.team_name;
    ....
}

So reading now looks like:
void readTeam(team_stats &team) {
    for (int i = 0; i < NO_FIELDS; i++) {
        if (isCharField(i)) {
            char * field;
            getField(i, team, field);
            readStringField(field);
        }
        if (isFloatField(i)) {
            float * field;
            getField(i, team, field);
            cin >> *field;
        }
        if (isIntField(i)) {
            int * field;
            getField(i, team, field);
            cin >> *field;
        }
    }


text:
Q: iPhone Settings programmatically can i change the iPhone settings programmatically?
For example.. I want to change my ringtone through my application ??
Is it possible or what ??

A: No it is not possible unless jail broken as said in the second link...
Programmatically access/add/change ringtones of contacts
http://www.iphonedevsdk.com/forum/iphone-sdk-development/13138-change-ringtone-programmatically.html


text:
Q: collatz-list implementation using haskell I am trying to implement collatz-list using Haskel:
Here's my code:
collatz n
     | mod n 2 == 0 = div n 2
     | otherwise =  3 * n + 1

collatzList n
        | n < 1 = error "Cannot have negative number"
collatzList
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

The error message I am getting is this:
parse error on input `collatzList'
[1 of 1] Compiling Main             ( exer.hs, interpreted )
Failed, modules loaded: none.
Can anyone tell me why I am getting this message?

A: I get different errors (using GHC 7.4.1):
> :load "/tmp/C.hs"
[1 of 1] Compiling Main             ( /tmp/C.hs, interpreted )

/tmp/C.hs:9:11: Not in scope: `n'

/tmp/C.hs:9:21: Not in scope: `n'

/tmp/C.hs:10:23: Not in scope: `n'

/tmp/C.hs:10:46: Not in scope: `n'
Failed, modules loaded: none.

This is because you forgot the n argument in your second equation for collatzList. You can either add this argument
collatzList n
        | n < 1 = error "Cannot have negative number"
collatzList n -- the n was missing here
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

or, since the left hand sides are now the same, you can simply join it with the first one:
collatzList n
        | n < 1 = error "Cannot have negative number"
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

A: You are redefining collatzList.
collatzList
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

do this:
collatz n
     | mod n 2 == 0 = div n 2
     | otherwise =  3 * n + 1

collatzList n
        | n < 1 = error "Cannot have negative number"
        | n == 1 = [n]
        | otherwise = n:collatzList (collatz n)

A: Generating a list of values that only depend on the previous value is a typical application for the unfoldr function (Data.List.unfoldr):
import Data.List (unfoldr)
collatzList = unfoldr nextCollatz
      where nextCollatz n | n <= 0    = Nothing
                          | n == 1    = Just (1,0)
                          | even n    = Just (n, n `quot` 2)
                          | otherwise = Just (n, 3*n+1)

unfoldr f x0 takes a starting value x0, and applies a function f to it. If f x0 is Nothing, the algorithm terminates; if it is Just (push, next), it adds push to the result list, and uses next as the new value for x0. Another example, generating squares up to 100 using unfoldr:
import Data.List (unfoldr)
squareList = unfoldr pow2
      where pow2 n | n > 100   = Nothing
                   | otherwise = Just (n, 2*n)
                   -- "Add n to the result list,
                   -- start next step at 2*n."

(And the obligatory remark about error: it's usually better to make the function return some dummy value. In my Collatz function above for example, the result for non-positive integers is an empty list instead of an exception.)


text:
Q: How to know where to look for media directories on android phone? I am working on a Gallery app which requires knowing where to look within the user's android device for images/videos. Currently, I am brute forcing it by going all the way up to the root directory, looking specifically for directories starting with "storage" and "sdcard" and searching each and every sub folder for files containing the proper extension.
There must be a better way to find media directories within the Android file system, no? Can anyone suggest any alternatives?
Thanks!

A: Not sure if there is a way to find all media directories, you'll have to scan each folder.
But you can skip folders which has .nomedia file, This will save some scanning time.


text:
Q: Understanding Elixir output I'm currently learning Elixir and going through all exercises in the "Programming Elixir 1.6" book.
As exercises itself are pretty simple, I struggle to understand something concerning outputs.
At the end of chapter 5, I'm asked to rewrite those lines using anonymous functions :
Enum.map [1, 2, 3, 4], fn x -> x + 2 end
Enum.each([1, 2, 3, 4], fn x -> IO.inspect x end

So I wrote this :
Enum.map([1, 2, 3, 4], &(&1 + 2))
Enum.each([1, 2, 3, 4], &IO.inspect/1)

But after running this my output was only from the inspect :
λ elixir functions-5.exs
1
2
3
4

So I added some IO.puts in here :
IO.puts Enum.map([1, 2, 3, 4], &(&1 + 2))
IO.puts Enum.each([1, 2, 3, 4], &IO.inspect/1)

And the output was really strange, to say the least :
λ elixir functions-5.exs
╚╝║═
1
2
3
4
ok

After trying some alternative syntax and using variables in between calls, I tried to execute those lines directly into Interactive Elixir :
iex(2)> Enum.map([1, 2, 3, 4], &(&1 + 2))
[3, 4, 5, 6]

It works fine this way! Why?
iex(1)> IO.puts Enum.map([1, 2, 3, 4], &(&1 + 2))
╚╝║═
:ok

IO.puts seems to break formatting again, why again?
What am I missing? why the different context of executions doesn't have the same output?
To summarize my overall question: Whiskey Tango Foxtrot ???

A: The value you're passing to IO.puts is a list of integers, and IO.puts interprets lists of integers as lists of Unicode codepoints (of which ASCII codes are a subset):
iex(1)> IO.puts [70,111,111]
Foo
:ok
iex(2)> IO.puts [1087, 1088, 1080, 1084, 1077, 1088]
пример
:ok

I'm not sure why you got ╚╝║═; I get different output for that list:
iex(1)> IO.puts [3,4,5,6]
^C^D^E^F
:ok

IO.inspect, on the other hand, tries to print the source code representation of whatever you pass to it.


text:
Q: Cumulative Sum in a column I am trying to write a VBA code to run a cumulative sum for a matrix of variable size to be output  to another sheet for further analysis. These cells need to be offset by 1 row and 1 column as well as the new top row assigned a "0" value. such as shown below (done by manual calc)

I am struggling to develop the code for this however what i have is shown below.
'Private Sub LGMethod_Click()
'Declare Variables
    Dim i As Integer
    Dim J As Integer
'Clear Worksheet
    Worksheets("LG").Cells.Clear
'Loop to count and and analyse
    For i = 1 To Worksheets("Data").Cells(Rows.Count, "A").End(xlUp).Row
        For J = 1 To Worksheets("Data").Cells(1, Columns.Count).End(xlToLeft).Column
            Worksheets("LG").Cells(i + 1, J + 1) = Application.WorksheetFunction.Sum(Worksheets("Data").Range.Cells(1, i))

        Next
    Next
End Sub'

A: As I see from your example, you want to shift down one row and calculate at each cell the cumulative sum on the column.
  Dim i As Integer, j As Integer, nRows As Integer, nCols As Integer
  With Worksheets("Data")
     nRows = .Cells(.Rows.Count, "A").End(xlUp).Row
     nCols = .Cells(1, .Columns.Count).End(xlToLeft).Column
     Worksheets("LG").Cells.Clear
     For i = 1 To nRows
        For j = 1 To nCols
            Worksheets("LG").Cells(i + 1, j) = Application.Sum(.Range(.Cells(1, j), .Cells(i, j)))
        Next
     Next

     For j = 1 To nCols + 2
        Worksheets("LG").Cells(1, j) = 0
     Next
   End With


text:
Q: Align views in Picker How do I align the Color views in a straight line with the text to the side?
To look like so (text aligned leading):
█  red
█  green
█  blue
Or this (text aligned center):
█    red
█  green
█   blue
Current code:
struct ContentView: View {
    @State private var colorName: Colors = .red

    var body: some View {
        Picker("Select color", selection: $colorName) {
            ForEach(Colors.allCases) { color in
                HStack {
                    color.asColor.aspectRatio(contentMode: .fit)

                    Text(color.rawValue)
                }
            }
        }
    }
}

enum Colors: String, CaseIterable, Identifiable {
    case red
    case green
    case blue

    var id: String { rawValue }
    var asColor: Color {
        switch self {
        case .red:      return .red
        case .green:    return .green
        case .blue:     return .blue
        }
    }
}

Result (not aligned properly):

Without the Picker, I found it is possible to use alignmentGuide(_:computeValue:) to achieve the result. However, this needs to be in a Picker.
Attempt:
VStack(alignment: .custom) {
    ForEach(Colors.allCases) { color in
        HStack {
            color.asColor.aspectRatio(contentMode: .fit)
                .alignmentGuide(.custom) { d in
                    d[.leading]
                }

            Text(color.rawValue)
                .frame(maxWidth: .infinity)
                .fixedSize()
        }
    }
    .frame(height: 50)
}

/* ... */

extension HorizontalAlignment {
    struct CustomAlignment: AlignmentID {
        static func defaultValue(in context: ViewDimensions) -> CGFloat {
            return context[HorizontalAlignment.leading]
        }
    }

    static let custom = HorizontalAlignment(CustomAlignment.self)
}

Result of attempt:

A: Possible solution is to use dynamic width for labels applied by max calculated one using view preferences.
Here is a demo. Tested with Xcode 13beta / iOS15

Note: the ViewWidthKey is taken from my other answer https://stackoverflow.com/a/63253241/12299030
struct ContentView: View {
    @State private var colorName: Colors = .red
    @State private var maxWidth = CGFloat.zero

    var body: some View {
        Picker("Select color", selection: $colorName) {
            ForEach(Colors.allCases) { color in
                HStack {
                    color.asColor.aspectRatio(contentMode: .fit)
                    Text(color.rawValue)
                }
                .background(GeometryReader {
                    Color.clear.preference(key: ViewWidthKey.self,
                        value: $0.frame(in: .local).size.width)
                })
                .onPreferenceChange(ViewWidthKey.self) {
                    self.maxWidth = max($0, maxWidth)
                }
                .frame(minWidth: maxWidth, alignment: .leading)
            }
        }
    }
}

A: I think this should align your text and fix your issue.
struct ContentView: View {
    @State private var colorName: Colors = .red

    var body: some View {
        Picker("Select color", selection: $colorName) {
            ForEach(Colors.allCases) { color in
                HStack() {
                    color.asColor.aspectRatio(contentMode: .fit)

                    Text(color.rawValue)
                        .frame(width: 100, height: 30, alignment: .leading)
                }
            }
        }
    }
}

A simple .frame modifier will fix these issues, try to frame your text together or use a Label if you don't want to complicate things when it comes to pickers or list views.
If you do go forward with this solution try to experiment with the width and height based on your requirements, and see if you want .leading, or .trailing in the alignment


text:
Q: Can't get why javascript skips the number of iterator in loop Here is a task
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
Below is my answer what I wrote, it passes 25 test cases and then gets stuck on this one below. It gives answer 25, except accepted 4. So it means for me that it thinks that the whole matrix contains ones. Okay Then a problem is in if statement if(matrix[j][i] === "0") in function find_max. Then I consoled logged j and indeed I don't know why but when it iterates through it skips number 2.. I have no clue why. It goes 0, 1, 3. Give it a quick look if you can find any mistake, if no don't worry I'll try to rewrite it.
  let maximalSquare = mx([
["1","1","1","1","1"],
["1","1","1","1","1"],
["0","0","0","0","0"],
["1","1","1","1","1"],
["1","1","1","1","1"]

]);
console.log(maximalSquare);

function mx(matrix) {
    let max_length = 0;
    let cur_length = 0;
    if(matrix.length === 0)
        return 0;
    if(matrix.length === 1){
            let arr = new Set(matrix[0]);

            arr.has("1") ? max_length = 1 : max_length = 0
            return max_length;
        }

        for(let i = 0; i < matrix.length; i++){
            for (let j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] === "1"){
                    cur_length = find_max(matrix, 2, j, i);
                    max_length = Math.max(cur_length, max_length);
                }
            }
        }
        return max_length * max_length;
    };

    function find_max(matrix, newSquerSize, x, y){
        let i = x;
        let j = y;

        if(x + newSquerSize > matrix.length || y + newSquerSize > matrix.length){
            return newSquerSize - 1;
        }
        while(j < y + newSquerSize && j < matrix.length){
            while(i < x + newSquerSize && i < matrix.length){
                console.log(j, matrix[j][i])
                if(matrix[j][i] === "0") //here where it doesnt iterate through j = 2
                    return newSquerSize - 1;
                ++i;
            }
            ++j;
        }
        return find_max(matrix, ++newSquerSize, x, y);
    }

A: The first guess on the reason why the 2 is skipped would be that j incremented twice. In this case it means on the next iteration of j, the while loop of i didn't was immediately skipped
(i.e i >= x + newSquerSize || i >= matrix.length)
Since you're looping through lines/columns for the square, shouldn't you reset the i index to the starting value ?
I did try adding a i = x; before that loop and the result was indeed 4 as stated.
while (j < y + newSquerSize && j < matrix.length)
{
  i = x;  // Add this line
  while (i < x + newSquerSize && i < matrix.length) {
    console.log(j, i, matrix[j][i]);
    if (matrix[j][i] === "0")
      return newSquerSize - 1;
    ++i;
  }
  ++j;
}


text:
Q: Recover the privileges of the admin user of DSpace Editing permissions of a collection, by mistake we have removed all the privileges of the admin user (currently only belongs to the Anonymous group). Is it possible to recover the privileges of this user? Or create a new administrator user with all permissions over all communities and collections?
We use version 3.2 of DSpace.
Thanks!

A: You can always create a new administrator with the command line utility bin/dspace create-administrator
You could also move your user back to the Administrator group (it's the group with id 1). But you'll probably need another administrator to do that in the first place.
I don't know if there is a way to find all the groups an eperson used to be in.

A: This is a known issue in DSpace that is being tracked by the following ticket: https://jira.duraspace.org/browse/DS-2687
You will need to re-create group 1.
dspace=> insert into epersongroup values(1,'Administrator');
INSERT 0 1

You can then use the .../bin/dspace create-administrator command to re-add users to that group.


text:
Q: Unity3D - Unable to run Dedicated Server build Here are my compile settings:

Inside docker image build with this recipe:
FROM ubuntu:latest

MAINTAINER armegon

RUN apt-get update
RUN apt-get install -y gnupg ca-certificates
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
RUN echo "deb https://download.mono-project.com/repo/ubuntu stable-focal main" | tee /etc/apt/sources.list.d/mono-official-stable.list
RUN apt-get update
RUN apt-get install -y mono-complete
RUN apt-get install -y net-tools

When I run the app I get this error:
root@docker-desktop:/home/authorativeclient# ./AuthorativeClient.x86_64
[UnityMemory] Configuration Parameters - Can be set up in boot.config
    "memorysetup-bucket-allocator-granularity=16"
    "memorysetup-bucket-allocator-bucket-count=8"
    "memorysetup-bucket-allocator-block-size=4194304"
    "memorysetup-bucket-allocator-block-count=1"
    "memorysetup-main-allocator-block-size=16777216"
    "memorysetup-thread-allocator-block-size=16777216"
    "memorysetup-gfx-main-allocator-block-size=16777216"
    "memorysetup-gfx-thread-allocator-block-size=16777216"
    "memorysetup-cache-allocator-block-size=4194304"
    "memorysetup-typetree-allocator-block-size=2097152"
    "memorysetup-profiler-bucket-allocator-granularity=16"
    "memorysetup-profiler-bucket-allocator-bucket-count=8"
    "memorysetup-profiler-bucket-allocator-block-size=4194304"
    "memorysetup-profiler-bucket-allocator-block-count=1"
    "memorysetup-profiler-allocator-block-size=16777216"
    "memorysetup-profiler-editor-allocator-block-size=1048576"
    "memorysetup-temp-allocator-size-main=4194304"
    "memorysetup-job-temp-allocator-block-size=2097152"
    "memorysetup-job-temp-allocator-block-size-background=1048576"
    "memorysetup-job-temp-allocator-reduction-small-platforms=262144"
    "memorysetup-temp-allocator-size-background-worker=32768"
    "memorysetup-temp-allocator-size-job-worker=262144"
    "memorysetup-temp-allocator-size-preload-manager=262144"
    "memorysetup-temp-allocator-size-nav-mesh-worker=65536"
    "memorysetup-temp-allocator-size-audio-worker=65536"
    "memorysetup-temp-allocator-size-cloud-worker=32768"
    "memorysetup-temp-allocator-size-gfx=262144"
Mono path[0] = '/home/authorativeclient/AuthorativeClient_Data/Managed'
Mono config path = '/home/authorativeclient/AuthorativeClient_Data/MonoBleedingEdge/etc'
Found 3 interfaces on host : 0) 192.168.65.3 1) 192.168.65.4 2) 172.17.0.1
Multi-casting "[IP] 192.168.65.3 [Port] 55294 [Flags] 19 [Guid] 601533813 [EditorId] 2814462019 [Version] 1048832 [Id] Unknown(43,192.168.65.3) [Debug] 1 [PackageName] Unknown [ProjectName] AuthorativeClient" to [225.0.0.222:54997]...
Stopping profiler. Profiler is not able to flush data to a file or socket and exceeded maximum allowed memory for buffering.
Please use Profiler.maxUsedMemory API or -profiler-maxusedmemory command line parameter to increase maximum allowed memory usage.
Using 134234112 bytes while Profiler.maxUsedMemory is 134217728 bytes.
Starting managed debugger on port 56813
Using monoOptions --debugger-agent=transport=dt_socket,embedding=1,server=y,suspend=n,address=0.0.0.0:56813
Preloaded 'lib_burst_generated.so'
Preloaded 'libgrpc_csharp_ext.so'
Unable to load player prefs
Initialize engine version: 2021.3.0f1 (6eacc8284459)
[Subsystems] Discovering subsystems at path /home/authorativeclient/AuthorativeClient_Data/UnitySubsystems
Forcing GfxDevice: Null
GfxDevice: creating device client; threaded=0; jobified=0
NullGfxDevice:
    Version:  NULL 1.0 [1.0]
    Renderer: Null Device
    Vendor:   Unity Technologies
Begin MonoManager ReloadAssembly
* Assertion at tramp-amd64.c:177, condition `(((guint64)(addr)) >> 32) == 0' not met

Caught fatal signal - signo:6 code:-6 errno:0 addr:0x9b
Obtained 48 stack frames.
#0  0x000040048a6520 in __sigaction
#1  0x000040048faa7c in pthread_kill
#2  0x000040048a6476 in raise
#3  0x0000400488c7f3 in abort
#4  0x00004168e60681 in monoeg_assert_abort
#5  0x00004168e49bc2 in mono_dl_fallback_unregister
#6  0x00004168e60999 in monoeg_g_logv
#7  0x00004168e60ad2 in monoeg_assertion_message
#8  0x00004168e60b04 in mono_assertion_message
#9  0x00004168d11253 in mono_breakpoint_clean_code
#10 0x00004168cc06bc in mono_install_ftnptr_eh_callback
#11 0x00004168cbfe14 in mono_install_ftnptr_eh_callback
#12 0x0000418948a396 in (Unknown)
#13 0x00004189edc4e8 in System.RuntimeType:GetConstructorCandidates (string,System.Reflection.BindingFlags,System.Reflection.CallingConventions,System.Type[],bool)
#14 0x00004189edc228 in System.RuntimeType:GetConstructors (System.Reflection.BindingFlags)
#15 0x00004189edbb46 in System.RuntimeType:GetDefaultConstructor ()
#16 0x00004189ed774c in System.Text.EncodingHelper:GetDefaultEncoding ()
#17 0x00004189ed7324 in System.Text.Encoding:CreateDefaultEncoding ()
#18 0x00004189ece575 in (wrapper runtime-invoke) object:runtime_invoke_void (object,intptr,intptr,intptr)
#19 0x00004168c461e8 in mono_get_runtime_build_info
#20 0x00004168de4dca in mono_runtime_invoke
#21 0x00004168de1465 in mono_runtime_class_init
#22 0x00004168c3ec9f in _init
#23 0x00004168c42548 in mono_jit_set_domain
#24 0x00004168cc03ab in mono_install_ftnptr_eh_callback
#25 0x00004168cbfe14 in mono_install_ftnptr_eh_callback
#26 0x0000418948a396 in (Unknown)
#27 0x00004189ecf92c in UnityEngine.UnityLogWriter:Init ()
#28 0x00004168c461e8 in mono_get_runtime_build_info
#29 0x00004168de4dca in mono_runtime_invoke
#30 0x00004168de4d14 in mono_runtime_invoke
#31 0x000040030cb662 in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#32 0x000040030c9237 in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#33 0x000040030a6c6f in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#34 0x000040030a746d in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#35 0x000040030a5102 in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#36 0x000040030a5076 in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#37 0x00004003135fb7 in std::vector<int, std::allocator<int> >::_M_fill_insert(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, unsigned long, int const&)
#38 0x00004003135845 in std::vector<int, std::allocator<int> >::_M_fill_insert(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, unsigned long, int const&)
#39 0x00004003118a32 in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#40 0x00004003119035 in void std::vector<unsigned int, std::allocator<unsigned int> >::_M_assign_aux<__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > > >(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, __gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >, std::forward_iterator_tag)
#41 0x00004002741f23 in operator delete[](void*, std::nothrow_t const&)
#42 0x00004002742052 in operator delete[](void*, std::nothrow_t const&)
#43 0x00004002c5ad25 in std::vector<int, std::allocator<int> >::_M_default_append(unsigned long)
#44 0x0000400314d8c5 in PlayerMain(int, char**)
#45 0x0000400488dd90 in __libc_init_first
#46 0x0000400488de40 in __libc_start_main
#47 0x00004000001029 in _start
qemu: uncaught target signal 6 (Aborted) - core dumped
Aborted

Any idea why I get this error and how can I solve it?


text:
Q: Cleaning up deprecated HTML code with DOMXPath (convert nested  tags to  tags) I'm trying to read Rich Text stored in an old MS Access database into a new PHP web app. The sanitised data will be displayed to users using CKEditor, which is quite strict on parsing standards compliant HTML code. However, the data stored in MS Access is often ill-formatted or uses deprecated HTML code.
Below is an example piece of data I am trying to sanitise:

Previous claim $   935.00
  This claim $1,572.50

This data is meant to be two lines of text that are right-justified, however MS Access has used the deprecated align attribute to style the
 tags instead of a style attribute, and has incorrectly nested them when in this scenario they should be sequential.
To turn this example data into two lines of text that are both right-justified and that CKEditor will read and display as intended (i.e. text appears as right justified), I am trying to replace the
 tags with
 tags, and inject an inline style attribute with right text-align to replace the deprecated align attribute.
I am using PHP's DOMXPath to clean up the data, with the following code:
$dom = new DOMDocument();
$dom->loadHTML($dataForCleaning, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);

foreach ($xpath->query('//div[@align]') as $node) {
    $alignment = $node->getAttribute('align');

    $newNode = $dom->createElement('p');
    $newNode->setAttribute("style", "text-align:".$alignment);
    $node->parentNode->insertBefore($newNode, $node);

    foreach ($node->childNodes as $child) {
        $newNode->appendChild($child);
    }

    $node->parentNode->removeChild($node);
}

I am using insertBefore in lieu of appendChild in trying to keep the sequence of elements the same, but this is what's causing the issues in this nested data example.
For non-nested
 tags as the input data to be cleaned, the sanitised output html is correct. However, in this nested
 example, the output ends up being:

Previous claim $   935.00

Note that the second line of text (This claim...) has been removed, as it was within a nested
 as a child to the parent

I don't mind if the resultant
 tags remain nested, as CKEditor ends up cleaning these up, but I do need to make sure I'm not losing data like this current code does.
Thanks in advance for any help and guidance.
-Mark

A: There are a couple of things I've changed.  The first is that rather than just append the existing node, I get it to clone the node and append the copy (in $newNode->appendChild($child->cloneNode(true));), the second thing I do is as you are moving the enclosed node, I think that the XPath is no longer pointing to this moved node.  So instead of that, I check when copying the child nodes if you have the same pattern of a
 node and if so I create a new node in the new format and add that instead...
foreach ($xpath->query('//div[@align]') as $node) {
    $alignment = $node->getAttribute('align');

    $newNode = $dom->createElement('p');
    $newNode->setAttribute("style", "text-align:".$alignment);

    $node->parentNode->insertBefore($newNode, $node);
    foreach ($node->childNodes as $child) {
        if ( $child instanceof DOMElement && $child->localName == "div"
                && $child->attributes->getNamedItem("align")->nodeValue == "right" )    {
            $subNode = $dom->createElement('p', $child->nodeValue );
            $subNode->setAttribute("style", "text-align:".$alignment);
            $newNode->appendChild($subNode);
        }
        else    {
            $newNode->appendChild($child->cloneNode(true));
        }
    }

    $node->parentNode->removeChild($node);
}

which for the sample you give will output...

    Previous claim $   935.00

  This claim $1,572.50


text:
Q: Django: Increment blog entry view count by one. Is this efficient? I have the following code in my index view.
latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
    entry.views = entry.views + 1
    entry.save()

If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?
Is there a more efficient method to achieve this result?

A: You can use F() objects for this.
Here is how you import F: from django.db.models import F
New in Django 1.1.
Calls to update can also use F() objects to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value.
Entry.objects.filter(is_published=True).update(views=F('views')+1)

Although you can't do an update on a sliced query set... edit: actually you can...
This can be done completely in django ORM. You need two SQL queries:

*

*Do your filter and collect a list of primary keys

*Do an update on a non-sliced query set of items matching any of those primary keys.

Getting the non-sliced query set is the hard bit. I wondered about using in_bulk but that returns a dictionary, not a query set. One would usually use Q objects to do complex OR type queries and that will work, but pk__in does the job much more simply.
latest_entry_ids = Entry.objects.filter(is_published=True)\
                                      .order_by('-date_published')
                                      .values_list('id', flat=True)[:10]
non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_ids)
n = non_sliced_query_set.update(views=F('views')+1)
print n or 0, 'items updated'

Due to the way that django executes queries lazily, this results in just 2 database hits, no matter how many items are updated.

A: If you really need the efficiency, at the moment you'd have to drop down into SQL and run the update yourself.  That's not worth the added complexity in this case, though.
By Django 1.1 you'll be able to do this in a single SQL call via the ORM using F() objects to reference fields in the update value.

A: Revised
You're updating 10 separate, individual, distinct objects.
The 10 separate, individual, distinct updates can't easily be collapsed into one magical update that somehow touches 10 objects.

A: A performance improvement to the previous entry. This results in one database hit, with a subquery.
latest_entry_query_set = Entry.objects.filter(is_published=True)
                                      .order_by('-date_published')[:10]
non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_query_set.values('id'))
n = non_sliced_query_set.update(views=F('views')+1)
print n or 0, 'items updated'

A: You could handle the updates in a single transaction, which could improve performance significantly.  Use a separate function, decorated with @transaction.commit_manually.
@transaction.commit_manually
def update_latest_entries(latest_entry_list):
    for entry in latest_entry_list:
        entry.views += 1
        entry.save()
    transaction.commit()


text:
Q: How to swap elements in a linked list without using collections.swap I'm a beginner at java. I want to be able to swap elements using index value while using my own method or without using collections.swap
import java.util.LinkedList;
import java.util.Scanner;

class Main {
    private static LinkedList<Integer> llist;
  public static void main(String[] args) {
    LinkedList<Integer> languages = new llist<>();
    Scanner s = new Scanner(System.in);

    // add elements in the linked list
    llist.add(5);
    llist.add(4);
    llist.add(3);
    llist.add(2);
    System.out.println("LinkedList: " + languages);
    exchange(3,2);
    System.out.println("LinkedList: " + languages);
  }

  public static void exchange(int i, int j) {
    llist.set(i, llist.set(j, llist.get(i)));
}

}

Whenever I build this one there is no error that pops up, but when I run it, it gives me the java.lang.NullPointerException.

A: Your line:
LinkedList<Integer> languages = new llist<>();

Has an error - replace it with
llist = new LinkedList<Integer>();

So it becomes
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    private static LinkedList<Integer> llist;
    public static void main(String[] args) {
        llist = new LinkedList<Integer>();
        Scanner s = new Scanner(System.in);

        // add elements in the linked list
        llist.add(5);
        llist.add(4);
        llist.add(3);
        llist.add(2);
        System.out.println("LinkedList: " + llist);
        exchange(3,2);
        System.out.println("LinkedList: " + llist);
    }

    public static void exchange(int i, int j) {
        llist.set(i, llist.set(j, llist.get(i)));
    }
}

Also
System.out.println("LinkedList: " + languages);

should be:
System.out.println("LinkedList: " + llist);

as you do not really use languages, but llist;


text:
Q: Is there a fast way to trilaterate a point? I have a point in 2D or 3D space at an unknown coordinate, $p_0$, and I'd like to determine its position using distances from known coordinates $(p_1, p_2, p_3)$.  Beyond using Reduce, what is a fast method of doing this in Mathematica, particularly for the two-dimensional case?  Is there some built-in function for this?
Also, how can I get an output in coordinate form without any string processing?  For example, to parse the output from Reduce, I need to convert the output to a string, infer where the actual coordinate values are, and extract them, which is an awful way to go about doing things.
Here's an implementation with Solve:
PostOne = {10, 10};
PostTwo = {10, 0};
PostThree = {0, 0};

PointToLocalize = {x0, y0};

D1 = 0;
D2 = 10;
D3 = 200^(1/2);

Solve[EuclideanDistance[PointToLocalize, PostOne] == D1 &&
      EuclideanDistance[PointToLocalize, PostTwo] == D2 &&
      EuclideanDistance[PointToLocalize, PostThree] == D3, {x0, y0}]

Now that the string processing issues have been resolved, is Solve or Reduce really the most efficient way to do this for $10^6$ or $10^7$ or so points?

A: In two dimensions, we can reformulate your problem as finding the intersection point of three circles with given centers and radii.
To ease things, you can first form the radical line of two of your three circles, and then find the intersection of that line with the third circle. This will return two solutions, which means we need to do some postprocessing to pick out the one you actually want.
Here's how to go about it:
pts = {x, y} /. Solve[{2 (PostTwo - PostOne).{x, y} +
                       PostOne.PostOne - PostTwo.PostTwo == D1^2 - D2^2,
                       #.# &[{x, y} - PostThree] == D3^2}, {x, y}, Reals];

Select[pts, And @@ MapThread[Function[{c, r}, EuclideanDistance[#, c] == r],
                             {{PostOne, PostTwo, PostThree}, {D1, D2, D3}}] &] // First

which yields the result {10, 10} in your particular case.


text:
Q: How to setup a maven project using fop and java-11? When I set up a maven project using Apache fop and Java 11 I get warnings and a NullPointerException with maven-compiler-plugin 3.8.0.
The used archetype is working fine with Java 11 to quickly create a desktop application, but only if I do not add the dependency to fop-2.3. (I also wonder how it is possible that the same Java code works fine in mvn test but fails when adding the fop dependency.)
adding
    <dependency>
        <groupId>org.apache.xmlgraphics</groupId>
        <artifactId>fop</artifactId>
        <version>2.3</version>
    </dependency>

to pom.xml and running with mvn test leads to
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ checkXslt ---
[WARNING] Can't extract module name from batik-script-1.10.jar: Provider class org.apache.batik.bridge.RhinoInterpreterFactory not in module
[WARNING] Can't extract module name from xalan-2.7.2.jar: Provider class org.apache.bsf.BSFManager not in module

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project checkXslt: Execution default-compile of goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile failed. NullPointerException -> [Help 1]

I wonder if there is a pom.xml using fop dependency and compiling for Java 11.

A: The nullpointer problem disappears if using the trunk of fop 2.4.0-SNAPSHOT.
Going back to 2.3 gives the nullpointer again.
Note that for fop just the dependency has been added to pom.xml. It has not been used yet in the java source code.
The warnings remain.

A: have you tried
 <dependency>
            <groupId>org.apache.xmlgraphics</groupId>
            <artifactId>fop</artifactId>
            <version>2.3</version>
            <exclusions>
                <exclusion>
                  <groupId>xalan</groupId>
                  <artifactId>serializer</artifactId>
                </exclusion>
                 <exclusion>
                  <groupId>xalan</groupId>
                  <artifactId>xalan</artifactId>
                </exclusion>
              </exclusions>
        </dependency>

A: I started to set up a project using FOP 2.3; I used a module-info.java containing:
requires fop;
requires avalon.framework.api;
requires avalon.framework.impl;

However, ultimately I had to defer, owing to avalon splitting packages.
That particular problem will be gone when FOP 2.4 is released: https://github.com/apache/fop/commit/bd7d5048785c691e6e3e152af10805f3127b760d
The Xalan problem I had addressed earlier by modularising it myself:- https://github.com/plutext/xalan-j/tree/Plutext_Java11_Repackaged_Docx4j


text:
Q: Error installing rails on windows
Building native extensions.  This could take a while...
ERROR:  Error installing rails:
          ERROR: Failed to build gem native extension.
C:/Ruby22-x64/bin/ruby.exe -r ./siteconf20160716-3500-cejnk5.rb
  extconf.rb
Invalid argument - C:/Ruby22-x64/bin/ruby.exe -r
  ./siteconf20160716-3500-cejnk5. rb extconf.rb 2>&1
Gem files will remain installed in
  C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/websoc ket-driver-0.6.4 for
  inspection.
Results logged to
  C:/Ruby22-x64/lib/ruby/gems/2.2.0/extensions/x64-mingw32/2.2.0
  /websocket-driver-0.6.4/gem_make.out

A: It could be many things as Windows is quite finicky to run Rails in. Off the top of my head:

*

*Did you accidentally install the 64 bit version of Ruby or Rails when you needed 32 bit? You can test by typing in ruby -v in the command line and seeing if your version is i386 or x64 as well as check your system information to see if your system is 32 or not. You can get different versions of Ruby here:
http://rubyinstaller.org/downloads

*Is the link to C:/Ruby22-x64/bin/ruby.exe in your Environment variable path?

*Are you installing a version of the Rails Gem that doesn't work well with Windows or your current system setup? It might be worth trying gem install rails -v 4.1.8 (which works on my windows setup) or other specific versions and see if one works.


text:
Q: Using a colon (:) in a url with ASP.NET/IIS I'm implementing a custom controller in ASP.NET MVC and really want to be able to use a colon in the urls, so that I can identify class/column names and their values, like so:
http://example.com/user:chaiguy
...but apparently ASP.NET or IIS doesn't allow colons in urls. I did some digging and apparently it's considered a security issue, but, I'm using MVC and am handling all url paths manually (just treating them as strings), and not relating them to the file system, so I'm pretty sure this doesn't apply.
I also heard some talk about implementing a custom Http handler or something.
Any thoughts or ideas would be much appreciated.

Er.... why? Seriously, why break standards? – Randolpho

...

I suggest, then, that you investigate building a web service. WCF is a nice technology for that, and it hosts well in IIS.

I happen to like urls, and WCF is way too complicated for my purposes. I want it to be url-compatible, like REST, but capable of more than just navigating hierarchies, or doing well laid-out things. The problem I have with /users/chaiguy is that it is interpreting hierarchy where there is none: in my system "user" is a class, it's not a folder. user:chaiguy means the instance of the user class with the value of "chaiguy", and that is a single entity, that has the potential of having child-entities. So for example:
/user:chaiguy/name
...I would like to display the name of that entity. If I did this with your method, it would look like this:
/users/chaiguy/name
The problem is how do you know what's the class and what's the value? It could be interpreted as
/users/chaiguy:name
in my system, and that doesn't make sense. See what I'm getting at? To give a slightly more complicated example, suppose we want to select a child of the user entity out of multiple instances. So a user might have several email addresses. To select one, we might use:
/user:chaiguy/email:me@here.com/
So it is in fact recursive. It's not a file path, it's more like an XPath (or maybe similar to jQuery based on what little I know of it yet). That is, it's more of a dynamically-evaluated query selection than a hardwired file path. It gets evaluated on the server.
Make no mistake, I'm not building a typical web site or even web service here.

A: Answered similar question here: https://stackoverflow.com/a/12037000/134761
It seems that ASP.net does not allow colons before the '?' in an URL, even if it is encoded as %3A.
For example, these won't work:
http://foo.org/api/persons/foo:bar
http://foo.org/api/persons/foo%3abar
But this works:
http://foo.org/api/persons?id=foo%3abar
In all examples, we would expect ASP.NET MVC to pass "foo:bar" as an id argument, properly decoded. I just tested this with MVC4 and it seems to work. It is annoying that it doesn't accept the URL encoding before the question mark though, but I'm sure there is a good reason for it. Probably to keep everything before the question mark a valid URL and any arguments after the question mark.

A: Change the requestPathInvalidCharacters attribute of httpRuntime in web.config:
<httpRuntime maxRequestLength="20480" requestValidationMode="2.0" requestPathInvalidCharacters="" maxQueryStringLength="20480" />

and ASP.NET should no longer block colons from your request path.

A: I suggest you rethink what you want to do. Use pathing to indicate context and hide your class and field names, mapping particular contexts within your URL paths to class names and fields. If you need to indicate a user, for example, build your URL layout like example.com/users/chaiguy rather than example.com/user:chaiguy.

A: Try setting HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\HTTP\Parameters\AllowRestrictedChars. This is from http://support.microsoft.com/?id=820129. I don't know whether ASP.NET/MVC does some checking on their own but if it's only http.sys blocking you, this should fix it.

A: This web.config setting worked for me. It accepts colons (:) in the url.
<httpRuntime targetFramework="4.6.1" requestPathInvalidCharacters=""/>

A: Actually there is WCF REST available, and you can easily get up and running within an hour by using the WCF Starter Kit available here. This takes the power of REST and merges it with the ease of WCF. Also with WCF you can also create your own transport layer if you need to that can intepret URL's in any way you wish. One interesting thing about the starter kit is that it allowed spaces in the Url, which actually caused some headaches for true REST fundi's.
I wasn't keen on looking at it due to WCF, but you really don't need to know that much. The solution creates everything you need, just add the code.

A: I would suggest using a period. REST, based on HTTP protocol, is an example of building a new use for HTTP that kept to standards and was highly successful. Perhaps you can do that.
AND a '.' is a standard 'class.method' or 'class.attribute' in many langauges.
Now ME, I wanted to use the colon in time URL parameters, and some places are doing it. I still have to see if I can get away with it.
PS, for me, I may use this:
     http://www.businesscasualblog.com/2009/07/how-to-share-a-link-to-a-specific-timecode-in-youtube-video.html
esentially '--h--m--s'

A: Is a colon valid in a url? Short answer no.
Long answer, yes if it's in a url fragment.
Example: http://site/gwturl#user:45/comments (note the colon proceeds the hash tag)
Sources

*

*this answer,

*Is a colon safe for friendly-URL use?

*along with a personal test of just adding : to a url in ASP.NET and getting the YSOD with A potentially dangerous Request.Path value was detected from the client (:)


text:
Q: JavaFx Webview with Motion Is it possible, to view the video which motion streams vie JavaFx Webview and WebEngine?
I have a code which shows me like every website i want, but when i try to open the stream from motion nothing happens
The app code:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("WebView.fxml"));
        Scene scene = new Scene(root, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.*?>
<?import javafx.scene.web.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="WebViewController">
   <children>
      <WebView fx:id="webView" layoutX="100.0" layoutY="176.0" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
      <ImageView fitHeight="150.0" fitWidth="200.0" layoutX="161.0" layoutY="27.0" pickOnBounds="true" preserveRatio="true">
         <image>
            <Image url="@../../../Schreibtisch/test.png" />
         </image>
      </ImageView>
   </children>
</AnchorPane>


text:
Q: What's the easiest way to create an HTTPS endpoint on Kubernetes? I've created a simple Python API using responder and deployed it to Google Cloud with Kubernetes. I don't have a domain name just a raw IP address.
http://192.0.2.42/api/myapi

And deployed as:
kubectl get service
NAME         TYPE           CLUSTER-IP    EXTERNAL-IP    PORT(S)        AGE
kubernetes   ClusterIP      192.0.2.1     <none>         443/TCP        5d15h
web          LoadBalancer   192.0.2.100   192.0.2.42        80:32749/TCP   5d15h

and
kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
my-pod-name   1/1     Running   0          16h

I'd like to make it an HTTPS endpoint so I can use it as:
https://192.0.2.42/api/myapi

But I am struggling to find the easiest way to do it.
Should this be something that is done via Kubernetes, or something that is done in the Python code? It doesn't look like responder  provides an easy mechanism for this.

A: If you're looking for the bare minimum level of effort to do this, you'll need to install an SSL certificate inside your docker container. You can also continue to use externalIP as you are now.
Then in responder you can enable HSTS to redirect http to https.
api = responder.API(enable_hsts=True)
Then just access your pod with
https://192.0.2.42/api/myapi