Change C:\Folder\File to C:\\Folder\\file

Question: I am fiddling around with the following code. However, I need the file name restructured from the C:\MY FOLDER\MY FILE format to the C:\\MY FOLDER\\MY FILE format. How can I do this?
Public Class Form1
    Private Sub TextBox1_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Click
        'OpenFileDialog1.Title = "Please Select a File"
        'OpenFileDialog1.InitialDirectory = "C:temp"

        OpenFileDialog1.ShowDialog()

    End Sub

    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

        Dim strm As System.IO.Stream
        strm = OpenFileDialog1.OpenFile()
        TextBox1.Text = OpenFileDialog1.FileName.ToString()
        If Not (strm Is Nothing) Then
            ''insert code to read the file data
            strm.Close()
            'MessageBox.Show("file closed")
        End If

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim FILEx As String = "C:\FILEPATH.txt"

        If System.IO.File.Exists(FILEx) = True Then
            Dim objWriter As New System.IO.StreamWriter(FILEx, False)
            objWriter.WriteLine(TextBox1.Text)
            objWriter.Close()
        End If
    End Sub
End Class
`code`

The code is rough.I am just testing some things out.
Comment: What does the question have to do with the code?  Why are you doubling the \'s?   What are you trying to do?
Answer: EDIT (VB, not C#, booh :p)
If you're writing a explicit string like "C:\FILEPATH.txt" you need to double up the \ yourself. Otherwise VB will think \F is a special character. That or preceed the string with a @.
So:
"C:\\FILEPATH.txt"

or
@"C:\FILEPATH.txt"

Internally VB will only see a single \
So if, say, you're getting the path from a textbox you don't need to double the backslashes.
EDIT
Ok, so according to here VB.NET actually does indeed not escape backslashes. Consider my answer useless then. (Although perhaps I educated some C-sharper out there... ? (I know I know, I'm grasping here :p)
Comment: IIRC, this isn't correct. I remember pulling my hair out for hours in VB.NET going `"blah blah blah \n"`, only to realize that it does not expand backslash escapes. Can someone check this quickly? (Don't have a good visual studio install available ATM..)


jhipster generated application failed to run on netbeans

Question: I created an application using hipster and then I opened the generated maven project over netbeans and run it.
I got this error :

Failed to execute goal com.github.trecloux:yeoman-maven-plugin:0.4:build (run-grunt) on project cabinet-medical: Error during : node --version: Cannot run program "node" (in directory "/Users/retina/Dropbox/QEMWEB/WORK/PROJETS/LOGICIELS/hispter/cabinet_hipster_generate"): error=2, No such file or directory -> [Help 1]
Answer: On Ubuntu, you might run into this issue, if you have installed Node.js via NVM and not via a global system package.
A possible workaround based on another example to create an executable file named as /usr/local/bin/node, which loads the NVM environment first with the following content:
 #\!/bin/bash
 export NVM_DIR="/home/USER/.nvm"
 [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
 node $@

Replace NVM_DIR with the path of your NVM installation and make the file executable for example with chmod +x /usr/local/bin/node.


Gobblin - how to get post from Facebook

Question: I have been investigating Gobblin for awhile and currently I am experiencing difficulties in using Gobblin to get post from Facebook. I could not find any connection example on the internet or I may have searched it wrongly.
I am looking at integrate restfb to Gobblin, however in Gobblin, there is a RestAPI class with connector, source and extractor and I am struggling to find a way to combine these together. Could you please help me with a simple guide on how to implement this or point me to the correct instruction? Thank you very much in advance.
Answer: I am working on the same thing, I have extracted my data using the graph-facebook api using a java code. I recently started using gobblin for extracting data. In the beginning i ran gobblin on the debug mode to get an idea as to how the flow was, I think you should definitely try doing that. Now I get my data as a json object and use convertors, Builders, Writers available to get data on to HDFS.
If you want some pointers as to how to run gobblin on debug mode you can comment below, I'll be happy to help.
Comment: I have been switching to Spark for this since Gobblin is still relatively new and the community is young, I am not also that good at programming so I chose the easy way out. However, I still regret not to be able to utilize the full power of Gobblin. Please provide guidance to me as you see best and if you could share your work, it would be most perfect. Thank you.

Gobblin - how to get post from Facebook


Initializing UITextView in a thread -- Causing issue

Question: When I am trying to execute in a thread:
UITextView *aDescriptionView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 25, 50)];

I am getting this error:
bool _WebTryThreadLock(bool), 0x2819b0: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

What went wrong here? What should I do? I have to have this in a separate thread as it returns me a UIView object.
Comment: The GUI should NEVER be done in a secondary thread.
Answer: You must not access UI from any thread besides the main thread. Ever.
Comment: Does this include accessing properties, such as [myTextView text] ?
Comment: I think it is safe if you are only reading info, but I am not sure.


C# - only first if gets executed (XNA/Keypress)

Question: I am making my own input system in Monogame program, and for now
I have a problem with if statments here:
public static void Input()
    {
        if (IsKeyPressed(Keys.Space))
        {
            Cursor.X += 25;
        }

        if (IsKeyPressed(Keys.Back))
        {
            Words.Last().RemoveLetter();
            Cursor.X -= 25;
        }

        if (IsKeyPressed(Keys.A))
        {
            Words.Last().AddLetter(new Letter(Letters.A, Cursor));
            Cursor.X += 25;
        }
    }

static bool IsKeyPressed(Keys key)
    {
        keyState = Keyboard.GetState();

        if (keyState.IsKeyDown(key) && prevKeyState.IsKeyUp(key))
        {
            prevKeyState = keyState;
            return true;
        }
        else
        {
            prevKeyState = keyState;
            return false;
        }
    }

Okay so in my method Input I check for keypresses, and the result in program is that whichever key I put in first IF statment, that key will work, so if I change 'A' where the 'Space' is now, A would work and Space wouldn't...
Why are other ifs always false ?
EDIT:
Okay so actually, if my IsKeyPressed() method looks like this (without prevKeyState variable):
   static bool IsKeyPressed(Keys key)
    {
        keyState = Keyboard.GetState();

        if (keyState.IsKeyDown(key))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

then it works :/ but I need that preKeyState variable because I want to, no matter how long I hold for example, A key to just print one letter a, until I release that key :/
Comment: Not sure if this will fix anything, but you probably want these keys to be mutually exclusive, so it would be best to turn those `if`s into `else if`s.
Comment: tried it, didn't change anything
Comment: Keep it that way. It solves other issues you've yet to realize (for example, what if someone presses `A` *and* `Space` at the same time?)
Comment: @RenéVogt that was spelling error sorry, it is keystate.IsKeyDown()
Answer: Had an similar issue. Solved it by passing the new and old KeyboardState to the function. Ended with something like this which works fine.
public void HandleKeyStroke(KeyboardState ks, KeyboardState oldks)
{
    if (ks.IsKeyDown(GameplayButtons.ACTIONBAR_0) && oldks.IsKeyUp(GameplayButtons.ACTIONBAR_0))
        UIManager.actionToBeTriggered("actionbar_0");
    if (ks.IsKeyDown(GameplayButtons.ACTIONBAR_1) && oldks.IsKeyUp(GameplayButtons.ACTIONBAR_1))
        UIManager.actionToBeTriggered("actionbar_1");
    if (ks.IsKeyDown(GameplayButtons.ACTIONBAR_2) && oldks.IsKeyUp(GameplayButtons.ACTIONBAR_2))
        UIManager.actionToBeTriggered("actionbar_2");
    if (ks.IsKeyDown(GameplayButtons.ACTIONBAR_3) && oldks.IsKeyUp(GameplayButtons.ACTIONBAR_3))
        UIManager.actionToBeTriggered("actionbar_3");
    if (ks.IsKeyDown(GameplayButtons.CHARACTER) && oldks.IsKeyUp(GameplayButtons.CHARACTER))
        UIManager.ToggleWindowById("button_Character");
}

There is probably some cleaner solution, especially if you have more buttons to handle.
Answer: Okay so it wasn't hard to fix this I just didn't think of it, but
hetting KeyboardStates in Input method instead of IsKeyPressed bool method fixes everything:
static bool IsKeyPressed(Keys key)
    {
        if (keyState.IsKeyDown(key) && prevKeyState.IsKeyUp(key))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static void Input()
    {
        keyState = Keyboard.GetState();

        if (IsKeyPressed(Keys.Space))
        {
            Cursor.X += 25;
        }

        else if (IsKeyPressed(Keys.Back))
        {
            Words.Last().RemoveLetter();
            Cursor.X -= 25;
        }

        else if (IsKeyPressed(Keys.A))
        {
            Words.Last().AddLetter(new Letter(Letters.A, Cursor));
            Cursor.X += 25;
        }

        prevKeyState = keyState;
    }

I'm not quiet sure what difference does it makes, if someone can explain in detail that would be awsome
PS. I can't upvote anyone because of my low reputation, but thanks everyone for sharing your thoughts it was helpful


Gradle print path of used jars in gradle init script

Question: I need to print the path of the jar files used by gradle.
Currently if I include the following lines in my top folder gradle project I am able to get the correct information:
allprojects {
    task printDependencies << {task -> println "Subproject -> $task.project.name" }
}

subprojects {
    printDependencies {
        afterEvaluate { Project project ->
            if (configurations.find { it.name == 'compile' }) {
                doLast {
                    println "$project.configurations.compile.asPath\n"
                }}}}}

Now I wanted to include this behavior into a init script as to avoid copying this code to all my build.gradle files.
The problem is I cannot get it to work at ${HOME}/.gradle/somename.gradle. The first error that pops up is:
Could not find method subprojects() for arguments

Is there any way to put this behaviour in a gradle init file?
Comment: Instead of using `project.afterEvaluate`, that logic can go inside `doLast`.
Answer: Gradle build scripts delegate to an instance of the Project class (see chapter 13 Gradle User guide), so that is where the subprojects method comes from.
However init scripts delegate to an instance of Gradle (see 60.3 Gradle User guide), which does not have a subprojects method.
It does have a rootProject method,so you probaby want something like
   projectsEvaluated {
     rootProject.subprojects {
         ...
     }
   }

Comment: It does not work. The error message is:
> The root project is not yet available for build.
Comment: Take a look at the api for the Gradle class that I linked to. I can see a number of approaches that you could try using them. I have updated the example in my answer to use one such approach.


How glVertexAttribPointer works?

Question: I know that when you call glVertexAttribPointer, you are specifying how the buffer currently binded should take its own data. But if you can have binded one buffer per type (Let's say GL_ARRAY_BUFFER and GL_ELEMENT_ARRAY_BUFFER) then, Are you specifying two buffers simultaneously? In this tutorial says:

glVertexAttribPointer always refers to whatever buffer is bound to
  GL_ARRAY_BUFFER at the time that this function is called. Therefore it
  does not take a buffer object handle; it simply uses the handle we
  bound previously.

If glVertexAttribPointer refers to the GL_ARRAY_BUFFER buffer currently binded, How I call glVertexAttribPointer for the GL_ELEMENT_ARRAY_BUFFER buffer?
Answer: A VAO holds the attribute information. This means that for each attribute it has a buffer, offset, size, type, stride and whether it's normalized. Separately from those is the element buffer binding that is set by binding the GL_ELEMENT_ARRAY_BUFFER while the VAO is bound.
Yes that odd but the reason this is the case is because VAO's were added after VBO and EBO.
In 4.5 (or with the Direct_state_access extension) you can instead use glVertexArrayElementBuffer to directly set the element buffer of a vao.
Comment: This answer is very helpful. In Example 3.5 of the Ninth Edition of the OpenGL Programming Guide, the EBO is bound *before* the VAO is bound, which doesn't work on my computer. After reading this answer I switched the order, which made it work. In Joey de Vries' "learnopengl.com" website, the correct order is given.
Answer:
How I call glVertexAttribPointer for the GL_ELEMENT_ARRAY_BUFFER buffer?

You don't. The element array buffer is used to store vertex indices, not vertex attribute data and therefore it doesn't have attribute pointers. The count, size, and offset for index data is specified in the draw call, e.g. glDrawElements.

How glVertexAttribPointer works?


How to dynamically change logging file output in Python

Question: How would you dynamically change the file where logs are written to in Python, using the standard logging package?
I have a single process multi-threaded application that processes tasks for specific logical bins. To help simplify debugging and searching the logs, I want each bin to have its own separate log file. Due to memory usage and scaling concerns, I don't want to split the process into multiple processes whose output I could otherwise easily redirect to a separate log. However, by default, Python's logging package only outputs to a single location, either stdout/stderr or or some other single file.
My question's similar to this question except I'm not trying to change the logging level, just the logging output destination.
Answer: you will need to create a different logger for each thread and configure each logger to it's own file.
You can call something like this function in each thread, with the appropiate bin_name:
def create_logger(bin_name, level=logging.INFO):
    handler = logging.FileHandler(f'{bin_name}.log')
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))

    bin_logger = logging.getLogger(bin_name)
    bin_logger .setLevel(level)
    bin_logger .addHandler(handler)

    return bin_logger

Comment: I'm not sure this is practical. I want to redirect all logging. That includes logs created by packages whose code I don't manage, and therefore can't modify to use my own `create_logger`()`.
Comment: It is more complicated but doable. You need to create a Handler with Filter per thread and add all handlers to the central log. all logging will be broadcast to all handler but will pass only the one with correct thread id. Each handler will have a different file. Look on this answer https://stackoverflow.com/a/55035193/3700626


Max width with twitter bootstrap label

Question: I am trying to achieve similar thing as SO with tags.
It looks great, but the problem is that I want to have a maximum width of each tag, so if a the length of the the tag, is too big, it will be truncated.
I can achieve it with:
.label{
    width: 50px;
    float: left;
    overflow: hidden;
}

Ok, it works, but when I do this, my number is not on the same line as label.
How can I achieve the same effect as on the first fiddle, but with maximum width.
Answer: This should to do the trick:
.label {
    display: inline-block;
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
}

JSFiddle demo.
What I've done here is dropped the float: left and replaced it with display: inline-block. I've then given it an ellipsis text-overflow property to make it look nicer, and set the vertical-align to middle to get it in line with the .multiple element. Oh, and I've replaced width with max-width to stop smaller tags being the same size.
Example Usage
Here is an example with multiple tags (each are on a new line intentionally): JSFiddle.

Obviously you can adjust the max-width accordingly.
Answer: You can give
 float:left;

to span.multiple as well so the span and label come in the same line.
.multiple{
    float:left;
}

Answer: You can add line-height to both of them
.label, .multiple {
  line-height: 15px;
}

Here is jsFiddle link.
Answer: .label{
   max-width: 150px;
   float: left;
   overflow: hidden;
 }

Comment: Have you actually tried it? It is the same thing that I just told that it does not work.

Max width with twitter bootstrap label


How to set radio button value by query string value on page load using AngularJS

Question: How to set radio button value by query string value on page load using AngularJS?
My View Code
Option One: This field can populate the "$scope.purpose" item in Controller, but doesn't select the radio button.
<input id="QueryStringLoanType" type="hidden" ng-model="data.purpose" ng-init="data.purpose = setLoanType()" />

Option Two: This field can populate the "$scope.data.purpose" item in Directive and selects the correct radio button, but I have to hard code value for it to work.
<input id="QueryStringLoanType" type="hidden" ng-model="data.purpose" ng-init="data.purpose = 'purchase'" />

My Controller
// Function: Set loan type
$scope.setLoanType = function () {
var queryStringLoanType = $location.search().loan_purpose;
$scope.purpose = queryStringLoanType;
if (queryStringLoanType == 'refi-loan') {
  $scope.purpose = "refinance";
}
if (queryStringLoanType == 'purchase-loan') {
  $scope.purpose = "purchase";
}
};

HTML

    Refinance
    <input type="radio" name="QuestionButton" ui-sref="home.custname" ng-model="data.purpose" value="refinance" ng-change="processForm()" />

    Purchase
    <input type="radio" name="QuestionButton" ui-sref="home.custname" ng-model="data.purpose" value="purchase" ng-change="processForm()" />

Any help is greatly appreciated!
Comment: where is radio button html? what is the reason behind using hidden element?
Comment: I used the hidden input to store the value of the the query string item I'm trying to pass to Controller.
Comment: you can directly get that inside angular controller..no need of hidden variable.have you tried my answer.
Comment: Yes, I tried your solution, but since both radio buttons affect the same model, the value is always set to "refinance" or whatever radio button shows last.
Comment: Oh..you're using different model for same radio then you should look at this https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
Comment: All though @pankajparker answer didn't solve my issue, your answer did show me results and got me looking at things differently. Thank you!
Answer: Probably your problem is with your radio buttons. You need to replace your value attribute with ng-value inside your radio element.
You might be declared radio button like this
<input type="radio" name="radio1" ng-model="data.purpose" value="purchase"/>
<input type="radio" name="radio1" ng-model="data.purpose" value="refinance"/>

Working Radio Button
<input type="radio" name="radio1" ng-model="data.purpose" ng-value="purchase"/>
<input type="radio" name="radio1" ng-model="data.purpose" ng-value="refinance"/>

only changed value attribute to ng-value, Angular will manage the value binding of that scope variable.
From your question things are not clearing.
I'm hoping this could help you. Thanks.
Answer: I didn't post this question to answer it myself, but after playing around with different solutions, this is what worked for me.
My form is a shared form that works globally on my website, but failed when trying to load my partial form view into a new landing page I'm building. My problem was that I was unable to populate a directive model value in my angular form without hard-coding the value into an ng-int attribute. I'm sure there's a better way to solve this problem, so feel free to comment.
My solution was to wrap my partial view on my landing page with a tag of my directive's name.
For example:
<my-directive>

    <input />

    <input />

</my-directive>


Yii2 Composer update fails: Undefined property: Fxp\Composer\AssetPlugin\Repository\AssetVcsRepository::$verbose

Question: When I try to update composer on a vanilla Yii2 install, everything goes well. When I try to update composer on an existing install with an IDENTICAL composer.json file, I get this error:
<code>Undefined property: Fxp\Composer\AssetPlugin\Repository\AssetVcsRepository::$verbose
</code>
I have no idea where to look to debug this and am pulling my hair out. Any ideas?
Many thanks for any insights!
Answer: I found it. A previous attempt had installed a vendor/fxp directory. The solution was to remove it, as documented here:
https://github.com/yiisoft/yii2/issues/9794


Android Adding Maps v2 API to Master Detail Flow - Error inflating class fragment

Question: I am trying to add a Google Maps view using the version 2 API to the built in Android Master Detail flow.  For some reason I am getting a error inflating class fragment exception:
    12-29 22:47:05.828: E/AndroidRuntime(1655): FATAL EXCEPTION: main
12-29 22:47:05.828: E/AndroidRuntime(1655): android.view.InflateException: Binary XML file line #48: Error inflating class fragment
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at com.reading.trackitparent.MapDetailFragment.onCreateView(MapDetailFragment.java:52)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.os.Handler.handleCallback(Handler.java:605)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.os.Looper.loop(Looper.java:137)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.app.ActivityThread.main(ActivityThread.java:4424)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at java.lang.reflect.Method.invokeNative(Native Method)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at java.lang.reflect.Method.invoke(Method.java:511)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at dalvik.system.NativeStart.main(Native Method)
12-29 22:47:05.828: E/AndroidRuntime(1655): Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
12-29 22:47:05.828: E/AndroidRuntime(1655):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)

I have created a new MapDetailFragment:
package com.reading.trackitparent;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.reading.trackitparent.dummy.DummyContent;

/**
 * A fragment representing a single Item detail screen. This fragment is either
 * contained in a {@link ItemListActivity} in two-pane mode (on tablets) or a
 * {@link ItemDetailActivity} on handsets.
 */
public class MapDetailFragment extends Fragment {
    /**
     * The fragment argument representing the item ID that this fragment
     * represents.
     */
    public static final String ARG_ITEM_ID = "item_id";

    /**
     * The dummy content this fragment is presenting.
     */
    private DummyContent.DummyItem mItem;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public MapDetailFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments().containsKey(ARG_ITEM_ID)) {
            // Load the dummy content specified by the fragment
            // arguments. In a real-world scenario, use a Loader
            // to load content from a content provider.
            mItem = DummyContent.ITEM_MAP.get(getArguments().getString(
                    ARG_ITEM_ID));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_map_detail,
                container, false);

//      // Show the dummy content as text in a TextView.
//      if (mItem != null) {
//          ((TextView) rootView.findViewById(R.id.item_detail))
//                  .setText(mItem.content);
//      }

        return rootView;
    }
}

and I am trying to use the following layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ItemDetailActivity" >

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</RelativeLayout>

ItemListActivity:
package com.reading.trackitparent;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

/**
 * An activity representing a list of Items. This activity has different
 * presentations for handset and tablet-size devices. On handsets, the activity
 * presents a list of items, which when touched, lead to a
 * {@link ItemDetailActivity} representing item details. On tablets, the
 * activity presents the list of items and item details side-by-side using two
 * vertical panes.
 *

 * The activity makes heavy use of fragments. The list of items is a
 * {@link ItemListFragment} and the item details (if present) is a
 * {@link ItemDetailFragment}.
 *

 * This activity also implements the required {@link ItemListFragment.Callbacks}
 * interface to listen for item selections.
 */
public class ItemListActivity extends FragmentActivity implements
        ItemListFragment.Callbacks {

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet
     * device.
     */
    private boolean mTwoPane;

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

        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the
            // large-screen layouts (res/values-large and
            // res/values-sw600dp). If this view is present, then the
            // activity should be in two-pane mode.
            mTwoPane = true;

            // In two-pane mode, list items should be given the
            // 'activated' state when touched.
            ((ItemListFragment) getSupportFragmentManager().findFragmentById(
                    R.id.item_list)).setActivateOnItemClick(true);
        }

        // TODO: If exposing deep links into your app, handle intents here.
    }

    /**
     * Callback method from {@link ItemListFragment.Callbacks} indicating that
     * the item with the given ID was selected.
     */
    @Override
    public void onItemSelected(String id) {
        if (mTwoPane) {
            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(MapDetailFragment.ARG_ITEM_ID, id);
            MapDetailFragment fragment = new MapDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.item_detail_container, fragment).commit();

        } else {
            // In single-pane mode, simply start the detail activity
            // for the selected item ID.
            Intent detailIntent = new Intent(this, ItemDetailActivity.class);
            detailIntent.putExtra(MapDetailFragment.ARG_ITEM_ID, id);
            startActivity(detailIntent);
        }
    }
}

I have referenced the Google Play Services Libs.  My manifest looks like so:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.reading.trackitparent"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="com.reading.trackitparent.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.reading.trackitparent.permission.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.reading.trackitparent.ItemListActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.reading.trackitparent.ItemDetailActivity"
            android:label="@string/title_item_detail" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ItemListActivity" />
        </activity>

        <uses-library android:name="com.google.android.maps" />
    </application>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxx" />

</manifest>

I would really appreciate any help!
Comment: You have to add the Google Play lib AND the src dir needs to be part of your project; not sure which IDE you are using or I could point you to examples on SO.
Comment: Using Eclipse - how do I add that in?
Comment: [Here](http://stackoverflow.com/questions/13719263/unable-instantiate-android-gms-maps-mapfragment/13744765#13744765) is the SO question that touched on it, note the answer from Guilherme Muniz.
Answer: Replace MapFragment with SupportMapFragment. SupportMapFragment is the one to use with the Android Support package backport of fragments. MapFragment is for the native API Level 11 version of fragments.
Comment: Thank you - I have done both of these things.  I am know getting a NoClassDefFoundError: com.google.android.gms.R$styleable both in an emulator and on my Xoom tablet.  It looks as though isGooglePlayServicesAvailable() is returning 1, although I have checked that Google Play Services are install from the Play Store.  Any ideas?
Comment: Update: Fixed the previous error, but back to the Error Inflating Class Fragment issue again.  I changed MapFragment to SupportMapFragment in the layout xml as suggested.
Comment: @JamesCross: Consider posting a fresh stack trace to your question.


Why is my styling being overwritten when adding a new React Component?

Question: I have a React component utilizing Material-UI called 'Profile', with custom CSS to create responsive font sizing like such:
let theme = createMuiTheme();

theme = responsiveFontSizes(theme);

theme.typography.h1 = {
    fontSize: '5.35rem',
    '@media (min-width: 600px)':{
        fontSize: '3.0rem',
    },
    '@media (max-width: 600px)':{
        fontSize: '2.2rem'
    },
    [theme.breakpoints.up('md')]:{
        fontSize: '5.35rem'
    }
}

The first few lines of the return are:
export default function Profile () {
        return (

                <ThemeProvider theme={theme}>
                    <Grid container direction="row">
                        <Grid item className="profile">

When I include this component in my index.js file, it renders perfectly. However, once I add a new component called 'PublicWorks.js' as such:
  <React.StrictMode>

      <Profile />
      <PublicWorks />
  </React.StrictMode>,

the responsive styling no longer works. The code for PublicWorks is very simple, essentially just this (with appropriate closing brackets):
import React from 'react';
import {Grid, Typography, Accordion, AccordionSummary, AccordionDetails, ThemeProvider} from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

export default function PublicWorks () {

    return (

            <Accordion>
                <AccordionSummary expandIcon={<ExpandMoreIcon />} >
                    <Typography>Project 1</Typography>
                </AccordionSummary>
                <AccordionDetails>

Is this overriding caused by the nature of MuiTheme operating at more of a global scale, or am I doing something else incorrectly? Should I be trying something like:
  <React.StrictMode>
    <ThemeProvide theme={theme}>

      <Profile />
      <PublicWorks />
    </ThemeProvide>
  </React.StrictMode>,

in order to implement this correctly?
Comment: Could you show the code inside `PublicWorks.js`?
Comment: I've just updated the code. Apologies for the confusion
Comment: If you need your custom theme in Header, Profile an PublicWorks component the answer is Yes, you shoul put the themProvider in the App,js
Comment: And if I just want it in Profile?
Answer: I think the problem you are having may be correlated with this issue.
Regardless, in general you would need to use the ThemeProvider as parent of your components since it uses React Context

This component takes a theme property, and makes it available down the
React tree thanks to the context. It should preferably be used at the
root of your component tree.

Docs: https://material-ui.com/styles/api/#themeprovider

Regarding your comment And if I just want it in Profile?
You can use other solutions such as makeStyles for this if you opt to style that component separately


ActionEvent doesn't work in libreoffice using python

Question: I am creating a for component command button by scripting in python. I fallowed the next tutorial https://help.libreoffice.org/latest/en-GB/text/sbasic/python/python_listener.html except that "com.sun.star.drawing.controlShape doesn't have the method addActionListener but AddEventListener
    oMRI.inspect(target )
def addingform():
    from com.sun.star.awt import Point
    from com.sun.star.awt import Size

    oDoc = XSCRIPTCONTEXT.getDocument()

    ctx = uno.getComponentContext()
    sm = ctx.getServiceManager()
    desktop = sm.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
    doc = desktop.getCurrentComponent()
    doc.getCurrentController().setFormDesignMode(True)
    oSheet = doc.getSheets().getByName("Sheet1")
    oDrawPage = oSheet.getDrawPage()
    oForm = oDoc.createInstance("com.sun.star.form.component.Form")
    oForm.Name = "Form2"
    oForms = oDrawPage.getForms()
    oForms.insertByIndex(0,oForm)
    oButton = doc.createInstance("com.sun.star.form.component.CommandButton")
    oButton.BackgroundColor = 15650253
    oButton.Name = "_MY_BUTTON"
    oButton.Label = "_MY_LABEL"
    #oButton.Enabled = True
    oForm.insertByName("_MY_BUTTON",oButton)
    oShape = doc.createInstance("com.sun.star.drawing.ControlShape")
    oShape.Control = oButton
    oDrawPage.add(oShape)
    oShape.Position  = Point(1000,2000)
    oShape.Size = Size(7560,4000)
    act = ActionListener()
    oShape.addEventListener(act)
    doc.getCurrentController().setFormDesignMode(False)

import uno, unohelper
from com.sun.star.awt import XActionListener
from com.sun.star.lang import EventObject
from com.sun.star.awt import ActionEvent
class ActionListener(unohelper.Base, XActionListener):
    def __init__(self):
        self.count = 0
    def actionPerformed(self, ActionEvent):
        msgbox("click")
    def disposing(self, eventObject):
        pass
~
~

I put an msgbox in __init__Self() and disposing and they  work
I want to click the command button and trigger msgbox
Comment: Please see https://stackoverflow.com/help/minimal-reproducible-example, so that people can understand your question and be able to identify your problem.
Answer: According to https://ask.libreoffice.org/t/how-to-programmatically-get-set-a-form-controls-events/45678/3, you need to add the listener to the form rather than to the control. So I came up with the following code.
from com.sun.star.script import ScriptEventDescriptor
oScript = ScriptEventDescriptor()
oScript.ListenerType = "com.sun.star.awt.XMouseListener"
oScript.EventMethod = "mousePressed"
oScript.AddListenerParam = ""
oScript.ScriptType = "Script"
oScript.ScriptCode = "vnd.sun.star.script:action_listener.py$test_message?language=Python&location=user"
oForm.registerScriptEvent(oForm.getCount(), oScript)

However, test_message() didn't get called. Probably there's some mistake, but I didn't want to spend too much time on it.
Note: Instead of form components, there are easier ways to create buttons, such as by inserting hyperlinks into a spreadsheet and then styling them to look like buttons.
Comment: acording to https://forum.openoffice.org/en/forum/viewtopic.php?t=71402&hilit=ScriptEventDescriptor&sid=c9d7250045716b0035c562422ecd6199 when you create one commandbutton you need to start in zero oForm.registerScriptEvent(0,oEvent)


Fitting new dimmer to old wiring but I've got four wires and an earth

Question: I'm fitting a new dimmer to a switch that controls a single ceiling bulb. Currently the switch has two red wires attached, one top one bottom. I'm guessing that this is live from circuit box and then live to ceiling rose. The two black wires have been connected together with a small box and the green is attached to the metal fixing embedded in the wall.

The dimmer I've bought says to fit a red and a black to terminals c and l1 respectively. Do I choose any two red and black wires? The instructions mention if there are two wires then put them both into the appropriate terminal on the switch but that seems like it would result in a constant connection between the two live wires.
Comment: A  complication: this dimmer is labeled for 2-way (USA: 3-way) switch operation. Color code advice is likely to be wrong since they are expecting a branch to another 2-way switch.
Comment: Also is that dimmer listed to play well with LEDs? Edison bulbs are going the way of the dinosaur.
Comment: @Harper, I suspect most light switches sold in the UK (for example) are 2-way (USA 3-way) even though the L2 terminal is usually not used. In other words, it is common to find 2-way(3-way) switches used for 1-way(2-way) applications. Good point about LEDs though. Flickering LEDs or LEDs glowing dimly when off are a common subject of questions on this website. LED compatibility with dimmers is pot-luck depending on which Chinese factory bid lowest this week.
Answer: The instructions for that dimmer switch assume that you only have a "switch loop" wired to the switch.
A "switch loop" brings an always-on Live wire down to the switch and carries the switched Live back up to the light fixture.
In this case, the always-on Live should be Red and the switched Live return should be Black.
The Neutral side of the power connection stays up at the light and is not brought down to the switch.

But what you have there is the always-on Live and its associated Neutral both brought to the switch, and then the switched Live and Neutral sent up to the light.
The Red wires are the Lives and the Black wires are the Neutrals.
There's no way to know for sure just by looking at your picture which of the Reds is always-on and which runs up to the light.
The switched Live should be marked somehow and it's possible that the red tape wrapped around one of the red wires is intended to be that mark.
But in your case it doesn't really matter because your dimmer doesn't care.
Just disconnect the 2 red wires from the old switch and connect them to the 2 terminals on your new dimmer which the instructions tell you to use (C and L1).
Also, as RedGrittyBrick pointed out, your new dimmer has an Earth terminal which your old switch did not.
This terminal must be connected to the green Earth wire in the box using a wire with green/yellow insulation.
Comment: Note, the metal switchplate has an earthing terminal which needs to be connected to the earth terminal in the backbox using an extra piece of copper wire in a green/yellow insulating sleeve. For what it's worth, Crabtree also sell in the UK (presumably hence the CE mark) and the wire-colours, metal backbox and switchplate formats are all typical of UK as well.
Comment: @RedGrittyBrick - true - I should add that to my answer, and since the branding isn't particularly relevant I'll remove that bit. And looking more closely at the shape & size of the plates they do look much more like UK than ZA.
Comment: @brhans had the most thorough answer. I got delayed in actually replacing the switch (depth of the box turned out to be a real pain) but can confirm wiring wise this was 100% correct.
Answer: The green is ground, that should stay connected to the box.  I cannot see where the two black wires are connecting.  It is normal to have two of positive  and negative  wires
Comment: AC mains doesn't have 'positive' and 'negative' wires. It has 'Live/Hot' and 'Neutral' wires.
Comment: You cannot leave a negative since my thread is correct and implying to receive more info.


How is the end of round bonus calculated?

Question: I've found several very contradictory explanations / formulas how the end of match bonus in MW3 multiplayer is calculated.
I would be very grateful if someone could shed some light on this subject.  If you can, please provide reliable sources.
Answer: This is from a modder who hacked the game code:
<code>Scaler = 1 if you win the match, 0.5 if you lose
spm = (3 + ( YOUR_RANK * 0.5 ) ) * 10
//maxmatchLength in seconds, YOUR_MATCHTIME in seconds (time it took to finish the match):
matchBonus = Scaler * ( ( maxmatchLength/60 ) * spm )  * (YOUR_MATCHTIME / maxmatchLength)
</code>
Obtained from here.
Hope this helps!


Let $K=F(\frac{x^7}{x^5+x^3+3x+1})$, where $F$ is a field. Determine $[F(x): K]$.

Question: (a) Let $R$ be a unique factorization domain and consider
$$ f(x,y) = x^7 + yx^5 + yx^3 + 3yx + y \in R[x,y].
$$
Show that $f(x,y)$ is irreducible.
Proof: Note $R[x,y]=R[y][x]$. Let $S=R[y]$. We will show $f(x,y)$ is irreducible in $S[x]$. By Eisenstein's Criterion, let $p=y$,

$y | a_0=y, a_1=3y, a_2=0, a-3=y, a_4=0, a_5=y, a_6=0$
$y \nmid a_7=1$
$y^2 \nmid a_0=y$

Why is $y$ a prime in $S$? Notice that $S/(y)=R[y]/(y)\cong R$ and $R$ is integral domain. So $(y)$ is a prime ideal in $S$, and hence $Y$ is a prime element in $S$.
Q.E.D.
(b) Let $K=F(\frac{x^7}{x^5+x^3+3x+1})$, where $F$ is a field. Determine $[F(x): K]$.
I think that I need to first show whether $x^5+x^3+3x+1$ is irreducible or not. But I'm not sure if that is right or how to show that or how to follow from there. Can I get some help?
Answer: Let $y=\frac{x^7}{x^5+x^3+3x+1}$, this is an element of $K$. We get:
$x^7-yx^5-yx^3-3yx-y=0$
Just like before, you can show that the polynomial $t^7-yt^5-yt^3-3yt-y\in K[t]=F(y)[t]$ is irreducible over $K=F(y)$, and so it is the minimal polynomial of $x$ over this field. So $[F(x):K]=[F(y)(x):F(y)]=7$.


Do I need to clean out/fill in cracks in wood floor?

Question: We have a lot of gaps between boards in our wood floor (see pic, I'm holding a penny in the crack, some are wider, most are narrower).  It looks like the cracks were originally filled with something, not sure what though (maybe just wood filler).
When I refinish the floors do I need to remove the filler and refill the gaps?  If so, how do I go about both?
Comment: Be best to fill them in, they only become dirt/mold/fungus traps.  Some ideas from this link.  https://diy.stackexchange.com/questions/170634/can-epoxy-artistically-fill-gaps-in-old-wood-floors?rq=1
Answer: In my 1920's house, the cracks between oak floorboards where caused by house settling, and sometimes compressing floorboards. They vary in width by time of year. That makes filling impractical. I do glue down any potential splinters with wood glue and a 5 Lb weight.
Comment: Not sure that's the same problem since our floorboards had the gaps filled from the beginning (well, I assume they were) and our house was built in the 60's.  On the other hand, maybe the filler is breaking up due to expansion/contraction of the boards. Is your floor sealed?
Comment: I saw the boards, and they looked like 1920's oak to me. In a newer house, they might well have filled in the cracks. I tried some of that in my old house, and it just cracked open. Your situation may be entirely different. I'd watch the cracks, and see if they change by season. Hopefully refinishing isn't a "git er done right now" task for you.
Comment: With heat and humidity changes solid flooring can move quite a bit. I can't quite tell if that is a nickel or penny but the gaps look uneven and could be from sessional movement.
Comment: @EdBeal That's a penny on the picture.  There are some gaps wider (maybe a quarter's width...maybe a little more) and there are a lot of adjacent boards that have no gap.
Comment: @WayfaringStranger No, this is 1960's oak, 3/4" thick.  No, this does not need done now.  It's just the next major project on the horizon and I'm starting to plan it out.


Pass the pipe character from a DOS batch script in a CALL statement

Question: within a DOS batch script (that needs to run in the Win 200x and Win7 environments) I need to pass a particular character, in quotes, to another executable; e.g.
 doparse -delimeter "$"

In general this works:
 CALL CMD /C "doparse -delimeter "$""

Unfortunately, I need to specify the pipe character as the delimeter (this is a requirement). I expected the following would work:
 CALL CMD /C "doparse -delimeter "^|""

But when I run the script I don't see any output at all for this line (e.g. no error message if I replace "doparse" with some non-existent name).
I've tried various combinations of escape chars but cannot get it to work. Is it possible? (Has to be done via a batch script, unfortunately).
Thanks
Comment: Why are you using `CMD /C`? It was only required in old versions of DOS that didn't support the CALL syntax to invoke one batch file from another. Also it isn't necessary to quote the parameters to `CMD /C`, you're thinking of `sh -c` which does take one quoted parameter.
Answer: The following works for me:
call delim -delimiter "|"

and then using it like this in the called batch:
setlocal enabledelayedexpansion
set "delim=%~2"
echo Delimiter: !delim!

Comment: That's it. Somehow I missed the simpler CALL syntax. Thanks Joey!
Comment: The solution is simple, but the cause of the failure is complex ;-)
Answer: These versions should work cmd /c "test2.bat "^|"" and cmd /c ^"test2.bat "|"".
Both starts the test2.bat.
Also the version of Joey works.
The problem in your case is the call and the number of quotes, it's not possible to escape special characters in a call statement (outside of quotes), at least without the special caret trick.
Example
set "caret=^"
call echo &
call echo ^&
call echo ^^&
call echo ^^^&
call echo "&"
call echo %%caret%%^&

Only the last two works, the first is inside of quotes and the second escapes the & in the second parser run with the special caret trick.
In your case the | is outside of the quotes (it's after the second quote).
And there is a bug in cmd.exe so it immediatly stops, if the parser founds a unescaped & or |<> after a call phase.


v-model inside a component is not listening to events vuejs

Question: I need to make a dynamic v-model using v-for. I have a child component that will be used inside the father component.
I'll put the full code and the warning received.
It is funny because I use the same method in other project (NUXT) and it is working just fine. And this project (vuejs) has the same code and it is not.
It is seems to me it is not listening to 'event' and because of that the v-model is not working well. The v-model value does not update according to the changes on input space.
This is the Child Component
<template>

            {{ profileDataItem }}

            <input
                type="text"
                class="form-control"
                :value="value"
                @input="$emit('input', $event.target.value)"
            >

</template>

And this is the father component
<template>

        <form class="login-form p-3 border m-auto">

Register yourself

            <RegisterField
                v-for="(item, index) in profileDataItems"
                :key="index"
                :profileDataItem="profileItems[index]"
                v-model="item.model"
            >
            </RegisterField>
        </form>

</template>

Warning on console
[Vue warn]: Missing required prop: "value"
  at <RegisterField key=4 profileDataItem="Confirm Password" modelValue="confirmPassword"  ... >
  at <RegisterForm>
  at <SigninPage onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy {…} > >
  at <RouterView>
  at <App>

Answer: change value prop to modelValue your component's code should be this:
<template>

      {{
        profileDataItem
      }}

      <input
        type="text"
        class="form-control"
        :value="modelValue"
        @input="$emit('input', $event.target.value)"
      />

</template>

Comment: Yes, Sadeq! I got it thankssss. Just to the others, I needed to update something in your tip. Here it is: @input="$emit('update:modelValue', $event.target.value)"
Comment: happy to help my friend


Is it possible to respec weapon upgrade points?

Question: I put a lot of points (Raritarium) into some of the early weapons I never found much use for, most notably the Combuster. Are the Raritarium upgrades permanent and can they ever be remove or changed at will?
Answer: From a cursory search and given how game mechanics usually work for such a renewable resource, probably not, because it'd be too easy to fund higher-level upgrades by scrapping lower-level ones, just gotta grind for more Raritarium, I guess.
Hope you purchased some of the Raritarium drop-rate boosters...
Comment: As far as I remember, I confirm this.


AWS cognito SRP calculations on JS browser app

Question: I'm a webDev and I need to integrate a login page using AWS cognito User Pools. I can't use the integrated UI so I'm using @aws-sdk/client-cognito-identity-provider.
I'm not in a secure server environment and can't keep secrets so I'd like to use SRP to login via the InitiateAuthCommand. I guess it's the recommended flow in the docs.
This aws srp auth doc flow page talks about 'SRP calculations' but I can't find any way to do it with the SDK nor any lead in the doc.
After some research, the  crypto requisite to implement this myself are too high to make this solution secure.
So my question is : How are you supposed to use SRP without the integrated UI ? Is this even possible without strong security knowledge ?
I have found some third-party libs, but I find it really weird to have to rely on this for such a critical part of an application when using AWS.
Comment: I know it's been some time since this question was posted, but there might be some confusion with the question.

You mentioned "I'm not in a secure server environment and can't keep secrets" and "I'd like to use SRP".

The confusing aspect is the "can't keep secrets". Is this public client? If so, then there's no need for secrets (assuming you're referring to the app client secret). If this is intended to be a private client, then that's a conflict with not having a "secure server environment"

So, to be clear app client secrets have nothing to do with using SRP.
Answer: You may have misunderstood the doc here. Your actual concern seems to be about how to implement SRP. This isn't a valid concern because the document mentions that:

The app generates SRP details with the Amazon Cognito SRP features
that are built in to AWS SDKs.

You don't need to worry about the details of SRP implementation. The SDK will handle that for you.
Here's the second part of the question: How can you securely use Amazon Cognito in an unsecured environment like a web frontend or mobile app? Since Cognito offers two types of operations:

Authenticated operations: These require IAM credentials, an access token, a session token, a client secret, or a combination of these.
Unauthenticated operations: These don't require including any secrets in your code. Please refer to this link and open the "Unauthenticated user operations" section for more details.

If you're interested in the actual code implementation, there are examples of usage in JS that you can easily copy and paste into your project (be sure to follow any required prerequisites).


How to detect that "where i am" in a usercontrol?

Question: I have a user control called "TopMenu". I have five pages in my website. Menu codes are like that below:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UstMenu.ascx.cs"         Inherits="UstMenu" %>

Anasayfa

Hakkımızda

enter code here

Ürünler

Destek

İletişim

I have an "active" class as you see upthere in my css.For example, If a user click on support page, Support page link must take "active" class. I dont want to write my menu to all of my pages.    How can i detect which page i am in?
Answer: You can do this on the back end, or on the front end via JS or CSS. If you want to stick with CSS, the trick is to place a different class or ID on each page, say on the  element:

On each list item, you put something similar. E.g.
Hakkımızda

Then, in your CSS file, have a series of declarations like this:
.about .about, .contact .contact, .home .home {active styles here}

(As a side note, it's better to call these "current" links rather than "active" ones, as ":active" links are something different.)


Question about bilinear form on Hilbert space

Question: I am trying to verify the following
Let $H$ be a Hilbert space, and let $a(\cdot,\cdot)$ be a real continuous bilinear form on $H$
Then, define the operator $A:H-> H'$ as
$Au(v) :=a(u,v), v\in H$
Also, define the operator $B:H->H'$ as
$Bu(v) :=a(v,u), v\in H$.
Then, I want to show that A is surjective if and only if B is injective.
Here is my attempt:
Assume A is surjective. Let $w,z \in H$ such that $Bw(v) = Bz(v), v\in H$. That is, $a(\cdot,w) = a(\cdot,z)$.
By using surjectivity of A, then I can find $s$ and $t$ in $H$ such that $a(s,\cdot) = a(\cdot,w)$ and $a(t,\cdot) = a(\cdot,z)$.
Then, I somehow want to conclude that z = w, but I am not sure how what to do next.
How should I proceed?
Comment: This may be a bit easier if we use the Riesz representation theorem as applied to bilinear forms.
Comment: @Omnomnomnom What do you mean by "as applied to bilinear forms"? I know the Riesz Theorem for the general Hilbert case
Comment: I mean that we can find a bounded $T:H \to H$ such that $a(x,y) = \langle x, Ty \rangle$
Answer: Here's one direction:
Assume $A$ is surjective.  That is, for every $f \in H'$, there exists a $u \in H$ such that
$$
a(u, \cdot) = f(\cdot)
$$
Now, suppose that $v,w \in H$ are such that $B(v) = B(w)$, that is, $a(\cdot,v) = a(\cdot,w)$.
That is, for every $u$, we have $a(u,v) = a(u,w)$.  By surjectivity, this implies that for every $f \in H'$, we have $f(v) = f(w)$.  This in turn implies that $v = w$ (why? we could use this, for example, but that's overkill.  Riesz representation could work here).  Thus, $B$ is injective.

Riesz representation approach: For every $f \in H'$, we have $f(v) = f(w)$.  Thus, for every $x \in H$, we have $\langle v,x \rangle = \langle w,x \rangle$.  So, we have
$$
\langle v,x \rangle = \langle w,x \rangle \qquad \forall x \in H \implies\\
\langle v,x \rangle - \langle w,x \rangle = 0 \qquad \forall x \in H \implies\\
\langle v-w,x \rangle = 0 \qquad \forall x \in H \implies\\
\langle v-w,v-w \rangle = 0 \implies\\
\|v -w\|^2 = 0
$$
Comment: Could you please show how you would use Riez representation to show $v = w$? I am just doing a  baby step with functional analysis, so it would be very helpful if you could show that
Comment: See my latest edit.
Comment: In your Riesz rep approach, you are considering every linear functional of the form $<\cdot,x> , x\in H$, so I guess even if I do not know $<\cdot,x> \in H'$ gives every continuous linear functional on H, the proof would still go through?
Comment: That is, we do not really need the "representation" aspect. we just need to know $<\cdot,x>$ is a continuous linear functional?
Comment: We need to know that the particular functional $\langle \cdot,v-w\rangle$ is hit by $A$. So you're right! No representation required.
Comment: Great! I got it!!!


Problem processing the data of a file to kafka and this to spark structured streaming

Question: I'm trying to produce from a file to kafka and then consume it in spark streaming.
historical_data_level_1.json -> producer.py -> consumer.py
The problem is that when the messages arrive at spark they arrive strange, so I understand that the problem is in the producer.py
when i check the df
kafka_df.selectExpr("CAST(value AS STRING)").show(30, False)

the result is:
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|value                                                                                |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|"{\"localSymbol\": \"EUR.USD\", \"time\": \"2021-05-07 10:10:50.873031+00:00\", \"precio_actual\": 1.2065, \"bid\": NaN, \"ask\": NaN, \"high\": 1.20905, \"low\": 1.2053, \"close\": 1.2065}\n"                   |
|"{\"localSymbol\": \"EUR.USD\", \"time\": \"2021-05-07 10:10:50.873720+00:00\", \"precio_actual\": 1.208235, \"bid\": 1.20823, \"ask\": 1.20824, \"high\": 1.20905, \"low\": 1.2053, \"close\": 1.2065}\n"         |
|"{\"localSymbol\": \"USD.JPY\", \"time\": \"2021-05-07 10:10:50.914310+00:00\", \"precio_actual\": 109.09, \"bid\": NaN, \"ask\": NaN, \"high\": 109.2, \"low\": 108.935, \"close\": 109.09}\n"                    |
|"{\"localSymbol\": \"USD.JPY\", \"time\": \"2021-05-07 10:10:50.914867+00:00\", \"precio_actual\": 109.10249999999999, \"bid\": 109.102, \"ask\": 109.103, \"high\": 109.2, \"low\": 108.935, \"close\": 109.09}\n"|
|"{\"localSymbol\": \"USD.JPY\", \"time\": \"2021-05-07 10:10:50.975038+00:00\", \"precio_actual\": 109.102, \"bid\": 109.101, \"ask\": 109.103, \"high\": 109.2, \"low\": 108.935, \"close\": 109.09}\n"           |
|"{\"localSymbol\": \"USD.JPY\", \"time\": \"2021-05-07 10:10:51.059851+00:00\", \"precio_actual\": 109.1015, \"bid\": 109.101, \"ask\": 109.102, \"high\": 109.2, \"low\": 108.935, \"close\": 109.09}\n"          |
|"{\"localSymbol\": \"EUR.USD\", \"time\": \"2021-05-07 10:10:51.101304+00:00\", \"precio_actual\": 1.208235, \"bid\": 1.20823, \"ask\": 1.20824, \"high\": 1.20905, \"low\": 1.2053, \"close\": 1.2065}\n"         |

If I copy and paste the data in a terminal (producer) then it works correctly, so the problem is in how I send the messages to spark
Could you help me?
I have the following file historical_data_level_1.json with this data:
{"localSymbol": "EUR.USD", "time": "2021-05-07 10:10:50.873031+00:00", "precio_actual": 1.2065, "bid": NaN, "ask": NaN, "high": 1.20905, "low": 1.2053, "close": 1.2065}
{"localSymbol": "EUR.USD", "time": "2021-05-07 10:10:50.873720+00:00", "precio_actual": 1.208235, "bid": 1.20823, "ask": 1.20824, "high": 1.20905, "low": 1.2053, "close": 1.2065}
{"localSymbol": "USD.JPY", "time": "2021-05-07 10:10:50.914310+00:00", "precio_actual": 109.09, "bid": NaN, "ask": NaN, "high": 109.2, "low": 108.935, "close": 109.09}
{"localSymbol": "USD.JPY", "time": "2021-05-07 10:10:50.914867+00:00", "precio_actual": 109.10249999999999, "bid": 109.102, "ask": 109.103, "high": 109.2, "low": 108.935, "close": 109.09}

I have the following producer producer.py
import json
from kafka import KafkaProducer
import settings

def producer():
    kafka_producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
    with open(settings.HISTORICAL_DATA_FOLDER+"historical_data_level_1.json") as historical_data_level_1:
        for line in historical_data_level_1:
            kafka_producer.send("test", json.dumps(line).encode('utf-8'))

if __name__ == '__main__':
    producer()

and
I have the folloing consumer consumer.py
from pyspark.sql import SparkSession
from pyspark.sql.functions import from_json, col, expr
from pyspark.sql.types import StructType, StructField, StringType, LongType, DoubleType, IntegerType, ArrayType

if __name__ == "__main__":
    spark = SparkSession \
        .builder \
        .appName("File Streaming Demo3") \
        .master("local[3]") \
        .config("spark.streaming.stopGracefullyOnShutdown", "true") \
        .config('spark.jars.packages', 'org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1') \
        .getOrCreate()

    kafka_df = spark.readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "localhost:9092") \
        .option("subscribe", "test") \
        .option("startingOffsets", "earliest") \
        .load()

    kafka_df.printSchema()

    schema = StructType([
        StructField('localSymbol', StringType()),
        StructField('time', StringType()),
        StructField('precio_actual', StringType()),
        StructField('bid', StringType()),
        StructField('ask', StringType()),
        StructField('high', StringType()),
        StructField('low', StringType()),
        StructField('close', StringType()),
    ])

    value_df = kafka_df.select(from_json(col("value").cast("string"), schema).alias("value"))

    value_df.printSchema()

    level_1_df_process = value_df \
        .select(
            'value.*'
        )

    invoice_writer_query = level_1_df_process.writeStream \
        .format("json") \
        .queryName("Flattened Invoice Writer") \
        .outputMode("append") \
        .option("path", "output") \
        .option("checkpointLocation", "chk-point-dir") \
        .trigger(processingTime="1 minute") \
        .start()

    invoice_writer_query.awaitTermination()

Comment: structured streaming?
Comment: yes, is structured streaming
Answer: It is solved sent by the producer.py a dictionary instead of a string, leaving the code as follows
import json
from kafka import KafkaProducer
import settings

def producer():
    kafka_producer = KafkaProducer(bootstrap_servers=['localhost:9092'])
    with open(settings.HISTORICAL_DATA_FOLDER+"historical_data_level_1.json") as historical_data_level_1:
        for line in historical_data_level_1:
            line_python_dict = json.loads(line)
            kafka_producer.send("test", json.dumps(line_python_dict).encode('utf-8'))

if __name__ == '__main__':
    producer()


Casting pointer types on different architectures

Question: I have the following structure and "getter" function that returns a cast to an unsigned integer:
struct s {
    uint32_t a;
};

void get_a(struct s *st, unsigned *ret)
{
    *ret = (unsigned)st->a;
}

The following code is run:
struct s st;
uint16_t x;

st.a = 1;
get_a(&st, (unsigned *)&x);

And for x86_64, i686, armv7hl, ppc64le and other architectures x == 1, but for ppc64 x == 0. Why is this? Little- vs. big-endian?
Comment: Set a to 0x12345678. Little-endian machines will return 0x5678, big-endian 0x1234. To maintain same behavior on all machines use htonl/htons/ntohl/ntohs functions.
Answer: The problem is that you have:
uint16_t x;

but then you try to write to that memory location as if it were the location of unsigned.
If you were on a system where unsigned and uint16_t are the same type, this is fine. But on other systems, such as the one you used for your code sample, you are in trouble.
First of all, this causes undefined behaviour by violating the strict aliasing rule. Variables of type uint16_t may only be written to through lvalues of type uint16_t, or a character type.
But even if it did not violate strict aliasing, you would still cause UB by writing outside the bounds of x. Probably, you are writing 4 or 8 bytes into a 2-byte memory location, so it will overflow the buffer.
There could also be UB if x is not correctly aligned for unsigned.
Comment: @black it sort of does: *if* all of the UB in the code doesn't produce nasal demons this time, we might expect that the `1` bit being written appears either inside `x` or outside `x` depending on the system endianness
Comment: Lesson learned: Do not cast pointers, or at least be very careful with what you are doing. There mostly ever is a different solution. Here a temporary `unsigned` typed variable would have wiped away all uncertainties.
Comment: I think it's also worth mentioning that endianness has nothing to do in this case.


Is it ok that the drain line for a septic system is above ground?

Question: Looking to buy a property with mound septic.  The pipe coming out of the house going into the mound is above ground.  Is this ok?  Would the pipe not freeze?
Thank you.
Comment: Not if you're in a freezing climate (or have any aesthetic sensibility). Are you sure that's the case here? Maybe what you're seeing is a vent line or something. Photos would be great.
Comment: I'm not totally sure.  The pipe comes out of the house and goes directly into the mound.  I will try to get a photo.  Thank you
Comment: If you have a pumped system it will be on the surface. You don't want the nozzles buried deep for when they get plugged and need to be replaced.
Answer: It would seem strange that the waste drain pipe goes straight out of the house above ground to the mound.  The primary purpose of the mound is for the distribution of water after it has passed through an enclosed septic tank and a pumping tank.  These two chambers are normally underground.  The pipes from the pumping stations would also be underground up to the mound and still would be buried in the mound as it travels to the top of the mound to the water distribution pipes.
I would have the owner explain where the septic tank and pump tanks are located and why the pipes you see are above ground.
Photos and more details on the pipes would be helpful.  Are these pipes on the surface of the ground?  What is the distance from house to mound?
Is it OK, depends on whether a fully functional septic system has been installed.
Comment: Pipe is 2 ft above ground, approx. 4 ft. from mound.  My son came and looked at this house I was wanting to purchase and he said "no go" so I don't have to worry about it now.  Thank you for your help.
Comment: 2 _feet_ above grade? Full stop.


What things can you unlock or customize for your apartment?

Question: There are a number of things that I've found so far that get added to my apartment - there is the gun wall from adding weapons into your stash, this allows you to show off a selection of weapons you've collected. There is a also cat that I have befriended by feeding it that now lives at the bottom of my bed.
Are there any other things that you can unlock or customize for your apartment?
Answer: You obviously have the gun wall. There is a seperate question specifically for the gun wall so I won't cover this in depth here but this wall is populated by putting specific iconic weapons into your stash.

You can get a cat - the cat is available by leaving your apartment and immediately going left to the end of the corridor. Just around the corner there is a bowl next to a note saying 'feed the cat'. If you put cat food in the bowl and then come back the next day, there will be a cat that you can take back to your apartment.

If you complete the side quest Fool on the Hill, Misty will gift you a dreamcatcher that you then hang above your bed. You don't have to hang it, it will be hung for you automatically.

After completing the Riders on the Storm side job, you will unlock another small job called I'll Fly Away, which is Scorpion's funeral. At the end of his send off Mitch will give you a Scorpion figure, which you can then put on the table in your apartment.

For completing the Peralez side mission Dream On, you get a Vote Peralez campaign poster, which is automatically put up on the wall next to the front door to your apartment. This seems to be the case even if you do not finish the missions on good terms.

Likewise if you complete the Lizzy Wizzy side mission Violence you get a Lizzy Wizzy poster to go next to your Peralez poster. This seems to be the case even if you don't stop her from going psycho.

Depending on your player back story, you will either have a Night City model, an Arasaka paperweight or a car model on your desk, after completing some of the first missions made available to you in the game.

After completing Following the River, you will get a copy of Big Trouble in Heywood (the augmented reality game you played with Joss's kids).

If you complete Judy's side quest Pyramid Song, you also unlock some scuba gear that is stored in your apartment.
If you complete the Zen Master questlines comprising of the quests Imagine, Stairway to Heaven, Poem of the Atoms and Meetings Along the Edge - you will be gifted an Altar, which is hung next to your bed.
Comment: I also picked up some Us Cracks and Kerry Eurodyne posters by following the quests linked to both of them respectively.
Answer: Spoilers:

During Jackie's funeral, if you scan the posters in his garage they will appear next to your pc.


Cache values of window.innerHeight and window.innerWidth

Question: To prevent layout thrashing I want to cache the values of window.innerHeight and window.innerWidth. Am I correct in assuming that this module:
module.exports = {
  h: window.innerHeight,
  w: window.innerWidth
};

When browserified, will access window.innerHeight and window.innerWidth everytime the properties are used, but that the below module:
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;

module.exports = {
  h: windowHeight,
  w: windowWidth
};

Will only access window.innerHeight and window.innerWidth once? Even when the exported properties are accessed multiple times?
Answer: I don't think you are right... I think both your examples will cache the values.
Module code is indeed run when an app is started, and just made available using require. It is not re-run at each require. If you want non-cached values, you'll have to put them in a method, something like:
module.exports = {
    cachedH: window.innerHeight, // will not change

    calculatedH: function() {
        return window.innerHeight; // will recalculate each time called
    }
};

Comment: Won't the properties in the first example just be passed as a reference instead of as a value?
Comment: You could prove me wrong, but I don't think so. I've been bit by that with trying set dates to the current time, and they keep returning the time my app started.
Comment: @vsjn no, numbers are always passed by value.


Woodstove Install in a Barn

Question: I want to install a 10yo Vermont Castings woodstove in a un-insulated barn so I can work on projects throughout the winter and allow friends and family to play ping pong.
I want to use single wall pipe to maximize heat exchange as well as it is much cheaper. The distance of the stove to the roof (10' off the peak) is about 25'.
I will mount the stove on a tile slab that I make from leftover tiles. I have 2 wood beams running horizontal that the exhaust pipe will pass by within 6 inches. I will either wrap the beams in fire retardant cloth or mount cement board in front of the beams.
What other considerations should I be making?
I had a sight unseen install quote of $3900 for this job and I feel confident that I can do it for much, much less.
Comment: You'll do better on this site with more clear and direct questions, though you might still get some good answers
Comment: Make sure you transition to double- or triple-wall pipe when you penetrate the ceiling, depending on local code.
Comment: I would put a very thick base, *thermal mass*, of concrete or pavers under your tiles  and a thick cement board  barrier between the stove and the wall. These will  capture heat  and radiate heat into the space.
Answer: Regardless of what you prefer, you need to meet both the requirements of your town/city/county (LAHJ) for proper woodstove installation, and your insurance company's standards, unless you operate "at risk" without insurance.
Both of those entities will almost certainly require transitioning to UL Listed Class A insulated chimney before leaving the room. If the beams in question are at, near (and you transition to class A before passing them), or in the ceiling space that will likely also address protecting them adequately, since those systems have much smaller clearances to combustibles than uninsulated single-wall stovepipe.
You will need to extend the exterior chimney at least 2 feet above the peak of the roof (2 feet above the highest part of the roof within 10 feet is the code language, so far as I recall at present.) You might be able to save money on Class A Chimney by locating the class A chimney at the peak of the roof (where it only has to stick up 2 feet above the peak) and angling the singlewall pipe to the center in the room below. That position is also less prone to leaks than a chimney sticking out 10 feet down the slope of the roof.
You will need to give consideration to access for cleaning your stovepipe and chimney, as well. A long run of singlewall can help to heat the space, but it also serves as a great place to collect creosote and start chimney fires.
It may also be required (and would be advisable regardless of that) to install smoke and carbon monoxide detectors in the space.

Woodstove Install in a Barn


iOS Pass on label of row in UITableView

Question: I'm trying to pass on the label of a table row when you hit that rows accessory button as it matches the key of an array in a plist, so the next page knows which array to load the settings from.
This is the code I'm using at the moment in performSegueWithIdentifier:
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
SettingsViewController *destViewController = segue.destinationViewController;
destViewController.nameViewer = [viewerKeys objectAtIndex:indexPath.row];

Unfortunately every time it picks the first row... I know because using NSLog it always gives the same output (the name of the first row). Any Ideas?
Cheers,
Chris
Answer: The problem is that when you tap an accessory button of a cell, the cell itself doesn't get selected (this is normal behavior since accessory buttons fire a different delegate method), so you get always 0.
What you could do though is to set an ivar with the selected index inside tableView:accessoryButtonTappedForRowWithIndexPath: delegate method and pass that ivar to your destination controller. I hope that this makes sense...
Comment: I did - it made me wait for a bit first :)
Answer: Use -prepareForSegue:sender: instead of -prepareForSegue: and use the following:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSIndexPath *indexPath = [[[segue sourceViewController] tableView] indexPathForCell:sender];

    SettingsViewController *destViewController = segue.destinationViewController;

    destViewController.nameViewer = [viewerKeys objectAtIndex:indexPath.row];
}

iOS Pass on label of row in UITableView


How to get BSSID of Access Point from client?

Question: I am developing a Django application and I need to know to which access point the client/user is connected to.
By searching in the internet I found out that I can find it using the BSSID of the access point.
The problem is I am unable to find a way to get that BSSID.
So, I want to know is there any information in the request object of Django.
If not, is there any other way to get the BSSID using JavaScript.
(Note: Please share any way that can be helpful to me).
If all those can't work can we set some configurations in the access point and use them to find the client access point (Yes, I have the option to set them as we are developing this application to be run on a organization server).
Any information will be appreciated.
Thank you in advance.
Answer: JavaScript itself does not allow for this (at least if ran in a browser env). It could still be possible if you fully control the user's device, but you'd have to run a workaround for that. I.e. you could store the time of connection and IP and have the workaround application monitor for connections to your site. Then you could have them store the connection and IP too, to allow you to compare these.
Tl;dr: not possible in a browser env.
Edit: It may actually be possible via a concept from the hacking community. See this Question's top answer on the SE's Security forum
Comment: Thank you for the information. Highly appreciated.
Comment: No problem mate, glad I could provide you with some info. I hope the security page of stackexchange has something that can help you. Good luck!


How is the order of execution for HttpModules determined?

Question: Suppose that both FirstModule and SecondModule handle the Application_BeginRequest event. Will it execute in the order defined in the web.config?
<httpModules>
  <add type="MyApp.FirstModule, MyApp" name="FirstModule"/>
  <add type="MyApp.SecondModule, MyApp" name="SecondModule"/>
  <add type="OtherApp.OtherModule, OtherApp" name="OtherModule"/>
</httpModules>

Are there other ways that the order can be specified?
Answer: According to this forum post, HttpModules are executed in the order in which they were registered. This makes sense to me, because otherwise the <clear> and <remove>  directives would also not work as expected, e.g. when used like this:
<httpModules>
   <clear/>
   <add... />
</httpModules>

Comment: Shouldn't depend on it yes, not because it doesn't work but because of design considerations and promoting loose coupling between the modules.  But there are no cases where the ordering of modules will be different to what is in the config file.  Hope this helps.
Comment: Someone in the forum post DOES say that. However there were several people who also said that you shouldn't depend on it.
Comment: check this as well before investing time in this answer. http://stackoverflow.com/a/14974151/398715
Comment: It appears you can order them, however the ordering appears to be locked, and you must unlock the entries to affect the actual ordering.
Comment: @jamiebarrow I would be interested to read more about this. Do you have a url or some sort of resource where you found out about the locking/unlocking.
Comment: Can MS be so lame to not include an explicit ordering mechanism?
Answer: According to the Internet Information Services (IIS) 7.0 Resource Kit book extract from Microsoft Press,

To resolve such relative ordering dependencies, the administrator can control the relative ordering of modules by changing the order in which they are listed in the modules section.
This works because the server uses the order in the modules configuration section to order module execution within each request processing stage. By placing module A before module B in the list, you can allow module A to execute before module B.


Fixing a splash screen that looks like a barcode

Question: My splash screen looks like a bar-code.
I've tried the Ubuntu 12.04 Live CD, and with it I don't get any errors except the screen resolution.  Yet, after installing Ubuntu my splash screen looks like this :

How can I fix this?  (Does it look like a driver problem, or something else?)
Answer: The mystery of the missing boot splash screen:
I installed Ubuntu 12.4 on my HP and had the same issue with my NVidia graphics card  - the graphical boot splash screen in Ubuntu stops working and looks scrambled after the first install or update of GRUB.
I found this solution elsewhere online and it worked so I thought I'd share it.
It is all due to a little variable called $vt_handoff in the /boot/grub/grub.cfg file that incorrectly blacklists my graphics card and decides that I am not allowed to see a graphical boot screen.
Simply edit the grub.cfg file and remove all $vt_handoff references in the code.
 sudo gedit /etc/grub/grub.cfg
The BASH script to fix the issue again and again:
Here's a short bash script to do the job.
Make it executable by using chmod +x and use the script every time after an update or upgrade.
FixBootSplash.sh :
#! /bin/bash
# Fix Ubuntu Plymouth Boot Splash
# if entry exists for $vt_handoff use sed to search and replace
# write to tmp file - move to original

checkVT=$(grep -c "\$vt_handoff" /boot/grub/grub.cfg)

if [ ! "$checkVT" -eq "0" ]
   then
     echo "> Found vt_handoff removing ..."
     sudo sed 's/$vt_handoff//g' /boot/grub/grub.cfg > /tmp/.grub.cfg
     sudo mv /boot/grub/grub.cfg /boot/grub/grub.cfg.backup
     sudo mv /tmp/.grub.cfg /boot/grub/grub.cfg
   fi

echo "> Done"

Answer: If you've installed graphics card driver, that might be causing the problem. In such case, go the link: http://kyleabaker.com/2010/07/11/how-to-fix-your-ubuntu-boot-screen/
Generally, encountering a problem in the splash screen means that there is a problem in the package plymouth. You might want to reinstall the package. Use the following commands:
sudo apt-get install --reinstall plymouth plymouth-label libplymouth2
sudo apt-get install --reinstall plymouth-theme-ubuntu-logo
sudo apt-get install --reinstall plymouth-theme-ubuntu-text

For more help in future, you can visit the following page: https://wiki.ubuntu.com/Bugs/FindRightPackage
Comment: thaks for your reply but its'n succesful i have tried both of them but didn't make any change for my splash screen


Why isn't container filling the whole screen?

Question: I'm trying to set a black background for one of my React Routes.  But when the page is rendered, it seems like the container I set the black background to isn't covering the whole screen.  Even if I set the background in the div in my App.js to black, the container doesn't fully cover the screen.  I included an shortened version of my code below.
foo.js Route
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import { withStyles } from '@material-ui/core/styles';

const StyledContainer = withStyles({
    root: {
        background: 'black',
        width: '100vw',
        height: '100vh'
    }
  })(Container);

export default function Foo(){
    return(

    )
}

App.js
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Foo from './routes/Foo';

function App() {
  return (

      <BrowserRouter>
        <Switch>
          <Route exact to path="/foo">
            <Foo />
          </Route>
        </Switch>
      </BrowserRouter>

  );
}

export default App;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
  document.getElementById('root')
);
reportWebVitals();

Answer: Make sure you have a css file you import on index / App containing your global styling (similar to what you would get by creating a new react app through npx create-react-app app-name.
In there, you need to have the following styles to avoid default margin / borders:
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
};


Javascript: Is there a function version of o.key / o['key']?

Question: Given o = { hey: 'sup' }, is there a vanilla function that is equivalent to o.hey / o['hey']?
My use case:
a = [ 'hey', 'nm' ];
o = { hey: 'sup', nm: 'u?' };

a.map(e => o[e]);

I want to replace that e => o[e] with something like o.get. The use case is rather trivial, but it'd make me feel a little better to use a function rather than create a lambda.
Note: I know I could use Map over Object, but that's another question.
Comment: Did you mean `o.get`?
Comment: `const get = p => o => o[p]; a.map(get(e));`…
Comment: @Bergi, Yes I did, thanks.
Answer: No, there's not. You should get comfortable with the lambda, which is really simple and understandable.
Of course you can write a helper function
function getPropertyIn(o) {
    return p => o[p];
}

and use it like a.map(getPropertyIn(o)) but I would not recommend it for simplicity.


Redirect a specific IP address to a special page of my homepage with .htaccess

Question: How can I use .htaccess to forward a visitor of a specific IP address to a webpage on my server?
This example causes an infinite loop:
RewriteCond %{REMOTE_ADDR} ^123\.\123\.123\.123$
RewriteRule ^(.*)$ /specialpage.php [R,L]

I found this on the web but it just does not work:
SetEnvIf REMOTE_ADDR 184.108.40.206 REDIR="redir"
RewriteCond %{REDIR} redir
RewriteRule ^(.*)$ /specialpage.php

Note: My website consists of .htm, html and .php pages.
Your help would be very much appreciated.
Answer: Add a condition to not rewrite when you're already at specialpage:
RewriteCond %{REMOTE_ADDR} ^123\.\123\.123\.123$
RewriteCond %{REQUEST_URI} !/specialpage.php
RewriteRule ^(.*)$ /specialpage.php [R,L]

Comment: Almost! Unfortunately, the CSS is not loaded anymore now. Any help?
Comment: @jim-knopf I edited this answer to overcome the CSS/JS issue, but it wasn't accepted for some reason. In case others stumble across this thread, the answer should also include the following line (just above the RewriteRule: `RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif|css|js) [NC]`
Answer: Just figured out the solution:
RewriteCond %{REMOTE_ADDR} ^123\.\123\.123\.123$
RewriteCond %{REQUEST_URI} !/specialpage.php
RewriteRule .*\.(htm|html|php)$ /specialpage.php [R,L]

Thank you for your help!


Container vs Host (Native) Performance

Question:
Since containers are lightweight os virtualization, can we get the same performance as native (host)?

What would be the difference in performance?

Any leads are highly appreciated or if you have any analysis reports or any reference with host vs containers performance comparison will help.
IA
Answer: This question has already been answered. While the answer is specifically referring to Docker, it can be generalized to other
OCI compliant Container technologies: they all use the same primitives such as cgroups, Linux namespaces and (mostly) unionfs.
Keep in mind, that (in case of Docker) this only refers to containers running in Linux. If you operate Docker containers on Windows or Mac you have a LInux virtualization layer which causes extra (significant1) performance loss.
Edit: there are other approaches of "containerization" like KVM - as the question is tagged with "Docker" I assume it is specifically asking for the performance impact of docker containers.
Comment: Thanks, apprecite it

Container vs Host (Native) Performance


What command to use to get blocks to appear or be placed/ disappear?

Question: I'm making adventure and just wondering how do get blocks to be placed or gotten rid of with a command (that can be set of by a command block).
Answer: Use this command:
/setblock <x> <y> <z> <blockname> [Damage] {dataTags}

Where "blockname" means the block's name (ex. minecraft:dirt) and x y z signifies the coordinates of the place you want the block to show up (use f3 to find these, and look on the middle left of your screen for the "Block" or "Looking At" section). Example:
/setblock 0 1 0 minecraft:air


C# Equivalent in Java for adding associative arrays to command parameter

Question: I am using bind variables in a merge statement and it contains associative arrays. What would be the equivalent Java code. I tried using PreparedStatement and callable statement but they won't work for arrays.
comm.Parameters.Add(new OracleParameter(":student_id", OracleDbType.Varchar2, arrayCount, studentId, System.Data.ParameterDirection.Input));
comm.Parameters.Add(new OracleParameter(":first_name", OracleDbType.Varchar2, arrayCount, firstName, System.Data.ParameterDirection.Input));
comm.Parameters.Add(new OracleParameter(":last_name", OracleDbType.Varchar2, arrayCount, lastName, System.Data.ParameterDirection.Input));
comm.Parameters.Add(new OracleParameter(":created_by", OracleDbType.Varchar2, arrayCount, createdBy, System.Data.ParameterDirection.Input));
comm.Parameters.Add(new OracleParameter(":modified_by", OracleDbType.Varchar2, arrayCount, modifiedBy, System.Data.ParameterDirection.Input));

if(conn.State != ConnectionState.Open)
    conn.Open();
comm.ArrayBindCount = arrayCount;
comm.BindByName = true;

Here is my merge statement
MERGE INTO STUDENT USING DUAL ON(student_id = :student_id)
WHEN MATCHED THEN
    UPDATE SET modified_by = :modified_by,
               first_name = :first_name,
               last_name = :last_name
WHEN NOT MATCHED THEN
    INSERT (student_id, first_name, last_name, created_by, modified_by)
    VALUES (:student_id, :first_name,:last_name,:created_by,:modified_by)
LOG ERRORS INTO ERR$_STUDENT ('MERGE') REJECT LIMIT UNLIMITED

Sample Java Code
        conn = DriverManager.getConnection(jdbcUrl,connProps);
        conn.setAutoCommit(false);
        stmt = conn.createStatement();
          int arrayCount = 3;
          String[] studentId = new String[arrayCount];
          String[] firstName = new String[arrayCount];
          String[] lastName = new String[arrayCount];
          String[] createdBy = new String[arrayCount];
          String[] modifiedBy = new String[arrayCount];
          for (int i = 0; i < arrayCount; i++)
          {
              studentId[i] = String.valueOf(i + 1);
              firstName[i] = "Alan" + (i + 1);
              lastName[i] = "King" + (i + 1);
              createdBy[i] = "Scott" + (i + 1);
              modifiedBy[i] = "Victor" + (i + 1);
          }
        String sql = GetArrayMergeSQL();
        PreparedStatement mergeStatement = conn.prepareStatement(sql);
        NamedParameterStatement p = new NamedParameterStatement(conn,sql);
        CallableStatement merge = (CallableStatement) conn.createStatement();
        merge.setNString(":student_id", studentId);
        int count = stmt.executeUpdate(sql);
        conn.commit();

Comment: Maybe this post http://stackoverflow.com/questions/8416815/pass-java-array-into-plsql/8417069#8417069 can help
Comment: Look at the oracle jdbc developers guide for how binding works. http://docs.oracle.com/cd/B28359_01/appdev.111/b28765/addfunc.htm#TDPJD213
Comment: Please elaborate on your use of "won't work".  (errors, etc.)
Comment: I cannot use the index as the parameter because the bind variables are not in order and different for update and insert (number of bind variables)
Comment: Ah, I confused the directionality of your question.  You want *Java* code?  If so, please post your (best) attempt at a Java implementation.  That will go a long way.
Answer: I think that you want to execute the same statement with a set of different parameters. In JDBC it is implemented using batching
So your result code will look like this:
Connection conn = DriverManager.getConnection(jdbcUrl, connProps);
conn.setAutoCommit(false);
String sql = GetArrayMergeSQL();
PreparedStatement mergeStatement = conn.prepareStatement(sql);
int arrayCount = 3;
for (int i = 0; i < arrayCount; i++)
{
    mergeStatement.setString(1, "Victor" + (i + 1));
    mergeStatement.setString(2, "Alan" + (i + 1));
    mergeStatement.setString(3, "King" + (i + 1));
    mergeStatement.setInt(4, i + 1);
    mergeStatement.setString(5, "Alan" + (i + 1));
    mergeStatement.setString(6, "King" + (i + 1));
    mergeStatement.setString(7, "Scott" + (i + 1));
    mergeStatement.setString(8, "Victor" + (i + 1));
    mergeStatement.addBatch();
}
int[] count = mergeStatement.executeBatch();
conn.commit();

Also JDBC does not support named parameters - you have to replace them with ? marks and reference them by position:
 MERGE INTO STUDENT USING DUAL ON(student_id = :student_id)
 WHEN MATCHED THEN
    UPDATE SET  modified_by = ? /*:modified_by*/,
                first_name = ? /*:first_name*/,
                last_name = ? /*:last_name*/
 WHEN NOT MATCHED THEN
    INSERT (student_id, first_name, last_name, created_by, modified_by)
    VALUES (? /*:student_id*/, ? /*:first_name*?, ? /*:last_name*/,? /*:created_by*/, ? /*:modified_by*/)
 LOG ERRORS INTO ERR$_STUDENT ('MERGE') REJECT LIMIT UNLIMITED


Solr Export Using Streaming Expressions not working when query is having special characters like comma

Question: I am running the following streaming expression
curl --data-urlencode 'expr=search(collection1, q="(text:("apple inc,ltd"))",
                                   fl="id",
                                   sort="id asc",
                                   qt="/export")' http://localhost:8983/solr/collection1/stream

above query is throwing the following error
"EXCEPTION":"invalid expression search(collection1,q=\"\"(text: (\"apple inc\",ltd\"))\",fl=\"id\",sort=\"id asc\",qt=\"/export\") - unknown operands found"

It is automatically splitting my query on comma. How can i resolve this?
Comment: Are you sure that it isn't the `"` inside the quotes for the `q` parameter that's fubaring the parsing? Try escaping them with \.
Comment: @MatsLindh: Thank you. Yes, that is what causing the issue. Is there a way to tell curl to do this instead of doing this manually?
Comment: CURL can't automagically know what you want escaped or not, so no, there is no way to let curl do that for you.
Answer: If you don't escape the quotes inside the quoted string, Solr will think that you're ending the parameter right there.
Use \" to escape the quotes:
expr=search(collection1, q="(text:(\"apple inc,ltd\"))"


TinyMCE Editor: A potentially dangerous Request.Form value was detected from the client

Question: I have aspx in that I am calling a ascx user control in that i am using tinymce editor. When I am trying to save data i am getting the error..
A potentially dangerous Request.Form value was detected from the client (UserControl1$TextBox1="fghfghj

I already check A potentially dangerous Request.Form value was detected from the client
I tried:
web.config I set
<pages validateRequest="false">
<httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters=""/>
<compilation debug="true" targetFramework="4.0">
<@page validateRequest="false">
Server.HtmlEncode(TextBox1.Text)
encoding: "xml" // This is solving the prob. but Text is converting in HTML tag I don't want that

Please someone help me...
Answer: You can also try adding the encoding attribute : encoding: 'xml'

You can check this link, it says :

encoding: "xml"
– solves  "A potentially dangerous Request.Form value was detected",
  which won't allow you to submit the Web Form
Answer: Add this to httpRuntime
< httpRuntime requestValidationMode="2.0"  />

Comment: HttpRuntimeSection.RequestValidation looks like a backwards compatibility feature to me. Using [AllowHtml] on individual fields seems better
Answer: Any reason why you can't encode the string and store in your database and then just before displaying the encoded string you can simply decode it ?
Comment: Why are you using xml encoding can you not just use Server.HtmlEncode(TextBox1.Text) not in web.config but in c# code behind where you pull the value just before saving.
Comment: for the first time I am able to save the data when i am using encoding: "xml", but again when i am unloading the data and trying to save same error is coming, I am storing the textbox text in a viewstate and assigning to hashtable also
Comment: if i am not using the xml encoding the error is coming, and when i am clicking on btn click debug pointer is not going in that before that only error is showing
Comment: will be really useful if you could post some more of your code and the outputs you are seeing.