text:
Q: React-Native Android: Resizing native UI Component causes black out I have a very strange issue I'm struggling with regarding using GLSurfaceView with react native on Android.
I've created a custom OpenGL renderer that I want to use as a component in a larger react native view. The problem is that when I size the component on the JS side to the size I want the rest of the screen goes black.

This is the React Native code that's creating that view:
    public render() {
       return (
            <View style={{ backgroundColor: '#ffffff' }}>
                <Text>Hello World!</Text>
                <ImageBlendView style={{ height: 50 }} boxColour="#f442df" />
            </View>
        );
    }

ImageBlendView is a react-native UI component I made following the instructions on the RN website here, this is what's creating the red with the purple rectangle in it. It is a just a pretty basic Opengl renderer that is drawing a rectangle with the color passed in from JS and a red clear color. I added a text field above it and sized the component to 50-height.
I can't figure out why the ImageBlendView component is surrounded by black.
The clear color is red so I know its not my renderer clearing pixels it shouldn't be. However, it does seem to be related to my renderer class because when I comment out the line in the GLSurfaceView class where I set it as the renderer the normal white background comes back and the text above the component is visible.
// setRenderer(new OpenGLRenderer(_context, colour));

The custom UI component follows the same structure as in the tutorial but I'll walk through it to be thorough.
The ImageBlendView is added to a package and bundled in the view managers list:
public class OTSNativePackage implements ReactPackage {

    @Nonnull
    @Override
    public List<NativeModule> createNativeModules(@Nonnull ReactApplicationContext reactContext) {
        List<NativeModule> nativeModules = new ArrayList<>();
        return nativeModules;
    }

    @Nonnull
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Arrays.<ViewManager>asList(new ImageBlendView());
    }
}

ImageBlendView.java then extends the SimpleViewManager which creates an instance of OpenGLView which extends GLSurfaceView
public class ImageBlendView extends SimpleViewManager<OpenGLView> {

    public static final String REACT_CLASS = "ImageBlendView";
    private static OpenGLView _openGLView;

    @Nonnull
    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Nonnull
    @Override
    protected OpenGLView createViewInstance(@Nonnull ThemedReactContext reactContext) {
        _openGLView = new OpenGLView(reactContext);
        return _openGLView;
    }

    @ReactProp(name = "boxColour")
    public void setBoxColour(OpenGLView view, String color) {
        _openGLView.init(color);
    }
}

OpenGLView.java
public class OpenGLView extends GLSurfaceView {
    private Context _context;
    public OpenGLView(Context context) {
        super(context);
        _context = context;
    }

    public OpenGLView(Context context, AttributeSet attrs) {
        super(context, attrs);
        _context = context;
    }

    public void init(String colour){
        setEGLContextClientVersion(2);
        setPreserveEGLContextOnPause(true);

        // If I disable the following line the black goes away
        setRenderer(new OpenGLRenderer(_context, colour));
    }
}

Note that it is here in the above class where I can disable the setRenderer line and the black goes away.
My Renderer is in OpenGLRenderer.java
public class OpenGLRenderer implements GLSurfaceView.Renderer {
    private Context _context;
    private FloatBuffer vertexBuffer;
    private ShortBuffer drawListBuffer;
    private int positionHandle, program, colorHandle;
    static final int COORDS_PER_VERTEX = 3;

    static float squareCoords[] = {
        -0.5f,  0.5f, 0.0f,   // top left
        -0.5f, -0.5f, 0.0f,   // bottom left
         0.5f, -0.5f, 0.0f,   // bottom right
         0.5f,  0.5f, 0.0f }; // top right

    private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices

    float color[] = {0.5f, 0.5f, 0.55f, 1.0f};
    private int vertexCount;
    private int vertexStride; // 4 bytes per vertex

    public OpenGLRenderer(Context context, String colorStr){
        super();
        _context = context;
        color = new float[]{(float)Integer.valueOf( colorStr.substring( 1, 3 ), 16 ) / 256.0f,
                        (float)Integer.valueOf( colorStr.substring( 3, 5 ), 16 ) / 256.0f,
                        (float)Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) / 256.0f, 1.0f};
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        GLES20.glClearColor(1f,0f,0f,1f);

        ByteBuffer bb = ByteBuffer.allocateDirect(squareCoords.length * 4);
        bb.order(ByteOrder.nativeOrder());
        vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(squareCoords);
        vertexBuffer.position(0);

        // initialize byte buffer for the draw list
        ByteBuffer dlb = ByteBuffer.allocateDirect(drawOrder.length * 2);
        dlb.order(ByteOrder.nativeOrder());
        drawListBuffer = dlb.asShortBuffer();
        drawListBuffer.put(drawOrder);
        drawListBuffer.position(0);

        vertexCount = squareCoords.length / COORDS_PER_VERTEX;
        vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex

        GLES20.glEnable(GLES20.GL_SCISSOR_TEST);

        compileShaders();
        sendData();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
        GLES20.glScissor(0,0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        GLES20.glEnableVertexAttribArray(positionHandle);

        GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length, GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

        GLES20.glDisableVertexAttribArray(positionHandle);
    }

    private void sendData(){
        positionHandle = GLES20.glGetAttribLocation(program, "position");
        GLES20.glEnableVertexAttribArray(positionHandle);

        GLES20.glVertexAttribPointer(positionHandle, COORDS_PER_VERTEX,
                             GLES20.GL_FLOAT, false,
                             vertexStride, vertexBuffer);

        colorHandle = GLES20.glGetUniformLocation(program, "vColor");

        GLES20.glUniform4fv(colorHandle, 1, color, 0);
    }

    private void compileShaders() {

        int vertexShader = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
        GLES20.glShaderSource(vertexShader, getShaderSource(R.raw.vertex_shader));

        int fragmentShader = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);
        GLES20.glShaderSource(fragmentShader, getShaderSource(R.raw.fragment_shader));

        GLES20.glCompileShader(vertexShader);
        GLES20.glCompileShader(fragmentShader);

        program = GLES20.glCreateProgram();
        GLES20.glAttachShader(program, vertexShader);
        GLES20.glAttachShader(program, fragmentShader);

        GLES20.glLinkProgram(program);
        GLES20.glUseProgram(program);
    }

    private String getShaderSource(int input){
        StringBuilder total = new StringBuilder();
        try{
            InputStream stream =
                _context.getResources().openRawResource(input);

            BufferedReader r = new BufferedReader(new InputStreamReader(stream));
            total = new StringBuilder();
            for (String line; (line = r.readLine()) != null; ) {
                total.append(line).append('\n');
            }
        } catch (IOException e){
            System.out.println(e.getMessage());
        }

        return total.toString();
    }
}

The latest thing I tried was the call to GLES20.glScissor(0,0, width, height); in the onSurfaceChanged method. I was hoping by scissoring to just the size and height of the component it wouldn't affect the rest of the pixels but its becoming pretty clear that its not an issue with the OpenGL but the setup.

A: Finally figured out a solution. I simply changed the JS code to this:
    public render() {
        console.log('***', ImageBlend);
        return (
            <View style={{ backgroundColor: '#ffffff' }}>
                <Text>Hello Nick!</Text>
                <View style={{ height: 50, overflow: 'hidden' }}>
                    <ImageBlendView
                        style={{ height: 50 }}
                        boxColour="#f442df"
                    />
                </View>
            </View>
        );
    }


text:
Q: Select float from MySQL with correct precision Common trouble that I've searched and read about and still stuck.
I have a table with trades, where trade price is declared as float. I cant' use decimal because different stocks have different precision in their price.
If a look at the table via phpMyAdmin, all numbers look correct - as they were inserted, as you can see on screenshot below, price (p) is 0.709 which is correct.

But when I select that trade from table using regular zend framework, I get price which is 0.70899999141693
How can I make a select which works same as MyAdmin select does? And receive number with correct precision? If myAdmin does the job, it can be possible in zend also, am I right?
EDIT: I can't use ROUND and I cant use DECIMAL because I don't know correct precision.
e.g. price of Apple has 2 decimals in precision, but price of VTB Bank has 6 decimal in precision
EDIT2: Here are more examples on same select within myAdmin and zend.
Trade 8838397 was made by price 0.01156. I've inserted it in database and that's what I get in myAdmin:

If I select it with php, I get this:

I assume, myAdmin somehow guesses precision and does it really good. How???

A: Quote "I have a table with trades, where trade price is declared as float. I cant' use decimal because different stocks have different precision in their price."
I daresay this is nonsense. If you want precise data then use a precise type. You would only use float if the values exceeded the range DECIMAL offers, which is not the case here. DECIMAL(65,30) handles values with up to 30 digital places. That should be enough for all your values, I guess.
I suppose you are mixing internal storage with data display here. If the number of decimal places is an information needed, then store this information:

trade_id  office  price  precision
12345678  123456  0,709  4

A query:
select trade_id, office, round(price, precision) as price
from trades;

Result:

trade_id  office  price
12345678  123456  0,7090

EDIT: As to "MyAdmin somehow already solved it, I just can't undertand how":
It doesn't. I doubt that it will display 0.120 for an entered 0.120 and 0.12000 for an entered 0.12000. The dbms will store the same float value for both and phpMyAdmin has no way of telling they are to be treated differently. The only thing that phpMyAdmin probably does is to round to a maximum number of decimal places, say 6. select round( 0.70899999141693 , 6) results in 0.709.

A: You can use round function:
select round(p, 3) as p from table_name;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Remove "Powered by Jekyll with Chirpy theme." I want to remove the "Powered by Jekyll with Chirpy theme." appearing at the footer of every page with other customized messages.
It works when I run bundle exec jekyll s locally and I remove the following from the file under C:/Ruby31-x64/lib/ruby/gems/3.1.0/gems/jekyll-theme-chirpy-5.1.0/\_includes/footer.html.

        {% capture _platform %}
          Jekyll
        {% endcapture %}

        {% capture _theme %}
          Chirpy
        {% endcapture %}

        {{ site.data.locales[lang].meta
          | default: 'Powered by :PLATFORM with :THEME theme.'
          | replace: ':PLATFORM', _platform | replace: ':THEME', _theme
        }}

However, it still shows on my Github page.
PS: AFAIK we can remove the "Powered by .." under the license.

A: Add a changed footer file _includes/footer.html to your repository to overwrite the original theme's footer file. This will be used by the GitHub pages deployment.
The instructions on docs.github.com on how to change the layout  explain it. The footer adjustment works the same.
Regarding the license, the theme's MIT license contains:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

I guess it's not ok to remove the copyright completely. You can remove it from the footer but you should keep it somewhere.

A: The meta information is coming from the files under the (language) locales. For my site I have edited only the en.yml file see the attached image. You can modify the whole of the files under locale. The param value is coming from the _config.yml file.
#meta: Powered by :PLATFORM and with :THEME theme.
meta: Powered by Open Source CMS.
en.yml


text:
Q: Why use cabal instead of make As far as I understand cabal is the preferred way of building Haskell projects. Coming from a unix C/C++ background, I am used to make.
So what does cabal offer that I will not get from make?

A: Cabal will do more than just build your project, it also can manage your dependencies in a sandbox environment (as of 1.18), upload your package to hackage, and build libraries and executables in a lot less setup than it would take in make.  It's more similar to pip/distutils/virtualenv rather than just a build system.


text:
Q: Find the Maclaurin seris for $f(x)= 1/(1+4/5x)^3$ I am having a few problems with this as the all of $(1+4/5x)$ is raised to the power of $3$ rather than just the $x$ term.

A: Let's write:
$$\frac{1}{\left(1+\frac{4}{5x}\right)^3}=\left(\frac{5x}{5x+4}\right)^3=125x^3\frac{1}{(5x+4)^3}$$
Now notice that we have:
$$\frac{1}{(5x+4)^3}=\frac{1}{50}\frac{d^2}{dx^2}\frac{1}{5x+4}$$
I think you can take it from here.


text:
Q: Flutter Android giving problem after update Flutter is giving me a problem post the Flutter and Android update.
I had updated Flutter to Flutter 2 and also updated Android to 3.4. Now Flutter refuses to run the app in the Emulator. It throws a messy error message. I also tried migrating to AndroidX, but it's still not working. Then tried giving the build with old Android Studio but unfortunately, that too is not working. I am not able to give build for both Android and iOS, though Flutter Doctor passes all the test correctly. Error messages for Android and iOS is as below.
For Android:
Launching lib/main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running Gradle task 'assembleDebug'...
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:preDebugBuild'.

Android dependency 'androidx.core:core' has different version for the compile (1.0.0) and runtime (1.0.1) classpath. You should manually set the same version via DependencyResolution

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 3s

The Gradle failure may have been because of AndroidX incompatibilities in this Flutter app.
See https://flutter.dev/docs/development/packages-and-plugins/androidx-compatibility for more information on the problem and how to fix it.

Finished with error: Gradle task assembleDebug failed with exit code 1
For iOS
Launching lib/main.dart on iPhone Xʀ in debug mode...
Running Xcode build...
Xcode build done.                                            9.0s
Failed to build iOS app
Could not build the application for the simulator.
Error output from Xcode build:
Error launching application on iPhone Xʀ.
↳
    ** BUILD FAILED **
Xcode's output:
↳
    === BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Debug ===
    The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test your code with "Use of deprecated Swift 3 @objc inference" logging enabled, and then disable inference by changing the "Swift 3 @objc Inference" build setting to "Default" for the "Runner" target.
    === BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Debug ===
    /Users/Downloads/GoogleService-Info.plist:0: error: reading data: The file "GoogleService-Info.plist" couldn't be opened because there is no such file.
How do I make this run in the Android and iOS emulators?


text:
Q: What corresponds to the Unity 'registration name' in the unity configuration section? When registering and resolving types in a Unity Container using code you can use 'Registration Names' to disambiguate your references that derive from an interface or base class hierarchy.
The 'registration name' text would be provided as a parameter to the register and resolve methods:
myContainer.RegisterType<IMyService, CustomerService>("Customers");

and
MyServiceBase result = myContainer.Resolve<MyServiceBase>("Customers");

However when I register types in the configuration files I do not see where the 'registration name' can be assigned
I register an Interface:
<typeAlias alias="IEnlistmentNotification" type="System.Transactions.IEnlistmentNotification, System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

Then two types that I happen to know implement that interface:
<typeAlias alias="PlaylistManager" type="Sample.Dailies.Grid.Workers.PlaylistManager, Sample.Dailies.Grid.Workers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />

<typeAlias alias="FlexAleManager" type="Sample.Dailies.Grid.Workers.FlexAleManager, Sample.Dailies.Grid.Workers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />

Then I provide mappings between the interface and the two types:
<type type="IEnlistmentNotification" mapTo="FlexAleManager"><lifetime type="singleton"/></type>

<type type="IEnlistmentNotification" mapTo="PlaylistManager"><lifetime type="singleton"/></type>

That seems to correspond to this code:
myContainer.RegisterType<IEnlistmentNotification, FlexAleManager>();
myContainer.RegisterType<IEnlistmentNotification, PlaylistManager>();

but clearly what I need is a disambiguating config entry that corresponds to this code:
myContainer.RegisterType<IEnlistmentNotification, FlexAleManager>("Flex");
myContainer.RegisterType<IEnlistmentNotification, PlaylistManager>("Play");

Then when I get into my code I could do this:
IEnlistmentNotification flex = myContainer.Resolve<IEnlistmentNotification>("Flex");
IEnlistmentNotification play = myContainer.Resolve<IEnlistmentNotification>("Play");

See what I mean?
Thanks,
Kimball

A: to answer my own question, I found this scrap on Codeplex/Unity home:
<type type="IFoo" mapTo="ServerFoo" name="server" />
<type type="IFoo" mapTo="ClientFoo" name="client">
    <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,Microsoft.Practices.Unity.Configuration">
      <constructor>
         <param name="server" parameterType="IFoo">
            <dependency name="server" />
         </param>
      </constructor>
     </typeConfig></type>

Notice that the type element has an additional field: 'name' that I was unaware of. This provides the 'registration name' value I was looking for.
Also  the param element also has a subelement named dependency with a name attribute that performs the same function.
So... Thanks to codeplex!
Kimball


text:
Q: SpecFlow, Selenium, NUnit, Parallelization: ChromeDriver Windows from two different NUnit Tests, keep having unexplained relation I have a selenium-webdriver-di.cs file like this:
using TechTalk.SpecFlow;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium;
using BoDi;
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

public class WebDriverHooks
{
    private readonly IObjectContainer container;
    private static Dictionary<string, ChromeDriver> drivers = new Dictionary<string, ChromeDriver>();
    private ScenarioContext _scenarioContext;
    private FeatureContext _featureContext;

    public WebDriverHooks(IObjectContainer container, ScenarioContext scenarioContext, FeatureContext featureContext)
    {
        this.container = container;
        _scenarioContext = scenarioContext;
        _featureContext = featureContext;
    }
    [BeforeFeature]
    public static void CreateWebDriver(FeatureContext featureContext)
    {
        Console.WriteLine("BeforeFeature");
        var chromeOptions = new ChromeOptions();
        chromeOptions.AddArguments("--window-size=1920,1080");
        drivers[featureContext.FeatureInfo.Title] = new ChromeDriver(chromeOptions);
    }
    [BeforeScenario]
    public void InjectWebDriver(FeatureContext featureContext)
    {
        if (!featureContext.ContainsKey("driver"))
        {
            featureContext.Add("driver", drivers[featureContext.FeatureInfo.Title]);
        }
    }
    [AfterFeature]
    public static void DeleteWebDriver(FeatureContext featureContext)
    {
        ((IWebDriver)featureContext["driver"]).Close();
        ((IWebDriver)featureContext["driver"]).Quit();
    }

And then in each of my .cs files that contains the step definitions, I have constructors like this:
using System;
using TechTalk.SpecFlow;
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections.Generic;
using PfizerWorld2019.CommunityCreationTestAutomation.SeleniumUtils;
using System.Threading;
using System.IO;

namespace PfizerWorld2019
{
    [Binding]
    public class SharePointListAssets
    {
        private readonly IWebDriver driver;
        public SharePointListAssets(FeatureContext featureContext)
        {
            this.driver = (IWebDriver)featureContext["driver"];
        }
    }
}

And then I'm using the driver variable in all the functions of the class. Lastly I have a file that I called Assembly.cs, where I put this for NUnit fixture level parallelization:
using NUnit.Framework;
[assembly: Parallelizable(ParallelScope.Fixtures)]

Which in SpecFlow's terms means parallelization on the Feature level(1 .feature file = 1 Nunit Test = 1 Nunit Fixture)
If I run my tests serially, they work fine.
But if I run 2 tests in parallel, any two tests, always something funny happens. For example: the first Chromedriver window tries to click an element and it clicks it if and only when the second Chromedriver window (that is running a different test) renders the exact same part of the website. But it sends the click to the correct window (the first one).
I have tried:

*

*To use the IObjectContainer interface and then do containers[featureContext.FeatureInfo.Title].RegisterInstanceAs<IWebDriver>(drivers[featureContext.FeatureInfo.Title]) in the InjectWebDriver function

*To use Thread.CurrentThread.ToString() instead of featureContext.FeatureInfo.Title for indexing

*To do featureContext.Add(featureContext.FeatureInfo.Title + "driver", new ChromeDriver(chromeOptions) instead of drivers[featureContext.FeatureInfo.Title] = new ChromeDriver(chromeOptions); in the CreateWebDriver function.

I just do not understand what allows this "sharing". Since FeatureContext is used for everything related to driver spawning and destruction, how can two chromedrivers talk with each other?
Update: I tried the driver initialization & sharing like this:
[BeforeFeature]
public static void CreateWebDriver(FeatureContext featureContext)
{
    var chromeOptions = new ChromeOptions();
    chromeOptions.AddArguments("--window-size=1920,1080");
    chromeOptions.AddArguments("--user-data-dir=C:/ChromeProfiles/Profile" + uniqueIndex);
    WebdriverSafeSharing.setWebDriver(TestContext.CurrentContext.WorkerId, new ChromeDriver(chromeOptions));
}

and I made a webdriver-safe-sharing.cs file like this:
class WebdriverSafeSharing
{
    private static Dictionary<string, IWebDriver> webdrivers = new Dictionary<string, IWebDriver>();
    public static void setWebDriver(string driver_identification, IWebDriver driver)
    {
        webdrivers[driver_identification] = driver;
    }
    public static IWebDriver getWebDriver(string driver_identification)
    {
        return webdrivers[driver_identification];
    }
}

and then in each step definition function, I'm just calling WebdriverSafeSharing.getWebDriver(TestContext.CurrentContext.WorkerId) without any involvement of the FeatureContext. And I'm still getting the same issue. Notice how I'm doing chromeOptions.AddArguments("--user-data-dir=C:/ChromeProfiles/Profile" + uniqueIndex); because I'm also starting to not trust that chromedriver itself is thread safe. But even that did not help.
Update 2: It tried an even more paranoid webdriver-safe-sharing.cs class:
class WebdriverSafeSharing
{
    private static readonly Dictionary<string, ThreadLocal<IWebDriver>> webdrivers = new Dictionary<string, ThreadLocal<IWebDriver>>();
    private static int port = 7000;
    public static void setWebDriver(string driver_identification)
    {
        lock (webdrivers)
        {
            ChromeDriverService service = ChromeDriverService.CreateDefaultService();
            service.Port = port;
            var chromeOptions = new ChromeOptions();
            chromeOptions.AddArguments("--window-size=1920,1080");
            ThreadLocal<IWebDriver> driver =
            new ThreadLocal<IWebDriver>(() =>
            {
                return new ChromeDriver(service, chromeOptions);
            });
            webdrivers[driver_identification] = driver;
            port += 1;
            Thread.Sleep(1000);
        }
    }
    public static IWebDriver getWebDriver(string driver_identification)
    {
        return webdrivers[driver_identification].Value;
    }

It has a lock, a Threadlocal and unique port. It still does not work. Exact same issues.
Update 3: If I run two separate Visual Studio instances and I run 1 test for each, it works. Or by having two identical projects run side by side

and then selecting to run the tests in parallel:

A: The problem appears to be that you are stashing the IWebDriver object in the FeatureContext. The FeatureContext is created and reused for each scenario in a feature. While on the surface it appears safe for running tests in parallel using NUnit (which does not run scenarios in the same feature in parallel), my hunch is that this is not as safe as you think.
Instead, initialize and destroy the IWebDriver object with each scenario, rather than feature. The ScenarioContext should be thread safe, since it is created once for each scenario, and is only used for one scenario. I would recommend using dependency injection instead:
[Binding]
public class WebDriverHooks
{
    private readonly IObjectContainer container;

    public WebDriverHooks(IObjectContainer container)
    {
        this.container = container;
    }

    [BeforeScenario]
    public void CreateWebDriver()
    {
        var driver = // Initialize your web driver here

        container.RegisterInstanceAs<IWebDriver>(driver);
    }

    [AfterScenario]
    public void DestroyWebDriver()
    {
        var driver = container.Resolve<IWebDriver>();

        // Take screenshot if you want...

        // Dispose of the web driver
        driver.Dispose();
    }
}

Then add a constructor argument to your step definition classes to pass the IWebDriver:
[Binding]
public class FooSteps
{
    private readonly IWebDriver driver;

    public FooSteps(IWebDriver driver)
    {
        this.driver = driver;
    }

    // step definitions...
}

A: The reason was that all the selenium API actions were wrapped in static methods written by me. It was a class in a file that I wrote many weeks ago for code re-usability. However not being used into working with parallel programming in C#, I was honestly not aware anymore that these methods were declared static. I am now running 20 parallel workers on Selenium Grid.
However I'm placing here some important notes to be aware of, if one faces parallelization issues with NUnit, SpecFlow and Selenium

*

*The initialization of the WebDriver must be done in the [BeforeFeauture]-bound method if the goal is feature-level and not scenario-level parallelization.

*The initialization of the WebDriver must be thread safe. What I did is that I used a static Dictionary that is indexed by the FeatureContext.FeatureInfo.Title that contains the WebDrivers

*chromedriver is thread safe. There is no need unique data-dir folders or unique ports or unique chromedriver file names. The --headless  and --no-sandbox arguments that one might be interested in have not caused me any issues with parallelization (either with Selenium Grid or simple single multi-core machine parallelization). Basically don't blame the chromedriver.

*For injecting the webdriver, do use the IObjectContainer interface in the [BeforeScenario]-bound method. It is great and safe.

*Dispose the driver in the [AfterFeature]-bound method with driver.Dispose() so that you don't have zombie processes. This helped me with Selenium Grid, because when I was using driver.Close() and driver.Quit(), the nodes would not kill the processes after the latter were done.

*For NUnit with [assembly: Parallelizable(ParallelScope.Fixtures)] enabled, all the scenarios within a .feature file run within the same FeatureContext and therefore the scenarios are FeatureContext-safe. This means that you can trust the FeatureContext for sharing data between scenarios within the same .feature file.

*The [BeforeFeature] hook is being called only once per .feature file (as one would logically assume). So if you have x .feature files, the hook will be called x times during a test run.

*As the Specflow Documentation says, for feature-level parallelization either NUnit or xUnit should be used as the test framework. However the NUnit has the benefit that it provides out of the box ordering for the tests, by alphabetical sort order. This is particularly useful if you want to have two scenarios run in sequence within the same feature file. i.e. putting a number in front of each scenario title will ensure their order during execution. xUnit does not support this natively and it looked like a difficult goal to achieve from searching around.

*Specflow is more "friendly" in terms of parallelization, for scenario-level parallelization. This is why the Specflow+ Runner test framework by SpecFlow runs scenario levels in parallel. it looks like the whole philosophy of SpecFlow (I wouldn't say BDD yet) is to have independent scenarios. This doesn't mean of course that you cannot have very nice feature-level parallelization by using the other test frameworks. Just putting it out there as a heads up for someone reading this while drafting a strategy for writing feature files.


text:
Q: Would Cython-like "Cypescript" be a feasible idea? Cython is a superset of Python that can be complied into C modules that can be imported and used normally in Python code. This can be used to speed up parts of a Python program. In a recent project, I used this to make a heavy part of the code run 90x faster. A downside of Cython is that to get significant performance benefits, one needs to add type annotations to Python code with a special syntax, which may decrease readability.
Would a similar system be feasible for Javascript or Typescript to speed up NodeJS backends or Electron applications? Typescript already has syntax for typing, so ideally "Cypescript" wouldn't need any additional syntax.
I found some projects that transpile JS/TS to C or WebAssembly, but these are just one-directional - AFAIK you can't conveniently use the compiled modules from normal TS code. In the system I'm imagining, one could just save a computationally expensive part of their normal NodeJS or Electron project in a file with a distinct file extension, say .cts, and then import code normally from this file in any other JS or TS file. Surely some language features would need to be restricted in .cts files, but making an editor extension to warn about these restrictions shouldn't be too hard.
Is there some technical hurdle here that I'm not seeing?

A:
A downside of Cython is that to get significant performance benefits, one needs to add type annotations to Python code with a special syntax, which may decrease readability.

Note that Python 3+ does have type annotations. I believe the reason Cython doesn't use that syntax is that it pre-dates Python 3. It could be changed, however, to use it, but that wouldn't help much, as I will explain later.

Would a similar system be feasible for Javascript or Typescript to speed up NodeJS backends or Electron applications?

Yes.

Typescript already has syntax for typing, so ideally "Cypescript" wouldn't need any additional syntax.

As I explained above, Python also has syntax for type annotations.
However, Cython distinguishes between Python code and "C" code, between Python types and "C" types. In other words, Cython is a union of two separate sub-languages that share a common syntax: a language for writing Python, and a Python-syntax-influenced language for writing high-level portable C-semantics.
You would still need those two sub-languages in Cypescript.

Is there some technical hurdle here that I'm not seeing?

No. Someone just needs to do it.
Note that there is a social hurdle, though: CPython generates CPython extensions. It generally wouldn't work or at least not that well for users using PyPy, IronPython, Jython, Pyston, Pynie, or any other Python implementation. However, it is usually possible to convince a user to use a specific implementation, plus, the vast majority are using CPython anyway.
The same is not true for Typescript / ECMAScript. There is not a single ECMAScript implementation that dominates the market like CPython does, and users usually don't get a choice of their implementation. If I am using Edge, I am stuck with Chakra, if I am using Firefox, I am stuck with SpiderMonkey, if I am using Safari, I am stuck with Nitro. So, which one of those would Cypescript generate extensions for?
Personally, I don't buy this approach. If CPython is too slow running Python, the solution is not to make it easier to write C code, the solution is to make CPython faster so you don't have to.
The CPython developers ignore lots of research into building high-performance dynamic language implementations gathered over the last 60 years, sometimes with good reason, sometimes without, sometimes simply because of a lack of resources. (Compare the number of developers Oracle JDK or IBM J9 has with the number of CPython developers, for example.)
The Oracle HotSpot JVM is based on the Animorphic Smalltalk VM (just like V8, BTW), Azul Zing is based on HotSpot, IBM J9 is based on IBM's Smalltalk VM, and none of them actually make much use of the static type information in the bytecode, most of their optimizations are dynamic. There is little technical reason why a Python or ECMAScript execution engine shouldn't be at least as performant as HotSpot, Zing, or J9.


text:
Q: Use custom Environment in Symfony Command I try to run a command with some custom parameters i put in my config_staging.yml file.
Here is the parameter i would like to get (located in my config_staging)
parameters:
  bdd_name: 'ISB_bdd'

The same parameter is also in the config_dev (It's the db name, it changed for every env)
parameters:
  bdd_name: 'DEV_ISB_bdd'

And that's the code in my command file:
<?php
namespace SafeEngine\ParserFluxBundle\Command;

use [..]

class GetFluxToProcessCommand extends ContainerAwareCommand
{
  protected function configure()
  {
      $this
          ->setName('parser:GetFluxToProcess')
       [...]
        );
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $tableTransactions = $this->getContainer()->getParameter('ISB_bdd');
    var_dump($tableTransactions):

[...]

Then i run
php app/console parser:GetFluxToProcess -e staging

But the var_dump returns DEV_ISB_bdd, the paramater in the dev config file, not the one in the staging config. It looks like Symfony don't switch environment and keep the default one,
Any idea?

A: You need to make your cache and logs directories writable. To do so read the documentation: http://symfony.com/doc/current/book/installation.html#configuration-and-setup. For example for systems with ACL support you can use:
HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs

After that clear your cache and you will have updated configuration file for your staging environment.


text:
Q: Change tint color for sharing via Notes app in iOS On iOS 11, if user shares a link via Notes app from my app, the Cancel/Done buttons are white (on white background). How to change those buttons tint?
I am sharing a link like this:
    let activityVC = UIActivityViewController(activityItems: [myShareUrl], applicationActivities: nil)
    presentViewController(activityVC, animated: true, completion: nil)

Here's an example how currently it looks like:

I am also adjust NavTint color in AppDelegate like this:
    UINavigationBar.appearance().shadowImage  = UIImage()
    UINavigationBar.appearance().barTintColor = .clearColor()
    UINavigationBar.appearance().tintColor    = .whiteColor()
    UINavigationBar.appearance().setBackgroundImage(
        UIImage(), forBarMetrics: UIBarMetrics.Default
    )

EDIT
I've tried setting tint color like this, before presenting UIActivityViewController:
UIApplication.sharedApplication().keyWindow?.tintColor = UIColor.appRed()

And while it worked on iOS9, does not work on iOS11.

A: Set this before you show
UIView.appearance().tintColor

Then reset after dismissal to restore - ie within activityViewController.completionWithItemsHandler


text:
Q: Toggle music in unity Currently I have my toggle to On Value Change make AudioSource.enabled, which does turn the music off.
However when I die in the game the level gets reloaded causing the toggle to go back to its default state and then i am unable to turn the music back on.
So what is the best way to make a music toggle and have the state of the toggle be remembered on load?

A: Another solution would be a singleton music manager game object that is created only once and is persistent between scenes, meaning that it will not be destroyed when you reload a scene or load a different scene.
You can read more about Singleton patterns here: http://unitypatterns.com/singletons/

A: You can save persistent data across scenes using PlayerPrefs. Just store there the audio status and be sure to check if it's enabled when loading a new scene (for example inside Awake method of a MonoBehaviour attached on the same AudioSource's GameObject).
Side note
Depending on the specific situations, turn off globally the volume could be easier using AudioListener.volume rather than modifying all AudioSources.


text:
Q: How to live-check class removal I have a function which removes CSS classes from a specific block element. How would I do a live check that the block no longer has any CSS classes before I add another class to it?
This is my code:
$('#back_button_recipes').on('DOMSubtreeModified',function(){
    if ($(this).attr('class').length <= 0){
        $(this).addClass('main_menu')
    }
});

A: the call to $(this).attr('class') does not return an array, so checking for length won't work. If there's not any classes, attr returns undefined, so just check for falsy:
var classes = $(this).attr('class');
if (!classes) {
  ...
}

From the jQuery online attr documentation

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.

A: I'd do this checkup in JavaScript:
$('#back_button_recipes').on('DOMSubtreeModified',function(){
    if (!this.className.length > 0){
        this.className += 'main_menu';
    }
});

JSFiddle
http://jsfiddle.net/2pW3v/2/

A: $('#back_button_recipes').on('DOMSubtreeModified',function(){
    if ($('.className').length > 0){
        $(this).addClass("main_menu");
    }
});


text:
Q: SAS macro include guards In other programming languages such as C++, include guards are used to prevent multiple inclusions of the same code.
Like this in C++:
#ifndef FOO_INCLUDED
#define FOO_INCLUDED
....
#endif

Does it make sense to build inclusion guards into your SAS macro function definitions? And how should it be done?

A: There is %SYMEXIST(macro-var-name) macro function to see if the macro-var exists, but you cannot write %IF in the open, so you have to enclose your %IF statement inside some other macro. You may end up writing a macro just to wrap your code in a source file like below. This is not pretty, but you can probably get by with this, if the guard is needed.
%macro wrapper;
  %if %symexist(foo_defined) %then %return;
  %macro foo;
    %global foo_defined;
    %let foo_defined = 1;
    %put i am foo;
  %mend foo;
%mend  wrapper;

%*-- tests --*;
options mcompilenote=all;
%symdel foo_defined;

%*-- first time it will define %foo --*;
%wrapper
%foo
/* on log
NOTE: The macro FOO completed compilation without errors.
      6 instructions 108 bytes.
i am foo
*/

%*-- second time it will not --*;
%wrapper
%foo
/* on log
(no notes on macro compilation)
i am foo
*/

Upon invocation, SAS makes available a bunch of catalogs, files, and directories for accessing (compiled/not compiled) macros. This makes it cumbersome, but not impossible, to directly find out a macro is already available to this session or not, given the macro's name. Read about the (gory) details in this paper:
http://support.sas.com/resources/papers/proceedings09/076-2009.pdf

A: You could use the NOMREPLACE option to prevent any macro to be redefined.
In my opinion, reusing macro names and macro variable names (and even data set names) is evil. If you define things just once, you can be relatively sure you can resubmit any part of the code and expect to get the same results as originally. I also prefer keeping macro definitions separate from the code they're called from.


text:
Q: How to get argument value in custom validation attribute in .net core 2.1 How can i access myargument value argvalue from ValidateMain
Model
[ValidateMain]
public class MainClass
{
    [ValidateChild(myargument: "argvalue")]
    public string myproperty { get; set; }

    [ValidateChild(myargument: "argvalue2")]
    public string myproperty2 { get; set; }

}

ValidationAttributes
public class ValidateChild : ValidationAttribute
{
    private readonly string myargument;

    public ValidateChild(string myargument)
    {
        this.myargument = myargument;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Here I know how to get myargument value. My problem is how to get it in ValidateMain
        return ValidationResult.Success;
    }
}

public class ValidateMain : ValidationAttribute
{
    public ValidateMain()
    {

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach (System.Reflection.PropertyInfo item in value.GetType().GetProperties())
        {
            // What I need here is to get 'myargument' value 'argvalue'
        }
        return ValidationResult.Success;
    }
}

A: Use the below statement to get its value:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach (System.Reflection.PropertyInfo item in value.GetType().GetProperties())
        {
            var x = item.CustomAttributes.FirstOrDefault().ConstructorArguments.FirstOrDefault();

        }
        return ValidationResult.Success;
    }

Debug and have a quick watch then you can find out how to get it


text:
Q: Set optirun and g++ as compiler to compile OpenCL in Ubuntu I am trying to compile an OpenCL example in Ubuntu and I need to use optirun (from the library Bumblebee) in order to circumvent the NVIDIA Optimus problem.
When using make, I need the output to be
optirun g++ ...

*

*In the CMakeLists.txt file, I first tried SET(CMAKE_CXX_COMPILER optirun g++) but it only generates "optirun;g++" ...

*Cmake:
SET(CMAKE_CXX_COMPILER "optirun g++")
Output:
"optirun g++" ...

Another Cmake:
include(CMakeForceCompiler)

CMAKE_FORCE_CXX_COMPILER(optirun g++ GNU_OCL)

Output:
optirun ...

Another Cmake:
include(CMakeForceCompiler)

CMAKE_FORCE_CXX_COMPILER("optirun g++" GNU_OCL)

Output:
"optirun g++" ...

A: any OpenCL SDK comes with its own compiler, you are supposed to use that compiler.


text:
Q: Is Julia's `hash()` function guaranteed to have a stable output across sessions, platforms and versions? I tried running the following code in multiple different Julia REPL sessions, on MacOSX and Linux, and I always got the exact same outputs:
julia> hash(123), hash("123"), hash([1,2,3]), hash((1,2,3)), hash(Set([1,2,3])), hash(:123)
(0x54657e9dbfd649e5, 0xb4e92987fa06fcab, 0xecc5186e7be222c6, 0xafc764e9c2b7cde5, 0x66406071c4c9b92a,
0x54657e9dbfd649e5)

Question: is this behavior guaranteed by the language? Or can the outputs vary (like they do in Python, across sessions, platforms and versions)?
Note: this question is related to my other question about the stability of the order of hash-based collections such as Set and Dict (it's closely related, but different).

A: They are not stable and can change from version to version or platforms. They are already different between systems with different word sizes.


text:
Q: Can't find a way to click on element in Chrome webdriver - Selenium I'm trying to click an element with Chrome webdriver but i just can't figure out a way to click it.
The page is showing after i've logged in, so i can't post the website URL
The HTML code of the element is:
<gf-dashboard-card class="ng-scope ng-isolate-scope" href="/chat">

            question_answer

        Conversations

</gf-dashboard-card>

I've tried any way that i can't think of to click on the element but i'm always keep getting error:
Message: no such element: Unable to locate element

The xpath of the element is
//*[@id="dashboard-cards"]/gf-dashboard-card[1]

which gives me nothing.
One interesting thing is that in Firefox webdriver i can click it with
driver.find_element_by_class_name("ng-isolate-scope").click()

but it is not working with Chrome.
I can click the element through the console with
$('.md-subhead').click();

But haven't figured out how to run this via Selenium.
Any idea how i can run it?

A: You might want to use implicitly_wait instead of time.sleep to wait for the element to become clickable. When the element is found before the 10 second timeout, it will continue instead of waiting the remaining time.
From the documentation:

An implicit wait tells WebDriver to poll the DOM for a certain amount
  of time when trying to find any element (or elements) not immediately
  available. The default setting is 0. Once set, the implicit wait is
  set for the life of the WebDriver object.

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.find_element_by_xpath("//*[@id='dashboard-cards']/gf-dashboard-card[1]").click()

A: It was an issue with loading and waiting time.
Adding:
time.sleep(10)

And then:
driver.find_element_by_xpath("//*[@id='dashboard-cards']/gf-dashboard-
card[1]").click()

It worked well


text:
Q: Understanding of a float counter I have following simple code:
for (float i=0; i<1f; i+=0.1) {
    System.out.println(i);
}

I have just got following results:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001

But I can't understand why there is. Please, I hope you can tell me. Thank you.

A: From The Floating-Point Guide:

Why don't my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and
  instead I get a weird result like 0.30000000000000004?
Because internally, computers use a format (binary floating-point)
  that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.
When the code is compiled or interpreted, your "0.1" is already
  rounded to the nearest number in that format, which results in a small
  rounding error even before the calculation happens.

A: Well because with the way float has been implemented there usually is a very small deviation from the mathematical 0.1f you are incrementing with, so actually you are incrementing with just a small amount over that.
A solution would be to use:
BigDecimal

EDIT:
Michael posted a better description of your problem, but still you should take a look at BigDecimal.

A: It's because the way computers store floating point numbers.
For detailed information you could have a look at the IEEE 754.
This is related to a numerical problem.

A: You almost always need to constrain the number of decimal places when printing floats or doubles.
Java's take on printf from C
for (float i = 0; i < 1f; i += 0.1) {
    System.out.printf("%.1f\n", i);
}

DecimalFormat to print up to 1 decimal place if necessary
DecimalFormat format1 = new DecimalFormat("#.#");
for (float i = 0; i < 1f; i += 0.1) {
    System.out.println(format1.format(i));
}

DecimalFormat to print 1 decimal place always
DecimalFormat format2 = new DecimalFormat("0.0");
for (float i = 0; i < 1f; i += 0.1) {
    System.out.println(format2.format(i));
}


text:
Q: Javascript check counter and repeat function I have an html page and I'm using JavaScript to create a function that display 2 images (the first between second 5 and second 10 and the second image between second 10 and second 20) and repeat that every 30 seconds.
I tried
var cmp=0
function main() {
window.setTimeout(main,30000);
cmp+1;
if (cmp >= 5 and cmp < 10)
    show_image_1 ();
if (cmp >= 10 and cmp < 15)
    show_image_2 ();
}

but I didn't find out how to check the time every second.

A: Define an Interval, and then display the image based on that:

window.setInterval(updateImg, 1000);
var timer = 0;
var imageSrc = document.getElementById("imageSrc");
imageSrc.style.display = "none";

function updateImg() {
    timer += 1;
    if (timer > 30) {
        timer = 0;
    }
    if (timer >= 5 && timer <= 10) {
        imageSrc.style.display = "block";
        imageSrc.src = "http://lorempicsum.com/futurama/255/200/1";
    } else if (timer >= 10 && timer <= 20) {
        imageSrc.style.display = "block";
        imageSrc.src = "http://lorempicsum.com/futurama/255/200/2";
    } else {
        imageSrc.style.display = "none";
    }
}
<img src="" id="imageSrc">

JsFiddle: http://jsfiddle.net/ghorg12110/z6vfn1nb/

A: Here is my proposal:
// Define the images and the duration of each one in seconds (a missing "src" means the image will be empty):
var steps=[
    {duration: 2},
    {duration: 3, src:'one.jpg'},
    {duration: 5, src:'two.jpg'},
    {duration: 5},
];

// Index of current step: Will cylce from 0 to steps.length:
var currentStep=0;

// Periodic function to show the current step, and re-invokes itself cyclically:
function nextStep()
{
    var step=steps[currentStep];
    var img=document.getElementById("myimg");
    if (step.src)
    {
        img.src=step.src;
        img.style.visibility="visible";
    }
    else
    {
        // When there is no "src" in the current step: Hide the image:
        img.style.visibility="hidden";
    }
    currentStep=(++currentStep % steps.length);
    setTimeout(nextStep, 1000*step.duration);
}

To start the cycle, you have to call nextStep().


text:
Q: bash_profile and the PATH variable I have the following in my bash_profile to automatically run the smlnjinterpreter:
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/smlnj-110.74/bin:${PATH}"
export PATH

Additionally I would also like to run theswi prolog interpreter by adding its path at:
\opt\local\bin

How can I set the PATH variable to check both or is there a better way?
Why does Petite Chez Scheme require no PATH or environment variable settings? That is, when I type petite into the terminal the petite chez scheme interpreter starts automatically.

A:
How can I set the PATH variable to check both?

This is one way, not necessarily the best way
items=(
  /Library/Frameworks/Python.framework/Versions/2.7/bin
  /usr/local/smlnj-110.74/bin
  /opt/local/bin
)
for item in ${items[*]}
do
  PATH=${item}:${PATH}
done
export PATH

Why does Petite Chez Scheme require no PATH or environment variable settings?

Perhaps it installs to a standard location, such as
/bin, /usr/bin, /usr/local/bin


text:
Q: Intermittent NullPointerException hard to reproduce I have an app which works almost perfect for around 500 users, BUT from time to time I am getting in Android Vitals report about Null Pointer Exception (always that same). For all 500 users, I got six times this error. I am not sure it is a lot, but it bothers me that I have a bug in my code. The problem is that it does not happen every use of my app and is very intermittent. Since a few days I am trying to reproduce it to fix it, but with no luck at all. Can I have your help, please?
Stacktrace:
java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3270)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3409)
  at android.app.ActivityThread.handleRelaunchActivityInner (ActivityThread.java:5279)
  at android.app.ActivityThread.handleRelaunchActivity (ActivityThread.java:5187)
  at android.app.servertransaction.ActivityRelaunchItem.execute (ActivityRelaunchItem.java:69)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2016)
  at android.os.Handler.dispatchMessage (Handler.java:107)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7356)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:492)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:930)

// My app part start //////////////////////////////////////////////////////////////

Caused by: java.lang.NullPointerException:
  at com.vulterey.nixieclockwidget.ConfigActivity.refreshClock (ConfigActivity.java:446)
  at com.vulterey.nixieclockwidget.ConfigActivity.access$000 (ConfigActivity.java:63)
  at com.vulterey.nixieclockwidget.ConfigActivity$SettingsFragment.onCreatePreferences (ConfigActivity.java:138)

// My app part end //////////////////////////////////////////////////////////////

  at androidx.preference.PreferenceFragmentCompat.onCreate (PreferenceFragmentCompat.java:160)
  at androidx.fragment.app.Fragment.performCreate (Fragment.java:2684)
  at androidx.fragment.app.FragmentStateManager.create (FragmentStateManager.java:280)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1175)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1356)
  at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState (FragmentManager.java:1434)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1497)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:2625)
  at androidx.fragment.app.FragmentManager.dispatchCreate (FragmentManager.java:2571)
  at androidx.fragment.app.FragmentController.dispatchCreate (FragmentController.java:236)
  at androidx.fragment.app.FragmentActivity.onCreate (FragmentActivity.java:315)
  at androidx.appcompat.app.AppCompatActivity.onCreate (AppCompatActivity.java:106)
  at com.vulterey.nixieclockwidget.ConfigActivity.onCreate (ConfigActivity.java:71)
  at android.app.Activity.performCreate (Activity.java:7825)
  at android.app.Activity.performCreate (Activity.java:7814)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1306)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3245)

A part of the code from ConfigActivity.java file:
Line

63  public class ConfigActivity extends AppCompatActivity {...

        public static class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {

            // Runs all services to enable/disable option preferences depend on user choices
            @Override
            public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
                setPreferencesFromResource(R.xml.root_preferences, rootKey);

            ...

            //Runs refreshClock on Create Preferences to show settings base on Shared Preferences state
            ConfigActivity refreshActivity = (ConfigActivity) this.getActivity();
138         refreshActivity.refreshClock(context);

            ...}

            // Refreshes view of the clock in Config Activity to visualise changes in options made by user
            private void refreshClock(Context context){...

            // Gets all colors from Preference Manager
            int hoursColor = PreferenceManager.getDefaultSharedPreferences(context).getInt("hoursColor", ContextCompat.getColor(context, R.color.clockTextColor));

            ...

            //Sets color of the clock elements with colors from Preference Manager
            TextView clockHours = activity.findViewById(R.id.clockHours);
446         clockHours.setTextColor(hoursColor);

        ...}

    ...}

The TextView "clockHours" exist in the configuration_activity.xml file.
So, my question is how to reproduce it?
Or what is causing it?
Any help as usual much appreciated.
Regards
Adam


text:
Q: Expendable listView ui design? I am facing a problem .
I need to design a UI basically i have done it but some one suggest me to design with ExpandableListView.
I am not getting any idea to design with ExpandableListView.
1-is it possible make this design with ExpandableListView.
if it is please guide me to design it with my desire view.

Problem:- In my list items two contains button and others are text only.
          That's why i want to know the possibility of this design ,it can be done or not.

A: Look at the Documents and these tutorials
ExpandableListView
Expandable ListView in ANDROID
Android Expandable ListView simple Example in android
you can expand list item by using this
ExpandableListView.setOnChildClickListener(new OnChildClickListener()
{
   public boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id)
   {
       // your code...
   }
}


text:
Q: Does Hibernate 4 with ehcache require ehcache-core library? I am attempting to upgrade an appliaction from Hibernate 3 to Hibernate 4. The application uses ehcache.
When upgrading to Hibernate 4.2.0.Final I added a dependency on hibernate-ehcache-4.2.0.Final as suggested.
When I started up the application I received the following error:
Caused by: java.lang.NoClassDefFoundError: org/hibernate/cache/TimestampsRegion

According to http://www.javacraft.org/2012/03/migrate-to-hibernate-4-ehcache.html I should remove the dependency on ehcache-core and only use the hibernate provided jar to resolve this error.
Now, if I follow these instructions and remove this dependency my application which uses the net.sf.ehcache.CacheManager no-longer compiles.
// For example, this no-longer works
CacheManager manager = CacheManager.getInstance();

So my question is, can I use both libraries and continue working as before (Without updating the app), or do I have to change the app, in which case does hibernate-ehcache even provide the functionality required to access the cache?

A: When using Hibernate 4 you have to use the org.hibernate packaged classes.
The net.sf.ehcache ones are target at Hibernate 3.
Form 4 they have ported to 4 within the Hibernate repo directly (which is the most sensible thing in our opinion).
So using org.hibernate.cache.ehcache.EhCacheRegionFactory should solve your problem.

A: Check if there any .properties file in your project like hsqlDatabaseConfig.properties, try to update the property as below
sessionFactory.hibernateProperties = hibernate.cache.use_second_level_cache=true\n\
                                     hibernate.cache.use_query_cache=true\n\
                              hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.internal.EhcacheRegionFactory\n\


text:
Q: Laravel 5.1 update many-to-many pivot I'm trying to update records on a pivot table using Eloquent in Laravel 5.1.
I've got 3 tables: pages, resources and the pivot pages_resources. These are the relationship methods:
Model Page.php
public function resources()
{
    return $this->belongsToMany('App\Resource', 'pages_resources', 'id_page', 'id_resource')
                ->orderBy('ordering', 'asc');
}

Model Resource.php
public function page()
{
    return $this->belongsToMany('App\Page', 'pages_resources', 'id_resource', 'id_page');
}

Now, I'm getting a list of resources from an AJAX POST request, and I want to change their order. I'm using a findMany method to fetch the collection:
$resources = Resource::with('page')->findMany($request->get('order'));
$resources->each(function ($item, $key) {
   // Working on $item here
});

and here is where I'm stumped. I tried both sync()
  $item->page()->sync([$item->id => ['ordering' => $key+1]], false));

and updateExistingPivot()
 $item->page()->updateExistingPivot($item->id, ['ordering' => $key+1], false);

and while the former yields wrong results the latter isn't event working (no error message received, though. It simply fails silently);
Using sync() always ends up creating a new record in the pivot table, with the correct value for the "ordering" column but wrong value for the keys. I tried using something different then $item->id (which maps to "id_resource"), but to no avail.
I might have done something wrong, though the relationships look correct, since a Resource object has a
#relations: array:1 [
    "page" =>

collection, and the page collection in turn shows the pivot:
#relations: array:1 [
            "pivot" => Pivot {#318

How can I update a pivot table record?


text:
Q: Magento Admin redirects to homepage after login i configured the magento backend. But now it redirects me to the homepage after successful login. When i type the backend url again, it also directly puts me to the front end.
I did clear all cache, tried different browsers etc.
Can anyone help?


text:
Q: App crashing after loging in using otp once and then after logout trying to go to login page again App has stopped. Open app again.
This is my SignUp activity where I have the phone number and password fields. After filling those, the user clicks on the sign in button, which redirects the user to otp verification page.
public class SignUp extends google_abstract {

    ImageView imageView4;
    ImageView imageView5;
    ImageView imageView6;
    TextView textView13;
    EditText phone_no;
    Button sign_up;
    EditText password;

    FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {
                Intent intent = new Intent(SignUp.this, verify_otp.class);
                startActivity(intent);
                finish();
            }
        }
    };

    FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();

    @Override
    protected void onStart() {
        super.onStart();
        firebaseAuth.addAuthStateListener(authStateListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        firebaseAuth.removeAuthStateListener(authStateListener);
    }

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

        imageView4 = findViewById(R.id.imageView4);

        imageView4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn();
            }
        });

        textView13 = findViewById(R.id.textView13);

        phone_no = findViewById(R.id.editText);

        password = findViewById(R.id.editText2);

        textView13.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SignUp.this,verify_otp.class);
                startActivity(intent);
            }
        });

        sign_up = findViewById(R.id.button1);
        sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String number = phone_no.getText().toString().trim();
                String pass = password.getText().toString();

                if(number.isEmpty()||number.length()<10) {
                    phone_no.setError("Valid Number is required");
                    phone_no.requestFocus();
                    return;
                }
                else if( (pass.length()<8 || pass.length()>12) ){
                    password.setError("must contain min 8 and max 12 characters");
                    password.requestFocus();
                }
                else {
                    String ph_no = "+91"+number;
                    Intent intent = new Intent(SignUp.this, verify_otp.class);
                    intent.putExtra("ph_no", ph_no);
                    startActivity(intent);
                }
            }
        });
    }
}

This is my verify_otp activity, where the otp is entered and then the user moves in to the profile section :
public class verify_otp extends AppCompatActivity {

    EditText otp;
    Button button3;
    private String verificationId;
    ProgressBar progressBar_otp;

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

        // rsnd = findViewById(R.id.rsnd);

        String phoneNumber = getIntent().getStringExtra("ph_no");
        sendVerificationCode(phoneNumber);

        otp = findViewById(R.id.editText3);
        button3 = findViewById(R.id.button3);
        progressBar_otp = findViewById(R.id.progressBar_otp);

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = otp.getText().toString().trim();

                if(code.isEmpty()||code.length()<6){
                    otp.setError("Enter code...");
                    otp.requestFocus();
                    return;
                }

                progressBar_otp.setVisibility(View.VISIBLE);
                verifyCode(code);
            }
        });

    }

    private void sendVerificationCode(String phoneNumber){
        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                phoneNumber,
                60,
                TimeUnit.SECONDS,
                TaskExecutors.MAIN_THREAD,
                mCallBack);
    }

    private PhoneAuthProvider.OnVerificationStateChangedCallbacks
            mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {

        @Override
        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
            verificationId=s;
        }

        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {

            String code = phoneAuthCredential.getSmsCode();
            if(code!=null){
                progressBar_otp.setVisibility(View.VISIBLE);
                verifyCode(code);
            }
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(verify_otp.this,e.getMessage(),Toast.LENGTH_LONG);
        }

    };

        private void verifyCode(String code) {
            PhoneAuthCredential credential= PhoneAuthProvider.getCredential(verificationId,code);
            signInWithCredential(credential);
        }

    private void signInWithCredential(PhoneAuthCredential credential){

        FirebaseAuth mAuth = FirebaseAuth.getInstance();

        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(verify_otp.this ,new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){
                            Intent intent= new Intent(verify_otp.this, tags.class);
                            intent.setFlags((Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK));

                            startActivity(intent);
                        }
                        else{
                            Toast.makeText(verify_otp.this, task.getException().getMessage(),Toast.LENGTH_LONG);
                        }
                    }
                });
     }
}

This works fine for the first time when the user installs this app but it crashes after the user tries to go to the signUp Activity.
The logcat shows these exceptions:
2020-04-23 21:17:04.625 23151-23151/com.sneha.blackcoffer I/zygote: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.sneha.blackcoffer-RQhqJvhXDK8dcBsMOKlvsQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.sneha.blackcoffer-RQhqJvhXDK8dcBsMOKlvsQ==/lib/arm, /system/lib, /system/vendor/lib]]
2020-04-23 21:17:04.627 23151-23151/com.sneha.blackcoffer I/zygote: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.sneha.blackcoffer-RQhqJvhXDK8dcBsMOKlvsQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.sneha.blackcoffer-RQhqJvhXDK8dcBsMOKlvsQ==/lib/arm, /system/lib, /system/vendor/lib]]
2020-04-23 21:17:04.628 23151-23151/com.sneha.blackcoffer I/zygote: Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/com.sneha.blackcoffer-RQhqJvhXDK8dcBsMOKlvsQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.sneha.blackcoffer-RQhqJvhXDK8dcBsMOKlvsQ==/lib/arm, /system/lib, /system/vendor/lib]]
2020-04-23 21:17:04.761 23151-23151/com.sneha.blackcoffer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sneha.blackcoffer, PID: 23151
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sneha.blackcoffer/com.sneha.blackcoffer.verify_otp}: java.lang.IllegalArgumentException: Given String is empty or null
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2974)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3059)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1724)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:7000)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
     Caused by: java.lang.IllegalArgumentException: Given String is empty or null
        at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(com.google.android.gms:play-services-basement@@17.1.1:5)
        at com.google.firebase.auth.PhoneAuthProvider.verifyPhoneNumber(com.google.firebase:firebase-auth@@19.3.0:13)
        at com.sneha.blackcoffer.verify_otp.sendVerificationCode(verify_otp.java:73)
        at com.sneha.blackcoffer.verify_otp.onCreate(verify_otp.java:47)
        at android.app.Activity.performCreate(Activity.java:7258)
        at android.app.Activity.performCreate(Activity.java:7249)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1222)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3059)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1724)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:7000)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

Line 47 is this
        sendVerificationCode(phoneNumber);
and, line 73 is this        PhoneAuthProvider.getInstance().verifyPhoneNumber(

A:
Caused by: java.lang.IllegalArgumentException: Given String is empty
  or null

Seems like your phoneNumber String is empty or null. You should check it through TextUtils.isEmpty().
 String phoneNumber = getIntent().getStringExtra("ph_no");
 if(!TextUtils.isEmpty(phoneNumber))
 {
  sendVerificationCode(phoneNumber);
 }
 else
 {
  //Print your phone number is null or empty
 }


text:
Q: How to delete duplicate rows in this specific statement I have seen some good examples for deleting duplicate rows, but my attempts fail.  Something in this won't let it happen.  Errors don't tell me anything to help me know whats wrong with it.  I won't include it to dirty up my question.  Lets just say that this script works and gives a sequential index for each duplicate row, as DuplicateCount.  Basically all lines with a DuplicateCount > 1 need deleted.  How do I wrap this around this statement?
SELECT
    v.WONum,
    o.OrderNumber,
    o.GUIDOrder,
    v.WorkOrder,
    v.Product,
    v.BuildDate,
    v.TestDate,
    v.PassFail,
    v.Valve,
    ROW_NUMBER() OVER
        (Partition BY v.WONum, o.OrderNumber, o.GUIDOrder, v.WorkOrder, v.Product, v.BuildDate, v.TestDate, v.PassFail, v.Valve
        ORDER BY Index_VSN) AS DuplicateCount
FROM dbo.Valve_One_Worksheet_New AS v
LEFT OUTER JOIN [KT-RD-01\acctivate].ACCTivate$KELSOTECH.dbo.Orders AS o
    ON v.WONum COLLATE SQL_Latin1_General_CP1_CI_AS = o.OrderNumber COLLATE SQL_Latin1_General_CP1_CI_AS

I have tried this, and no work.
https://www.sqlshack.com/different-ways-to-sql-delete-duplicate-rows-from-a-sql-table/

A: Have you tried SELECT DISTINCT?
Its normal use is to remove duplicate lines.
SELECT DISTINCT v.WONum, o.OrderNumber, o.GUIDOrder, v.WorkOrder, v.Product, v.BuildDate, v.TestDate, v.PassFail, v.Valve, ROW_NUMBER() OVER (Partition BY v.WONum, o.OrderNumber, o.GUIDOrder, v.WorkOrder, v.Product, v.BuildDate, v.TestDate, v.PassFail, v.Valve
ORDER BY Index_VSN) AS DuplicateCount FROM dbo.Valve_One_Worksheet_New AS v
LEFT OUTER JOIN [KT-RD-01\acctivate].ACCTivate$KELSOTECH.dbo.Orders AS o
ON v.WONum COLLATE SQL_Latin1_General_CP1_CI_AS = o.OrderNumber COLLATE SQL_Latin1_General_CP1_CI_AS

A: Huh... I guess I was thinking about it too complicated.  I did have to take out the DuplicateCount stuff...  This is what finally worked.  Thanks, @FelixACR
SELECT DISTINCT v.WONum, o.OrderNumber, o.GUIDOrder, v.WorkOrder, v.Product, v.BuildDate, v.TestDate, v.PassFail, v.Valve
FROM   dbo.Valve_One_Worksheet_New AS v LEFT OUTER JOIN
             [KT-RD-01\acctivate].ACCTivate$KELSOTECH.dbo.Orders AS o ON v.WONum COLLATE SQL_Latin1_General_CP1_CI_AS = o.OrderNumber COLLATE SQL_Latin1_General_CP1_CI_AS


text:
Q: Oauth2.json not generated after calling flow_from_clientsecrets with my client secrets file Trying to run the code below and keep getting told that there's no such file or directory as main.py-oauth2.json. Anyone got any idea what could be going wrong? Printing storage shows it is an oauth2client.file.Storage object. Is this an issue with using the flow_from_clientsecrets method or an issue with creating the Storage class instance?
Code:
def get_authenticated_service():

flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_SCOPE,
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()

if credentials is None or credentials.invalid:
  credentials = tools.run_flow(flow, storage)

return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))

Error message:
/home/runner/project/venv/lib/python3.8/site-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access main.py-oauth2.json: No such file or directory

warnings.warn(_MISSING_FILE_MESSAGE.format(filename))


text:
Q: Multiple Instances of the Same Microservice BUT with Different Secrets I would like to run 3 instances of the same exact microservice but would also like that each microservice will read from a different secret with unique parameters and database connection string.

*

*Is this something that can be configured in Kubernetes?

*In case we decide not to use Kubernetes, what is the best way to associate a microservice instance with its secret (appsettings?).

A: When you say: same exact microservice, do you mean "same image" or "same deployment"? Are these part of the same replicaset or they are "independent"? Is this a multi-tenant where each "instance" is processing requests for a tenant?
If they are different deployments, they that can easily be done because in k8s they are different and each can have it's own config/secrets.
If they are the same deployment/replicaset; then I'd question why you need this?


text:
Q: HQL Query for simple SQL joins how can i apply 2 conditions in join in HQL
I want to write HQL for below query
Select * from Employee e
left join fetch Salary s on s.sal in (1000,2000);

My question is: how can we apply multiple conditions on join. i know internally,
the query will be executed like
select * from Employee e
left join Salary s on s.id = e.id

but how can i write hql for more than single condition?
I hope my question is cleared?

A: A valid HQL query would look something like this:
select e, s
from Employee e left join e.salary s with (s.sal in (1000,2000))

This assumes that the Employee entity has a Salary field salary.  If I have the names off, then change the query.


text:
Q: Custom base_site.html not working in Django I am using Nitrous for playing with the Django framework. In tutorial 2 is shown how to change the base_site.html template. I've added in the TEMPLATE_DIRS = ( ) a new line:

'home/action/workspace/mysite/templates',

And in base_site.html I changed the site name title of Django Administration into Administration:

{% trans 'Administration' %}

But I still see no changes on the website. I've tried different TEMPLATE_DIRS like:

'~/workspace/mysite/templates',
'home/action/workspace/mysite/',
'home/action/workspace/mysite/templates/',

And restarting the server. But I am doing something wrong.

A: Note that this answer was written before the TEMPLATES setting was introduced in Django 1.8.
The tutorial says you should create an admin subdirectory inside your template directory, and put your template inside that.
Try with base_site.html in /home/action/workspace/mysite/templates/admin and with
TEMPLATE_DIRS = (
    '/home/action/workspace/mysite/templates',
)

Note the slash before /home/... and the trailing comma to make it a tuple.


text:
Q: VBA to Decipher between a regular SELECT query vs any type of ACTION query in MS Access 2016 How can I decipher a simple SELECT query vs an Action Query?
I have a loop that edits a query if the name matches a name in my table.  The code works, but I want it to skip over any action query i.e. UPDATE, DELETE, INSERT, etc.
I thought I could simply check LEFT(qdf.sql,6) for "SELECT"  but any action query that involves selecting another query will begin with 'SELECT'...

A: Actually each type of query has its own integer value. By this integer value you can define the type of query. Here is few sample. You will get these integer value by below line
CurrentDb.QueryDefs("YourQuery").Type

 0   SELECT Query
 128 UNION Query
 32  DELETE Query
 48  UPDATE Query
 64  APPEND Query

If you want to return action First Word of a query then extract first word from query SQL statement. Loop through all query and get first word. try below sub.
Private Sub Command1_Click()
Dim qSQL As String
Dim qAction As String
Dim qdf As DAO.QueryDef

    For Each qdf In CurrentDb.QueryDefs
        qSQL = qdf.SQL  'CurrentDb.QueryDefs("Query7").SQL
        qAction = Left(qSQL, InStr(1, qSQL, " ") - 1)
        Debug.Print qAction
        Debug.Print "Type Integer Value= " & qdf.Type
    Next

End Sub

Please note: This sub will not work if parameter is defined at starting of query. Then you have to use QueryDef.Type property to determine query type.

Edit: Use Select Case statement to define each query type. See below. You have explore more for other queries.

Private Sub Command1_Click()
Dim qdf As DAO.QueryDef

    For Each qdf In CurrentDb.QueryDefs
        Select Case qdf.Type
            Case dbQSelect
                Debug.Print qdf.Name; " is a SELECT Query."
            Case dbQDelete
                Debug.Print qdf.Name; " is a DELETE Query."
            Case dbQUpdate
                Debug.Print qdf.Name; " is a UPDATE Query."
            Case dbQAppend
                Debug.Print qdf.Name; " is a APPEND Query."
            Case dbQSetOperation
                Debug.Print qdf.Name; " is a UNION Query."
            Case Else
                Debug.Print "Something else."
        End Select
    Next

End Sub

A: You can check the Type property of each QueryDef object and skip those you don't want to handle:
QueryDef.Type property (DAO)


text:
Q: Can I use AD CS to Authenticate Domain Users Instead of a Password? I have a number of Active Directory Domain User Accounts, which function essentially as service accounts.  I'd like to avoid having to rotate the passwords for all of those domain user accounts, and rather allow/force those domain user accounts to authenticate via certificates (AD CS) when the domain user accounts are used to run scripts/scheduled tasks/RDP connections.
I've installed AD CS following https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/jj129709(v=ws.11), but am getting lost somewhere trying to validate that domain user accounts are able to authenticate via AD CS rather than domain user/password.
How can I implement a structure where domain user accounts can authenticate to domain-joined servers using certificates (AD CS) rather than domain user/password?
For the record, I'm still running Server 2012R2 on all my domain controllers, and currently have AD CS installed on one of the two synchronized domain controllers.


text:
Q: longtable Alignment I'm using a long table with image and lots of text. The alignment of it is wrong for me. I'd like to know how to make the text start on top of the box, near the line.
Here is my code for the longtable
\begin{longtable}{|c|p{3cm}|p{8cm}|}

\hline
\rowcolor{blue!35}
Ícone & Barra de ferramentas perfis & Ações
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil apontador.png}
&
Apontador
&
Seleciona track, finaliza algumas ações como: identificador de pontos editar marcadores, criar camadas, zoom vertical.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil indentidicadordepontos.png}
&
Identificador de pontos
&
Selecione e passe sobre o perfil, e etiquetas com informações serão mostradas.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil localizador.png}
&
Localizador
&
Apresenta o valor da escala do perfil e da profundidade no perfil da amostragem.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil zoomvertical.png}
&
Zoom vertical
&
Aumenta verticalmente, selecione e clique no topo e na base de onde deseja aumentar o zoom.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil zoommenos.png}
&
Zoom -
&
Clique para diminuir ou retirar o zoom vertical.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil visaoglobal.png}
&
Visão global
&
Volta ao tamanho normal de apresentação do dado.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil editordemarcadores.png}
&
Editor de marcadores
&
Cria pontos de informação no registro, ligado a uma profundidade.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil editordecamadas.png}
&
Editor de camadas
&
Cria pontos ligados a topo de base de um intervalo.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil gerenciarcolunas.png}
&
Gerenciar colunas
&
Apresenta os perfis existentes e está ligado aos ícones inserir ou remover track e gerenciador de Perfis.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil gerenciarperfis.png}
&
Gerenciar perfis
&
Através de uma caixa de diálogos ajuda a inserir ou remover perfis de uma mesma track.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil configurarperfis.png}
&
Configurar perfis
&
Apresenta uma caixa de diálogos onde poderá manusear as informações e estilos dos perfis. Editar nome, escala, unidades, grids, cores e preenchimento entre perfis.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil inserirtrack.png}
&
Inserir track
&
Possui combo box  com diferentes tipos de tracks: perfis, litologia, ihc,  marcadores, imagens, bioestratigrafia e camadas.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil removertrack.png}
&
Remover Track
&
Remove a track selecionada.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil moverparaesquerdaeparadireita.png}
&
Mover para a esquerda e para a direita
&
Move a track selecionada para esquerda e para a direita.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil setarposicaodepocos.png}
&
Setar posição dos poços
&
Para a múltipla visualização, ajusta os poços a uma distancia que pode ser editada pelo usuário.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil desenhodascamadas.png}
&
Desenho das camadas
&
Para Desenha as camadas correlatas entre poços.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil definirdatum.png}
&
Definir datum
&
Para a múltipla visualização ajusta as profundidades dos poços para visualização de datum, selecionado pelo usuário.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil dadomedido.png}
&
Dado medido
&
O dado medido é definido nas \textbf{propriedades} do poço na aba de \textbf{Datum Vertical} e podem ser alterados pelo usuário.
\\
\hline
\rowcolor{gray!35}
\includegraphics[scale=0.7]{\visualizadordeperfil salvarimagem.png}
&
Salvar imagem
&
Salva uma cópia da imagem em diretório formatos  diferentes de arquivo, mas por default é .png.
\\
\hline
\includegraphics[scale=0.7]{\visualizadordeperfil salvartemplate.png}
&
Salvar template
&
Se salva como \textbf{Template}, um formato de visualização padrão de perfis, gráficos etc., definido pelo usuário ou padrão da indústria.
\\
\hline

\caption{Tabela de ferramentas para Perfis.}
\label{tab:tabeladeferramentasperfil}
\end{longtable}

Here is an Image
Any sugestions on how to make it look better?

A:
The tex model of table layout doesn't really allow for vertically centering within the space of a cell, each cell has a base reference point and these are aligned. l, c, r columns it is the baseline of the text p columns it is the baseline of the top row.
and for m columns it is that cell's centre and b it is that cells bottom line. The baseline of an image is on its bottom edge. Note that m does not place the cell content in the centre of the space finally allocated to that cell, it simply puts the baseline of the content on that content's vertical centre.
So you get the layout in the first example.
You can change the reference point of the image to be roughly one line's worth below the top with
\raisebox{10pt-\height}{\includegraphics....

That will give a layout like the second image, but the first column it is not centred, if there is a lot of text in the third column, the image will still be aligned on its top row.
If you want centred appearance you need to center the third column. If that used m rather than p its reference point would be in its centre, then you can put the reference point of the image in the centre with
\raisebox{-.5\height}{\includegraphics....

and the alignment will be:

A: Type \usepackage[export]{adjustbox} to your document preamble immediately above \usepackage{graphicx}.
Then include your images as
\includegraphics[scale=0.7,valign=t]{\visualizadordeperfil apontador.png}

This will shift the picture vertically, so that its height is just like the height of a line of text.
Here's an example, I used \fbox around \includegraphics to show the precise bounding box.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[portuguese]{babel}
\usepackage[table]{xcolor}
\usepackage{longtable}
\usepackage[export]{adjustbox}

\setlength{\fboxsep}{-.5\fboxrule}% just for the example

\begin{document}

\begin{longtable}{|c|p{3cm}|p{8cm}|}

\hline
\rowcolor{blue!35}
Ícone & Barra de ferramentas perfis & Ações
\\
\hline
\rowcolor{gray!35}
\fbox{\includegraphics[width=1cm,valign=t]{apontador.png}}
&
Apontador
&
Seleciona track, finaliza algumas ações como: identificador de pontos editar marcadores, criar
camadas, zoom vertical.
\\
\hline
\fbox{\includegraphics[width=1cm,valign=t]{apontador.png}}
&
Identificador de pontos
&
Selecione e passe sobre o perfil, e etiquetas com informações serão mostradas.
\\
\hline
\end{longtable}

\end{document}

A: You can centre the images with a simple \raisebox{-0.5\height}{…}. As the vertical spacing in tables is very tight, you can introduce some more with the cellspace package: it ensures a minimal spacing between a cell and the above and below cells in columns that have an S prespecifier.
Here is an example, using one of my favourite images. In order to have a shorter code, I define a \myincludegraphics command:
\documentclass[a4paper,12pt,]{article}

\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage[vmargin=2cm, hmargin=2.5cm]{geometry}
\usepackage{array, colortbl}
\usepackage{cellspace}
\setlength\cellspacetoplimit{5pt}
\setlength\cellspacebottomlimit{5pt}

\newcommand\myincludegraphics[2][]{ \raisebox{-0.5\height}{\includegraphics[#1]{#2}}}
    \begin{document}
    \begin{longtable}{|Sc|m{3cm}|m{8cm}|}
    \endhead
    \endfirsthead
    \endfoot
    \multicolumn{3}{c}{}\
    \caption{Tabela de ferramentas para Perfis.}
    \label{tab:tabeladeferramentasperfil}
    \endlastfoot
\hline
\rowcolor{blue!35}
Ícone & Barra de ferramentas perfis & Ações
\\
\hline
\rowcolor{gray!35}
%\raisebox{-0.5\height}{\includegraphics[scale=0.5]{sendak.png}}
\myincludegraphics[scale=0.5]{sendak.png}
&
Apontador
&
Seleciona track, finaliza algumas ações como: identificador de pontos editar marcadores, criar camadas, zoom vertical.
\\
\hline
\myincludegraphics[scale=0.5]{sendak.png}
&
Identificador de pontos
&
Selecione e passe sobre o perfil, e etiquetas com informações serão mostradas.
\\
\hline
\rowcolor{gray!35}

\myincludegraphics[scale=0.5]{sendak.png}
    &
    Localizador
    &
    Apresenta o valor da escala do perfil e da profundidade no perfil da amostragem.
    \
    \hline
    \myincludegraphics[scale=0.5]{sendak.png}
    &
    Zoom vertical
    &
    Aumenta verticalmente, selecione e clique no topo e na base de onde deseja aumentar o zoom.
    \
    \hline
    \rowcolor{gray!35}
    \myincludegraphics[scale=0.5]{sendak.png}
    &
    Zoom -
    &
    Clique para diminuir ou retirar o zoom vertical.
    \
    \hline
    \end{longtable}
    \end{document}


text:
Q: __NSDictionaryI setObject:forKey: Crash The problem is that I am mutating a NSDictionary, but even after getting a mutableCopy, the app crashes.
Below is Method for copy :
+ (NSMutableDictionary *)updateQuery:(NSMutableDictionary *)currentQuery toSearchAfterAccountPaginationSequence:(NSString *)accountPaginationSequence {

    //try1
    NSMutableDictionary *mutableQuery = [currentQuery mutableCopy];

    //try2
    NSMutableDictionary *mutableQuery2=[NSMutableDictionary dictionaryWithDictionary:currentQuery];

    //crashes on this line
    mutableQuery[@"where"][@"account_pagination_sequence"] = @{ @"lt" : accountPaginationSequence };

    return mutableQuery;
}

Error Log (the app crashes on a limited amount of devices)
[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance

A: i think this is what you trying to achieve
+ (NSMutableDictionary *)updateQuery:(NSMutableDictionary *)currentQuery toSearchAfterAccountPaginationSequence:(NSString *)accountPaginationSequence {

    //try1
    NSMutableDictionary *mutableQuery = currentQuery.mutableCopy;
    NSMutableDictionary *where =  mutableQuery[@"where"].mutableCopy;

    where[@"account_pagination_sequence"] = @{ @"lt" : accountPaginationSequence };
    mutableQuery[@"where"] =  where;

    return mutableQuery;
}

Edit:
In Objective-C calling mutableCopy on objects is not recursive.You need to call mutableCopy in nested objects too.


text:
Q: Java jjwt creating invalid JSON for JWT I must be missing something. I am using the JJWT library to create JWTs. The JWTs are created inconsistently from the library depending on the data set in the claims. My code:
Date now = new Date();
Date expiration = new Date(now.getTime() + TimeUnit.MINUTES.toMillis(30));

Claims claims = Jwts.claims();

JSONObject jsonObject = new JSONObject();
jsonObject.put("serviceName1", "serviceStatus1");
jsonObject.put("serviceName2", "serviceStatus2");
claims.put("services",jsonObject);

claims.setSubject("225544");
claims.setExpiration(expiration);
claims.setId(UUID.randomUUID().toString());
claims.setIssuedAt(now);

return Jwts.builder()
    .setClaims(claims)
    .signWith(SignatureAlgorithm.HS256, Base64.encodeBase64(secret.getBytes()))
    .compact();

This code creates a JWT and signs it correctly. However, when the payload is decoded, the payload value is not always valid JSON. Most often it is missing the closing } causing any parsing of it to fail.
If the Subject is 8 characters, it works fine. If it is 7 or 6 characters long, it is invalid JSON. Or if I add other tags to the claim, sometimes it works and sometimes it doesn't. Am I doing something wrong?
I have also tried using Auth0 java-JWT library and get similar results, Payload not always valid JSON.

A: Please instead of JSONObject try Map<String,String>

A: Ultimately, I could not get the JJWT library working how I wanted. As such, I implemented a simple hashing algorithm and jwt creator manually. Here is what that looks like:
    Date now = new Date();
    //Valid only for 30 minutes
    Date expiration = new Date(now.getTime() + TimeUnit.MINUTES.toMillis(30));

    JSONObject header = new JSONObject();
    JSONObject payload = new JSONObject();

    header.put("alg", "HS256");

    payload.put("sub", "ourSubject");
    payload.put("exp", expiration.getTime() / 1000);
    payload.put("jti", UUID.randomUUID().toString());
    payload.put("iat", now.getTime() / 1000);
    payload.put("services", "JSON object of our custom data needed in authorization (not authentication");
    String signature = "";

    StringBuilder token = new StringBuilder();
    token.append(new String(Base64.encodeBase64(header.toString().getBytes())));
    token.append(".");
    token.append(new String(Base64.encodeBase64(payload.toString().getBytes())));
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(Base64.encodeBase64((secret + otherPartOfSecret).getBytes()), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        signature = new String(Base64.encodeBase64(sha256_HMAC.doFinal(token.toString().getBytes())));
    } catch (Exception e) {
        System.out.println("Error");
    }

    token.append(".");
    token.append(signature);

    return token.toString();

A: You can use the toMap() method to solve this issue.
The code from your example will then look like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("serviceName1", "serviceStatus1");
jsonObject.put("serviceName2", "serviceStatus2");
claims.put("services",jsonObject.toMap());

This will result in the following claim in the JWT.
"services": {
    "serviceName1": "serviceStatus1",
    "serviceName2": "serviceStatus2"
}