text:
Q: Radio button in list view I am showing list of sting in list view formate, i used default list view and placed a radio button by using simple_list_item_single_choice. But this shown the Radio button in right side, i want to display the radio button in left side. is that any possible to show the radio button in left side using default list view

A: simple_list_item_single_choice.xml use CheckedTextView class
Here is the  simple_list_item_single_choice.xml
 <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
   />

You need to create a custom xml for your need and use a CheckBox to achieve your goal
Here is your custom.xml
 <CheckBox
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:button="?android:attr/listChoiceIndicatorSingle"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
   />

Just use the custom.xml in place of simple_list_item_single_choice.xml in your code.
Hope it helps you.

A: It's not possible, by default the radio button is on the right. If you want it on the left then you should grab the sources for simple_list_item_single_choice.xml layout from the SDK and make the appropriate changes, then use this custom layout instead of the default one.

A: simple_list_item_single_choice use CheckedTextView class.
<?xml version="1.0" encoding="utf-8"?>

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
/>

CheckedTextView class is android.widget package.
This Class source below.
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.widget;

import com.android.internal.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewDebug;
import android.view.accessibility.AccessibilityEvent;

/**
 * An extension to TextView that supports the {@link android.widget.Checkable} interface.
 * This is useful when used in a {@link android.widget.ListView ListView} where the it's
 * {@link android.widget.ListView#setChoiceMode(int) setChoiceMode} has been set to
 * something other than {@link android.widget.ListView#CHOICE_MODE_NONE CHOICE_MODE_NONE}.
 *
 */
public class CheckedTextView extends TextView implements Checkable {
    private boolean mChecked;
    private int mCheckMarkResource;
    private Drawable mCheckMarkDrawable;
    private int mBasePaddingRight;
    private int mCheckMarkWidth;

    private static final int[] CHECKED_STATE_SET = {
        R.attr.state_checked
    };

    public CheckedTextView(Context context) {
        this(context, null);
    }

    public CheckedTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CheckedTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.CheckedTextView, defStyle, 0);

        Drawable d = a.getDrawable(R.styleable.CheckedTextView_checkMark);
        if (d != null) {
            setCheckMarkDrawable(d);
        }

        boolean checked = a.getBoolean(R.styleable.CheckedTextView_checked, false);
        setChecked(checked);

        a.recycle();
    }

    public void toggle() {
        setChecked(!mChecked);
    }

    @ViewDebug.ExportedProperty
    public boolean isChecked() {
        return mChecked;
    }

    /**
     *
Changes the checked state of this text view.

     *
     * @param checked true to check the text, false to uncheck it
     */
    public void setChecked(boolean checked) {
        if (mChecked != checked) {
            mChecked = checked;
            refreshDrawableState();
        }
    }

    /**
     * Set the checkmark to a given Drawable, identified by its resourece id. This will be drawn
     * when {@link #isChecked()} is true.
     *
     * @param resid The Drawable to use for the checkmark.
     */
    public void setCheckMarkDrawable(int resid) {
        if (resid != 0 && resid == mCheckMarkResource) {
            return;
        }

        mCheckMarkResource = resid;

        Drawable d = null;
        if (mCheckMarkResource != 0) {
            d = getResources().getDrawable(mCheckMarkResource);
        }
        setCheckMarkDrawable(d);
    }

    /**
     * Set the checkmark to a given Drawable. This will be drawn when {@link #isChecked()} is true.
     *
     * @param d The Drawable to use for the checkmark.
     */
    public void setCheckMarkDrawable(Drawable d) {
        if (mCheckMarkDrawable != null) {
            mCheckMarkDrawable.setCallback(null);
            unscheduleDrawable(mCheckMarkDrawable);
        }
        if (d != null) {
            d.setCallback(this);
            d.setVisible(getVisibility() == VISIBLE, false);
            d.setState(CHECKED_STATE_SET);
            setMinHeight(d.getIntrinsicHeight());

            mCheckMarkWidth = d.getIntrinsicWidth();
            mPaddingRight = mCheckMarkWidth + mBasePaddingRight;
            d.setState(getDrawableState());
        } else {
            mPaddingRight = mBasePaddingRight;
        }
        mCheckMarkDrawable = d;
        requestLayout();
    }

    @Override
    public void setPadding(int left, int top, int right, int bottom) {
        super.setPadding(left, top, right, bottom);
        mBasePaddingRight = mPaddingRight;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        final Drawable checkMarkDrawable = mCheckMarkDrawable;
        if (checkMarkDrawable != null) {
            final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
            final int height = checkMarkDrawable.getIntrinsicHeight();

            int y = 0;

            switch (verticalGravity) {
                case Gravity.BOTTOM:
                    y = getHeight() - height;
                    break;
                case Gravity.CENTER_VERTICAL:
                    y = (getHeight() - height) / 2;
                    break;
            }

            int right = getWidth();
            checkMarkDrawable.setBounds(
                    right - mCheckMarkWidth - mBasePaddingRight,
                    y,
                    right - mBasePaddingRight,
                    y + height);
            checkMarkDrawable.draw(canvas);
        }
    }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        return drawableState;
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();

        if (mCheckMarkDrawable != null) {
            int[] myDrawableState = getDrawableState();

            // Set the state of the Drawable
            mCheckMarkDrawable.setState(myDrawableState);

            invalidate();
        }
    }

    @Override
    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
        boolean populated = super.dispatchPopulateAccessibilityEvent(event);
        if (!populated) {
            event.setChecked(mChecked);
        }
        return populated;
    }
}

You are onDraw modify. and simple_list_item_single_choice.xml modify.
ex.
<**your class(modifyed CheckedTextView)** xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:paddingLeft="6dip"
    android:paddingRight="6dip"
/>


text:
Q: Append a list as a column in a dataset I have a Dataset and a List, called dataset and intervals, and I would like to append the list as a new column of the dataset. I have tried:
ds = Dataset[{
   <|"char" -> 1, "freq" -> 0.1|>,
   <|"char" -> 2, "freq" -> 0.2|>,
   <|"char" -> 3, "freq" -> 0.3|>,
   <|"char" -> 0, "freq" -> 0.4|>
   }]

intervals = {{0, 0.4}, {0.4, 0.7}, {0.7, 0.9}, {0.9, 1.}}
ds[All, <|#, "intervals" -> intervals|> &]

but this adds the whole list to every row, whereas I would like each item of the list to be added to a different row.
Can this be achieved?

A: Here is a way using MapIndexed:
ds[MapIndexed[<| #, "intervals" -> intervals[[#2[[1]]]]|> &]]

Streams
In some other software environments, streams are often used to solve problems like this.  For lists, we can define a poor-man's version like this:
stream[list_List] := Module[{i = 1}, If[i > Length[list], Missing[], list[[i++]]] &]

Then we can write:
nextInterval = intervals // stream;

ds[All, <| #, "interval" -> nextInterval[] |> &]

Streams can greatly simplify merging operations.  Let's say we wanted to add each interval as two columns instead of one:
nextLimit = intervals // Flatten // stream;

ds[All, <| #, "lower" -> nextLimit[], "upper" -> nextLimit[] |> &]

Or perhaps we wanted to add columns from multiple sources:
nextInterval = intervals // stream;
nextCode = "ROYG" // Characters // stream;
nextColor = {Red, Orange, Yellow, Green} // stream;

ds[All, <| #, "interval"->nextInterval[], "code"->nextCode[], "color"->nextColor[] |>&]

Coming Soon?
Since at least version 10.4 of Mathematica there has been an undocumented set of iterator functions.  Perhaps they will become documented some day?  Then we could officially write:
nextInterval = GeneralUtilities`ToIterator[intervals];

ds[All, <| #, "interval" -> Read[nextInterval] |> &]

Also in the Coming Soon? department, we have the Streaming package of Leonid Shifrin.

A: More easy way
ds[All, Append["intervals" -> # & /@ intervals]]

A: One way:
ds // Transpose // Append["intervals" -> intervals] // Transpose

In Mathematica it is usually easier to operate on rows, which is what this solution demonstrates. I would have done the same if I was working with lists too. However, as other answers show there are dataset specific solutions that might work better.

A: Another way:
ds[MapThread[Append[#1, "intervals" -> #2] &, {#, intervals}] &]

A: Suppose your column is a list of Association objects or a Dataset:
ds = Dataset[{
<|"char" -> 1, "freq" -> 0.1|>,
<|"char" -> 2, "freq" -> 0.2|>,
<|"char" -> 3, "freq" -> 0.3|>,
<|"char" -> 0, "freq" -> 0.4|>
}];

intervals = {{0, 0.4}, {0.4, 0.7}, {0.7, 0.9}, {0.9, 1.}};

assoc=<|"interval"->#|>& /@ intervals;
col = Dataset[assoc];

Then you can simply use Join to add a column:
Join[ds, assoc, 2]
Join[ds, col, 2]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ordering SQL SELECT by result of a string comparison I have a table with two string columns, ID and LANGUAGE. Language can be one of CYM, ENG, GAE.
When selecting data from the table, I want to order it by the language column, putting a specified language at the start of the results, with the other languages later, in any order.
Say I have the data
+===+=====+
+ 1 + CYM +
+ 2 + GAE +
+ 3 + ENG +
+ 4 + CYM +
+===+=====+

and I want the output to be
+===+=====+
+ 3 + ENG +
+ 1 + CYM +
+ 2 + GAE +
+ 4 + CYM +
+===+=====+

How do I do the equivalent of
SELECT ID, LANGUAGE
FROM TABLE
ORDER BY (LANGUAGE = 'ENG'), ID

A: You can use CASE WHEN to ensure ENG will be first:
SELECT ID, LANGUAGE
FROM your_table
ORDER BY
  CASE LANGUAGE WHEN 'ENG' THEN 0
                ELSE 1
  END ASC;
  -- ,ID ASC -- if needed

LiveDemo


text:
Q: In Maven, how do I make the version of my build use the version of one of its dependencies? I'm building a helper library for an external dependency. How can I make the version of my build take from the version of the external dependency?
  <groupId>com.foo</groupId>
  <artifactId>bar</artifactId>
  <version>???</version>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.external.dependency</groupId>
        <artifactId>bar</artifactId>
        <version>3.0.42</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

I want my library to build as 3.0.42 as well to reflect that it's a helper for that version (and possibly some older versions) of that external dependency.

A: You can either follow @Thorbjørn's suggestion to use ${project.version} in the dependency tag.
Alternatively, you can define a property <revision> in the properties section of your POM (note that the name is important, don't try another property name) and define both the <version> in the project and the library as ${revision}.
The second approach requires a reasonably new Maven version (like 3.5.x or 3.6.x).


text:
Q: Getting results between dates in PHP/MySQL I am trying to get all rows from a database that was added between 5 and 10 minutes ago.
Here is what I have tried:
$query9 = mysql_query("SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 5 minute) AND date_sub(now(), interval 10 minute);");

$onlineUsersLast10Mins = mysql_num_rows($query9);

Despite having data in the database from 6,7,8 and 9 mins ago, this script is not picking it up. Where am I going wrong?
for info, dates are stored as a timestamp in the usual format yyyy-mm-dd hh:mm:ss

A: The semicolon at the end of your query BEFORE the last double quote needs to be removed:
$query9 = mysql_query("SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 10 minute) AND date_sub(now(), interval 5 minute)");

This should work.

A: Let's take a look at BETWEEN's documentation.
BETWEEN works with an interval, but if you take a look at this official example:

mysql> SELECT 2 BETWEEN 1 AND 3, 2 BETWEEN 3 and 1;
-> 1, 0

you will see that 2 is between 1 and 3, but 2 is not between 3 and 1. So, if the right side is bigger than the left side, like in the second case where 3 is the left and 1 is the right, then your element will not be between them.
So, 2 is between 1 and 3, but 2 is not between 3 and 1.
Let us take a look at your query:
SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 5 minute) AND date_sub(now(), interval 10 minute);

The left side contains the moment earlier than now with 5 minutes and the right side contains the moment earlier than now with 10 minutes. So, the right side is actually earlier (smaller) than the left side. We need to see whether we have values between 10 minutes ago and 5 minutes ago, not the other way around :)
So, this should be the query:
SELECT * FROM user_actions  WHERE timestamp BETWEEN date_sub(now(), interval 10 minute) AND date_sub(now(), interval 5 minute);


text:
Q: SQL Server column design I always tried to make my sql database as simple and as understandable as possible.
Until now I always used a limited number of columns, I think I never had more than 20. Now, there is one thing, that would make my life easier, if I had much more columns. Let´s say 200 columns. (not rows). What do you think about it?
I just want to know, if it is a bad idea, not why i´m doing this or if there are other possibilities, just if somebody has already experienced something like that and if it is a bad idea to do such a table.

A: Fewer, smaller width columns is better than lots of columns and/or large width columns.
Why? Because the narrower the row size, the more rows you fit on a 8K page. That means you do less I/O and use less memory to buffer pages. That is always a good thing.
In those (hopefully) rare cases, where the domain requires many attributes on an object (with the assumption of 1-1 object-table mapping), you should consider splitting into two tables ina  1-1 relationship, one containing the frequently used columns.

A: I don't think it is black and white. Having a large row size (implied by the large number of columns) will hurt performance (i.e., more I/O) -- but there are cases where taking a small hit in performance in one place will be offset by increased performance in others.
I'd say it depends on how many rows you expect this table to have, how often will it will be queried, how many of those additional columns will really be accessed, and how it would compare to your alternative design in terms of efficiency and complexity.

A: Luke--
It really depends on the type of the system you are working with. Example in transactional systems, most tables have at most 50 columns or so with almost no redundant data attrributes ( If you have a process date, you would not need the Process Month or the process year as a seperate column). This of course is because the records are updated/inserted frequently and you'll need to update all the redundant attributes everytime you update one row.
In Data Warehouse/reporting environments, for Dimension tables (which have the attributes for an entity) it is typical to have 100+ columns as there are could be various ways you want to categorize a given entity.The Updates here are not so much a problem as data is typically loaded once during off-peak hours and then is used mostly in selects.
Take a look at these links to know more..
http://en.wikipedia.org/wiki/Database_normalization
http://en.wikipedia.org/wiki/Star_schema
So the answer is it depends... If you want a perfectly relational system, then may be 200+ columns is kind of a red flag indicating you should look at normalize your data (May be not). Updates and Indexes are two things that you should be concerned with in such a system.

A: You are using SQL Server, which I think defaults to row-oriented storage (all fields in a row are stored together in a page), which can be a problem with large number of columns.  However, if you use column-oriented storage, the number of columns per table does not matter because each column is stored together. I don't know if this is possible with SQL Server.


text:
Q: IE 11 "An error has occurred in the script on this page" at the end of the line I am trying to test a legacy web site originally intended to work on IE8 in IE11.
I get an error as "An Error has occurred in the script on this page." on my code when accessing the page on IE11 (it works fine on IE8). The line number stated here is the last line of clientCXMLDocument.js file and I don't see any issue in that code that would case the issue.

On IE11 in Internet Options, if I uncheck "Disable script debugging (Internet Explorer)", I no longer get the error but I would be more interested to know what is causing the error.

A: There are a lot of API featured removed and replaced in IE11 as listed in this documentation:
https://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx
For example, the use of document.selection will no longer work in IE11 so your javascipt code may contain some of these and use the corresponding replacements.
In the meantime while you are fixing the code, you might want to use the IE X-UA tag to specify the IE8 legacy document mode
<meta http-equiv="X-UA-Compatible" content="IE=8" />


text:
Q: What is the super fast and prefered way for two code bellow? My code get all online people from server
But I just need just those online people that I have in my contact list.
there I have two way:

*

*having two nested loop to comare all online people with those online people I have in my conact list and then just add online people of my contact list to an Object in my App. code is below:

people = {};
myContacts = [...];
this.socket.on('online', users => {
    for (let i = users.length - 1; i >= 0; i--) {
         for (let j = myContacts.length - 1; j >= 0; j--) {
             if (myContacts[j].userid === users[i]) {
                this.people[myContacts[j].userid] = 'online';
             }
        }
    }
   this.setState({refresh: !this.state.refresh});
});

*having just one loop and adding all online people to an object in my App. code is below:

people = {};
myContacts = [...];
this.socket.on('online', users => {
    for (let i = users.length - 1; i >= 0; i--) {
         this.people[users[i]] = 'online';
    }
   this.setState({refresh: !this.state.refresh});
});

Now my question is: What is best way which of the above number you prefer me for having a good performance and a fast job during using the App.
**Note: Why I am worry about this although both of them works well, you think there is 10000 people online at the same time.
Here may you tell me second one is better because there is one loop,
but I am confusing if we have 10000 people online on that time we will have 10000 people in the Object and accessing online people we need from the object by username may take a long time.
But in first code getting people take much time because we have two loop and comparing them but accessing within the app will be easy because we just have those online people are in my contact list.**

A: IMHO browser's native includes() (applied to bigger array) method should be the fastest one:
for (let j = myContacts.length - 1; j >= 0; j--) {
  this.people[myContacts[j].userid] = users.includes( myContacts[j].userid ) ? 'online' : 'offline';
}

you can also store only a boolean value
for (let j = myContacts.length - 1; j >= 0; j--) {
  this.people[myContacts[j].userid] = users.includes( myContacts[j].userid );
}

and render conditionally what you need (translated message, icon, etc.)

A: if you really want to only show online people who are in your contact list, I think you can turn myContacts array into a key/value object {...}. Key is userID and value is boolean (true: online, false: offline). That would help to speed up performance a bit


text:
Q: Changing color programmatically in a for loop does not refresh on the screen I am new to Android development. I am currently building an application that must flash different colors when a button is clicked. When the button is clicked I call a function. This function loops through a list of items and basically at the moment attempts to show blue and green after each other a couple of times. Problem is that it only shows the last color. And this only happens when the thread has exited the method. In the example below it is blue. I have noticed with some of the work I have done that screen changes reflects once the program have left the current method where the loop occurs and sometimes even longer after that. Below is the code :
   //Method that sets the color

   public void SetVisualLayoutColor(int Color)
    {
        linearLayout.setBackgroundColor(Color);
        linearLayout.invalidate();
        linearLayout.refreshDrawableState();
    }

    //Method that loops and calls above method to set color
   public boolean ShowRepititive()
    {

        boolean successfull = false;

        try
        {
            boolean isGreen =  true;

            //for (TimingItem timingItem : items) {
            for (int i=0;i<=10;i++) {
                if (isGreen) {
                    SetVisualLayoutColor(Color.BLUE);
                    isGreen = false;
                } else
                {
                    SetVisualLayoutColor(Color.BLUE);
                    isGreen = true;
                }

            }

            successfull = true;

        } catch (Exception e)
        {
            Log.e("Repeating Flash", "showFlashRepititive: ", e);
            successfull = false;
        }

        return successfull;
    }

Is there some way to get past this or to force the changes to occur timeously ?
Thank you in advance.

A: Unless you explicitly run your code on a different thread, the code you write in an Activity, Fragment, or View will run on the UI thread.
When you are performing work on the UI thread, the UI cannot update. The UI only updates after your code has finished executing. Thus your for loop blocks any UI updates until it completes, showing the last color you set.
A more appropriate pattern to use would be to use an animation to change the color
Here is an example of a very basic animation that does a cross-fade between two background colors:
ObjectAnimator.ofObject(view, "backgroundColor", new ArgbEvaluator(), 0xFF0000, 0x00FF00)
    .start();

Obviously this won't achieve the flashing effect you are looking for, but you can define your own animations in a similar manner to achieve the desired effect.

A: As Tanis.7x said, you can't create the desired animation while your code is executed in the main thread. All potential solutions have to have a background Thread and a way for it to communicate with your UI thread. (see AsyncTasks,Threads,Handlers)
An alternative to ObjectAnimator that can work in your specific case is TransitionDrawable. It's not that powerful but if it suits your needs, it's preferable since it's API 1 compatible:
You need to store a transitioncolors.xml in your drawables folder with your transition definition:
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/green"/>
    <item android:drawable="@color/blue"/>
</transition>

and then call:
 ImageView view = (ImageView) findViewById(R.id.transitionId);
 view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     TransitionDrawable transition = (TransitionDrawable) v.getBackground();
     transition.startTransition(3000);
 });

where R.id.transitionId is:
<ImageView
    android:id="@+id/transitionId"
    android:background="@drawable/transitioncolors"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

A: I did some more research after I read Tanis.7x and Sevle's post, which put me in the right direction. For some reason the Object animator did not worked when I ran it and the Transition does not give me the flexibility I wanted. So I came across the ValueAnimator, which worked perfectly for me. I created my own class that extended the ValueAnimator and within the class I control how long each animation must be and also other aspects like running indefinitely until the user interrupts it on the screen. Thanks a lot guys, I really appreciate the help.


text:
Q: Tracking chained usage in huge legacy C codebase with Frama-C I have huge (65 mln. lines of C code) legacy codebase.
Need to track usage of single cpp numeric const (#define MAX_NUM 32) which is used to define a number of structs (struct a { ... int a[MAX_NUM]; ... };), which in turn used to define fields in other structs, which in turn... at least 4 levels of usage of this kind.
Structs in turn are used to define other consts (like #define SIZE_A sizeof(struct a))
Structs are also used to define function params.
Obviously functions use these structs to access their fields in function implementations.
And functions are called with params of these structs types.
And so on...
Could I track all this forest of chained usages with Frama-C?
Tried to track these usage chains manually - oh my, 65 mln lines of code...
Tried to understand Frame-C usage for static usage analysis - too many docs to understand at a single glance...

A: Frama-C does not have its own C preprocessor, it uses the system's preprocessor.
This means that the Cil (normalized) code seen by Frama-C is the version after preprocessing. Thus #define macros are not directly seen by Frama-C; the MAX_NUM constant in your example does not exist in Frama-C's AST. If it were an enum, then it would be present.
Concerning the type definitions, however, they are present in Frama-C's AST, and the graphical interface's Information panel does display type information, e.g. if you select an expression the AST, it will show its type, with clickable links to further expand type definitions, recursively. The screenshot below shows an example: a variable has a type ADC_parameters_t, which is a struct containing (among others) a field channel_t, which is in fact just a uint_least8_t, defined in header su_ctrl.h, line 146.
This code of code navigation (plus jumping from function calls to definitions, and back to callers, etc) is easy to do in Frama-C. But there is currently no way to directly navigate from a given macro/constant to all of its uses.

If you don't need Frama-C's semantic analyses, but only a powerful syntactic exploration and navigation tool, maybe SourceTrail (which has unfortunately been discontinued) could help you. It is a syntactic analysis and navigation tool which does know about preprocessing symbols, and can thus show places of definition, as in the example below:


text:
Q: Back button doesn't work if question is too long If I open a question and the question title is too long, then the back button doesn't work and the only way to use the app again is to restart it.

*

*App Version: 1.4.5

*Device: iPhone 5s (Global)

*OS Version: Version 10.0.2 (Build 14A456)


text:
Q: How to save Android edit text content with rich text I have an EditText where users can set text to bold, italic, etc but I can't figure out how to save that text with styles as .txt file/any other way to save it.If we save as HTML page we can't edit the webview. I use getText but that only returns text and no style info.

A: I think the best way would be, if you build an own class, which handles the styles. I think, if its a EditText and you can say, part of the text should be bold, so you save something like "10.20.b|" into a temporary var. Later you can handle your styles, parsing the styles-var, split it by "|" and analyze the "10.20.b" which would mean something like "position 10 to position 10+20 is bold".
To save it, use XML for example, like:
<?xml version="1.0" encoding="utf-8"?>
<styles>0.4.b|6.2.i|</styles>
<text>This is a wonderful text! OH MY GOD!!!</text>

This would produce:

This is a wonderful text! OH MY GOD!!!


text:
Q: RDS does not issue CALs on Windows Server 2012 Essentials I'm trying to get RDS services running on a clean install of Windows Server 2012.
I followed this example http://support.microsoft.com/kb/2833839?wa=wsignin1.0
The licensing server is activated, and CALs installed OK.  Nothing is reporting errors.
But when a users tries to log in, the system does not issue a CAL.
Only the 2 administrative sessions are allowed.
The machine is a AD DC, but doesn't need to be.  This server was intended to run in an isolated environment (of 1 server only) for users to log on and run our suite of applications.
What am I doing wrong, or what options do I have?  I know hardly anything about Windows Servers.

A: You can not install RDSH or Hyper-V on Windows server 2012 Essentials.
It's also dangerous to allow non-administrative users to remotely access an domain controller.


text:
Q: VBA Lotus DB Search - Get folder/view name of current document i am trying to write a VBA code to search Lotus DB based on keywords and then extract the results details into another Sheet.
Although i am able to pull multiple fields as needed, i would also need the 'Folder' name / View name to which the current document belongs to. I have tried searching for all available fields but still unable to find any. Any help please?
Set notesdb = NotesSession.getDatabase(Servr, Dbase)
DteTime = ((DateAdd("n", ThisWorkbook.Sheets("Main").Range("E15").Value, Now())))

If notesdb.IsOpen = True Then
    'Already open for mail
Else
    notesdb.OPENMAIL
End If

Set GlobalCollection = notesdb.Search("@Created > [" & DteTime & "] " & " & @Contains(" & "Subject" & ";" & """" & Subjct & """" & ")", Nothing, 0)

Set AllDocc = GlobalCollection.GetFirstDocument

While Not (AllDocc Is Nothing)
    LastRow = Sht.Cells(Sht.rows.Count, "A").End(xlUp).Row
    roww = LastRow + 1
    Sht.Range("A" & roww) = AllDocc.GetItemValue("SendTo")(0)
wend

A: This information is not easily available. A folder / view KNOWS which documents it contains, but a document does not know in which folder / view it is shown.
A document can be in many folders and views. One single mail can be in multiple folders, will allways be shown in "all documents" view and if it was sent it will eb shown in "Sent" view. If you enable a followup it will be in the followup view as well...
There are multiple ways to get that information: you could run through all views, then through all documents in them and then check if your document belongs , then remember the names of all folders / views the document is in.
OR you could enable "Folderreferences" in the database. Then each document will contain the UNIVERSALID of every folder it belongs to, you just need to assign these UNIDS to readable foldernames. Unfortunately this feature does not work for documents that were put in the folders BEFORE the property had been enabled... not a perfekt match either...
So: unfortunately this is not done easily and needs a lot of code to write, and even more code, to do it quick for many documents...


text:
Q: DolphinDB: How to delete all the records in the middle of the table? When I use DolphinDB, I wonder that if there are 3 or more consecutive identical records in both the a and b columns of the table, how can I delete all the records in the middle?
For example:

A: You can use the following methods:
select * from t where (x -> x == 1 or (next deltas x) < 0)(segmentby(x -> 1..size(x), a, a)) and (x -> x ==1 or (next deltas x) < 0)(segmentby(x -> 1..size(x), b, b))

or
select * from t where each(def(x,y): x==1 or x==y, segmentby(x -> 1..size(x), a, a), segmentby(size, a, a)) and each(def(x,y): x==1 or x==y, segmentby(x -> 1..size(x), b, b), segmentby(size, b, b))


text:
Q: How can a multi-property ndb query be successful without a composite index? I have this entity model:
class ApartCILabel(ndb.Model):
    project_id = ndb.IntegerProperty(indexed=True)
    changeset_ids = ndb.IntegerProperty(repeated=True, indexed=True)   # ApartCIChangeset IDs
    # other properties

I recently added a new type of query for these entities:
            keys = ApartCILabel.query(ApartCILabel.project_id == self.db_data.project_id,
                                      ApartCILabel.changeset_ids == self.key_id).fetch(keys_only=True)
            if keys:
                label = Label(db_key=keys[0], handler=self.handler)
                logging.debug('label found: %s' % label.name)
            else:
                logging.error('label for %s not found' % self.lid)

I knew I needed a composite index for it, so I ran the app in dev_appserver.py, which used to automatically update my index.yaml file. I see the debug message in the log, indicating that the query was successful:
DEBUG    2018-02-20 23:56:11,720 ci_changeset.py:70] label found: ACI_COPY_OF_SMALL_180221_1

To my surprise, I see no update in my index.yaml file. OK, I did update my GAE SDK since the last time I needed an index update (running 1.9.65 now), maybe the symlink-based scheme I'm using for sharing my index definition file across all my services interferes somehow. No problem, I'm gonna deploy the change on GAE and I'll see the missing composite index error there.
Again surprise: the query is successful, no error.
I checked my index.yaml file, the only composite index for this kind is this one:
- kind: ApartCILabel
  properties:
  - name: project_id
  - name: created
    direction: desc

I double-checked the datastore indexes in the developer console, which is, as I expected, in sync with the index.yaml file:

I even performed a manual query in the developer console, which should also require a composite index. Also successful:

How is it possible for such query to function without a composite index? What am I missing?
UPDATE:
After a few hours I performed another similar manual query, again the result is correct, but this time the Your Datastore does not have the composite index (developer-supplied) required for this query. error (or should I rather call it warning?) showed up:

A: Queries using only equality filters do not require a composite index to be created.  From the documentation:

Cloud Datastore provides built-in, or automatic, indexes for queries of the following forms:

*

*Queries using only ancestor and equality filters

https://cloud.google.com/datastore/docs/concepts/indexes#index_configuration


text:
Q: What are these weird Postgresql connection attempts on my Heroku app? We updated our database from Hobby to a paid one (50$/mo).
We're constantly seeing these weird connection attempts (it's being logged hundreds of times daily), one after another (like 100 attempts in 5 seconds, and then a delay)

153XXX7XXXX   2022-12-07 11:XX:XX 2022-12-07
11:XX:XX  130057XXXX  appname 3.227.75.243    Local0  Error   app/postgres.209796 [GREEN]
[9-1]  sql_error_code = 28000 time_ms = "2022-12-07 HIDDEN UTC"
pid="25283" proc_start_time="2022-12-07 HIDDEN UTC"
session_id="639HIDDEN" vtid="6/35726" tid="0" log_line="2"
database="postgres" connection_source="159.HIDDEN(35786)"
user="postgres" application_name="[unknown]" FATAL:  no pg_hba.conf
entry for host "159.HIDDEN", user "postgres", database "postgres",
no encryption

We have connection_logging and lock_waits enabled in the dashboard, but I don't think that's it.

Our app is a webserver written in Go. We're also directly connected through Jetbrain's DataGrip from our PC.
Is that connection attempt something default to Heroku?


text:
Q: How to convert XML empty tag This might sound strange but I need to convert all empty tags to a pair of open and closing tag with a carrage return in between. Thanks in advance.
From
<OBR>
<OBR_31_Lab_Ins_Typ_Id>L</OBR_31_Lab_Ins_Typ_Id>
<OBX>
<OBX_3_Ltt_Cd>N877</OBX_3_Ltt_Cd>
<OBX_5_1_Lbr_No>0</OBX_5_1_Lbr_No>
<OBX_5_2_Lbr_Tx/>
<OBX_6_Lbr_Unt_Tx/>
</OBX>
<OBX>
<OBX_3_Ltt_Cd>N878</OBX_3_Ltt_Cd>
<OBX_5_1_Lbr_No>-15</OBX_5_1_Lbr_No>
<OBX_5_2_Lbr_Tx/>
<OBX_6_Lbr_Unt_Tx/>
</OBX>
<OBR>

To
<OBR>
<OBR_31_Lab_Ins_Typ_Id>L</OBR_31_Lab_Ins_Typ_Id>
<OBX>
<OBX_3_Ltt_Cd>N877</OBX_3_Ltt_Cd>
<OBX_5_1_Lbr_No>0</OBX_5_1_Lbr_No>
<OBX_5_2_Lbr_Tx>

</OBX_5_2_Lbr_Tx>
<OBX_6_Lbr_Unt_Tx>

</OBX_6_Lbr_Unt_Tx>
</OBX>
<OBX>
<OBX_3_Ltt_Cd>N878</OBX_3_Ltt_Cd>
<OBX_5_1_Lbr_No>-15</OBX_5_1_Lbr_No>
<OBX_5_2_Lbr_Tx>

</OBX_5_2_Lbr_Tx>
<OBX_6_Lbr_Unt_Tx>

</OBX_6_Lbr_Unt_Tx>
</OBX>
<OBR>

A: Use:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*[not(node())]">
    <xsl:copy>
      <xsl:text>
</xsl:text>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

A: you could use a regular expression like this:
s/\<([a-zA-z0-9-_]+(\s+[a-zA-z0-9-_]+=".*?")*?\s*\/\>/<$1>\n\n<\/$1>/g


text:
Q: Multiple `if` conditions with `jq` and `grep` incorrectly matches and returns true when it shouldn't match at all I have a json file:
cat myjsonfile.json

{
    "directory": true,
    "condition": "",
    "specialCondition": "",
    "dataFiles": "",
    "nonstandard-protocol": true
}

specialCondition is standardized and can be empty or have a matched or unmatched state.
I simply want to translate those conditions to another state when nonstandard-protocol is false.
So I wrote this in my bash script.
if [[  "jq '.specialCondition' myjsonfile.json | grep -q 'matched'"  &&  "jq '."nonstandard-protocol"' myjsonfile.json | grep -q 'false'"  ]]; then echo 'MATCHED' | cat > protocol_result.txt; fi
if [[  "jq '.specialCondition' myjsonfile.json | grep -q 'unmatched'"  &&  "jq '."nonstandard-protocol"' myjsonfile.json | grep -q 'false'"  ]]; then echo 'NOTMATCHED' | cat > protocol_result.txt; fi

However, this returns incorrect results. When I run the script, I always see that first it writes MATCHED to my protocol_result.txt and then with the second if line it writes NOTMATCHED to the file! While it shouldn't write anything at all... Why is this happening?

A: Take the if statements to jq and have it output whatever you want.
The following example prints nothing "" if nonstandard-protocol is true, or specialCondition is neither matched nor unmatched. Otherwise it'll print MATCHED or NOTMATCHED, depending on the content of specialCondition:
jq --raw-output '
  if ."nonstandard-protocol" then ""
  else if .specialCondition == "matched" then "MATCHED"
    elif .specialCondition == "unmatched" then "NOTMATCHED"
    else "" end
  end
' myjsonfile.json > protocol_result.txt

Demo
Note: Using "" will print nothing as expected, but followed by a newline because it had an output (which essentially is an empty line, then). If you don't want that, change "" to empty.

A: You need to actually execute your grep command, if you need its status code:
if jq .specialCondition myjsonfile.json | tee protocol_result.txt | grep -q matched  &&  jq '."nonstandard-protocol"' myjsonfile.json | tee -a protocol_result.txt | grep -q false
then
  .....
fi


text:
Q: Altium STEP Models Aligning Underneath Board I'm trying to import a STEP model for a uFL connector and it's oddly misaligned beneath the board (see "3D uFL PCB" image attached). I've tried rotating it every which way but I cannot fathom how it wouldn't just align itself on the footprint. Photos attached. How do I get it to move up vertically onto the same top layer plane as the PCB?

A: You're at the mercy of the origin defined by whoever designed the 3D model. Use the "Standoff Height" to adjust the height between the board and 3D model.

A: You can use Tools->3D Body Placement->Align Face with Board and click on the face of the 3D model you want to sit on the board.


text:
Q: How to use the output we see of expression when this expression is inside Dynamic Consider this example:
Manipulate[status = Dynamic[If[a < b, Yes, No]], {a, 2}, {b, 5}]

The output of this calculation is
(*Yes*)

when I call status again I get Yes as expected.
No when I want to used the output of status in further calculation I failed. I tried to do the following:
status === Yes

the results is False
The full form of status is not what is seen in the output.
My question is, how to use the output of expression no matter what the definition of that expression is.
(Note: status[[1]] does not help because the level of the output is unpredictable)
Thank you.

A: (status /. Dynamic -> Identity) === Yes
(* True *)

A: If you  want the value of status outside of the Manipulate to be updated whenever it changes inside the Manipulate, just drop the explicitDynamic`.
 Manipulate[status = If[a < b, Yes, No], {a, 2}, {b, 5}]
 Dynamic[status === Yes]

The Manipulate will still work as it did before the change, and the second expression will track the changed to status made inside the 1st.


text: Q: Hessian-Matrix of a Determinant Let $f:\mathbb{R}^{n}\rightarrow \mathbb{R}$ be a polynomial function and let $H_f(x)$ denote its Hessian. Now define $p:=\det(H_f(x))$. Is there a nice way to relate the Hessian of $p$ i.e. $H_p(x)$ with the Hessian of $f$?


text:
Q: How to get links from an opened IE page How can I control an IE page that is already opened, for which I only have the handle?
The following code retrieves the links from a web page. I want to do the same, but I only have the handle from IE, because the page is already opened.
How can I do it?
Var
  I, n : Integer;
  IEApp: OLEVariant;
begin
  if(VarIsEmpty(IEApp))then
  begin
    IEApp := CreateOleObject('InternetExplorer.Application');
    IEApp.Visible := true;
  end;
  IEApp.Navigate('www.google.com');
  while Cardinal(IEApp.readyState) <> 4 do sleep(1000);
  n := Cardinal(IEApp.Document.links.length);
  for i := 0 to n - 1 do
    Memo1.Lines.Add(string(IEApp.Document.links.item(i).href));


text:
Q: How to download file - lightning component I developed custom files section using lightning components.
I am trying to download file from ligtning component, but not able to find solution.
Piece of component code:
 <aura:attribute name="Baseurl" type="String" />

Download

Controller.JS
downloadfile : function (component, event, helper){
    var id = event.target.getAttribute("data-id");
    alert('Document ID:' +id);
    var actiondownload = component.get("c.DownloadAttachment");

    actiondownload.setParams({
        "DownloadAttachmentID": id
    });

      actiondownload.setCallback(this, function(b){
        component.set("v.Baseurl", b.getReturnValue());

    });

Apex COntroller
     public static string DownloadAttachment(Id DownloadAttachmentID)
   {
    ContentVersion oldCV = [Select Id,Title,Locked__c,Locked_By__c from ContentVersion Where ContentDocumentId=:DownloadAttachmentID and IsLatest = true ];
    System.Debug('Old LV INitial :'+ oldCV.Id);
    System.Debug('Old Lock :'+ oldCV.Locked__c);
    String fullFileURL = URL.getSalesforceBaseUrl().toExternalForm();
    String URlDownload = fullFileURL+'/sfc/servlet.shepherd/version/download/'+oldCV.Id;
    system.debug('Download URL:' +URlDownload);
    return URlDownload;
    }

Below is the piece of code used in classic salesforce
pagereference newTab=new pagereference('/sfc/servlet.shepherd/version/download/'+oldCV.Id+'?asPdf=false&operationContext=CHATTER');
        newTab.setRedirect(true);
        return (newTab);

i cannot use "pagereference" in @auraenabled. Is there any other option to download files from Apex controller ?
Thanks.
Best Regards
Visu

A: After the discussion in the comments of the question, here is how you can use navigateToURL event. Update your setCallBack to this.
actiondownload.setCallback(this, function(b){
        component.set("v.Baseurl", b.getReturnValue());
var urlEvent = $A.get("e.force:navigateToURL");
    urlEvent.setParams({
      "url": b.getReturnValue()
    });
    urlEvent.fire();
}


text:
Q: Generating PDF Reports with Pentaho User Console 9.0 I have Pentaho Server 9.0 installed on a Linux CentOS 7 VM, I have created some reports in Spanish and publish them into my server.
When I run the reports on the server,requesting a PDF document as output, it deletes all the accented vowels (á, é, í, ó and ú). When I run the report directly on Report Designer it works fine. And when I run the report on the server with HTML output its displayed correctly.
I already read forums with this kind of problem in past versions but their solutions are already applied or are inefficient.
Does anyone know how to solve this problem or have any ideas on how to solve them?

A: Found the solution.
The problem was that the font used in the report wasn't installed on the system.
The problem was solved by copying the TTF file in $JRE/lib/fonts where $JRE is the path your java runtime enviroment is installed.


text:
Q: How to define type to choose one but not another - TypeScript I would like to define the type so that TS knows that when I define one variable, another will be undefined
interface Fruits {
    apple: string,
    strawberry: string
}

type ExtraFruits = Fruits & ({
    banana: string;
    kiwi: undefined;
} | {
    kiwi: string;
    banana: undefined;
})

and when I'm using ExtraFruits interface like this:
const {apple, strawberry, kiwi, banana} = fruits <--- fruit is ExtraFruits type

const selectedFruit = kiwi ?  kiwi :  banana

TS think that kiwi is possibily undefined but in this configuration it is not


text:
Q: Python telnetlib read_until spams my server I'm using telnet lib to read from an Telnet server.
my code looks like this:

 s = telnetlib.Telnet(self.host, self.port)
 while 1:
     line = s.read_until("\n")
     print(line)

this is working fine so far, but as i have a look on the network traffic i can see tons of packets between client and server. If i use raw socket, this is not happening.
packets on the network are nearly empty. I Guess this is a pull for next charakter
Has anybody an explanation for this? I don't whant to spam my telnet server but i like the idea of the read_until mechanism since i can get line by line.
thanks!

A: It seems that your Telnet server works in non-buffered mode (sends not the entire line, but rather each symbol in a separate packet). You probably need to change you server settings so it can work in a buffered mode.
Also, you may see:

*

*a lot of packets from telnet client back to server. These are echos of all commands and it's pretty normal

*Small packets with new line symbols like \n\n\r
EDIT:
Another possible cause is polling, you may try this:
import sys
import select
del select.poll
import telnetlib

tn = telnetlib.Telnet('10.32.137.39', 3008)

while 1:
    line = s.read_until("\n")
    print(line)

To say something more specific it would be great to see Wireshark trace of the traffic

A: Solved it by using:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
for i in s.makefile('r'):
    print("FOO " + i)


text:
Q: Always-on-top header I want to add a always-on-top header like the new twitter does.
Explanation: When the user scrolls down the page, I want the header to stay on top of the window.
Somebody know a script that does that? Or can target me how can I do it?

A: You can use position: fixed; on the header.
<div id="header">
content goes here.
</div>

and the CSS:
#header { position: fixed; z-index: 9999; top: 0; left: 0; }

A: You need to give your header a position of fixed to make it visible throughout the page. And set the top value appropriately along with width.
Example:
#header{
  position:'fixed';
  top:0;
  width:800px;
}

A: Use position:fixed on the header in its CSS.
Also, dont forget to set the left and top attributes to where you want it to go :)


text:
Q: Java and Heroku I got my Java server deployed on Heroku. Im creating a server socket there and I can not find the way to set the PORT for this. I kinda see in Heroku logs a PORT that it gives me, but I dont know how to use it in my code. Thank you.

A: here is how you can do it
    public int getPort() {

    String port = System.getenv("PORT");

    if (port == null || port.isEmpty()) {
        port = "8888";  // default
    }

    return Integer.valueOf(port);
}


text:
Q: Почему указатель равен NULL? Видимо ответ крайне прост, но...
Есть файлы 1.cpp и 2.cpp, в файле 1.cpp:

void Fun(){
  double *Arr;
  Arr=NULL;
  GetTable(Arr);
}

в файле 2.cpp:

double * GlobalTable=new double[10];
void GetTable(double * Table){
Table=new double[10];
    CopyMemory(Table,GlobalTable,10*sizeof(double));
}

В итоге вызова ф-ции GetTable(), указатель Arr всё равно равен NULL! ПОЧЕМУ!?
A: Передавать надо не указатель, а указатель-на-указатель.
void Fun()
{
  double *Arr;
  Arr=NULL;
  GetTable(&Arr);
}

double * GlobalTable=new double[10];
void GetTable(double ** Table)
{
    *Table=new double[10];
    CopyMemory(*Table,GlobalTable,10*sizeof(double));
}

A: void GetTable(double *& Table)
{
    Table=new double[10];
    CopyMemory(Table,GlobalTable,10*sizeof(double));
}

также можно передавать не по значению а по ссылке, указывая & в параметре функции


text:
Q: Digipot for DC motor I am going to use a 3V DC motor (operating voltage 1.5 to 4.5V DC) and MSP430G2553 microcontroller. So which digital potentiometer should I use to control the speed of the DC motor?

A: Digital potentiometers are designed to control low power signals that must be passed through a variable resistance, eg. the volume control in an audio amplifier. Most are only capable of handling 1~2mA, not nearly enough to power an electric motor which could draw several Amps.
Now that doesn't mean you can't use a digital pot, but you will need something to boost its output current. A bipolar transistor is the obvious choice, since it is a current amplifier. However it also has limitations. High power transistors generally have low current gain, so you will probably need at least two transistors to get enough gain. Also some voltage loss may occur due to biasing requirements.
Here is a circuit that uses an MCP4231-502 and an NPN and PNP transistor to control motor voltage at up to 3 Amps. The 2N4401's typical current gain (Hfe) is about 180 at 100mA collector current, and the TIP42's is about 30 at 3A, for a total of 180 x 30 = 5400. Therefore at 3A output current the load on the MCP4231 should be well under 1mA.

simulate this circuit – Schematic created using CircuitLab
One possible problem with this simple circuit is that bipolar transistors need about 0.6V between Base and Emitter to turn on; so Q1 won't turn on until the potentiometer gets up to 0.6V, and Q2 absorbs about 0.6V from the motor supply. As a result, this circuit can only supply a maximum of about 2.4V to the motor. If you need to control motor voltage over a wider range then a few extra components will be required.


text:
Q: How do I reinterpret the exponents (2^31, ..., 2^0) of an integer? I have a regular 32 bit Integer where the bits represent b31*2^31, b30*2^30, ..., b0*2^0 respectively.
Is there a way to decrease each exponent by 32, i.e. calculate b31*2^-1 + b30*2^-2 + ... + b0*2^-32 (similar to an IEEE Float mantissa) without having to extract the bits (e.g. using shifts or mod)?
E.g. for an 8 bit Integer, if input is 0010 1111 = 47 then output is 0 * 2^-1 + 0 * 2^-2 + 1 * 2^-3 + 0 * 2^-4 + 1 * 2^-5 + 1 * 2^-6 + 1 * 2^-7 + 1 * 2^-8 = 0.18359375.


text:
Q: My Python selenium code cannot select a select option I cannot select a select option using below Python code..
I have tried to refer many Q&A such as select, execute_script... but they are still not working.
enter image description here
import time
from selenium import webdriver

browser = webdriver.Chrome()

seoul_url = 'http://kras.seoul.go.kr/land_info/info/landprice/landprice.do'
browser.get(seoul_url)

time.sleep(1)

browser.find_element_by_xpath('//*[@id="sggnm"]/option[11]').click()

A: NEW
Or you can use ActionChains. In the code pos is the position of the option you want to select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

actions = ActionChains(driver)

def select_option(id_, pos):
    driver.find_element(By.CSS_SELECTOR, id_).click()
    actions.send_keys(Keys.DOWN * pos).send_keys(Keys.ENTER).perform()

select_option('#sggnm', 10)
time.sleep(1)
select_option('#umdnm', 3)

OLD
With this code you can change the currently selected option to the desired one without doing a click.
# webelement containing the currently selected option
option1 = driver.find_element(By.XPATH, '//*[@id="sggnm"]/option[1]')
# string with the text of the 11th option
option11 = driver.find_element(By.XPATH, '//*[@id="sggnm"]/option[11]').text
# replace the current option with the 11th option
driver.execute_script("var el = arguments[0]; arguments[1].innerText = el", option11, option1)

A: You have first click on dropdown and then click on the value that you wanted to select like below
Import
import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.WebElement

select the desire value
WebElement element = browser.find_element_by_xpath("//option[contains(text(),'동대문구')]"); // you can choose the value you want
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

A: My guess would be you cannot click the element as it is not visible.
To make it visible you must click the dropdown menu first as suggested by @Akzy
driver = webdriver.Chrome()

url: str = "http://kras.seoul.go.kr/land_info/info/landprice/landprice.do"

driver.get(url)

dropdown_element = driver.find_element_by_id("sggnm")

# Open the dropdown menu first
dropdown_element.click()

option_element = driver.find_element_by_xpath('//*[@id="sggnm"]/option[11]')

# Now the options are visible we want to click the option in the list
option_element.click()

This is untested (for this page) but should work for a generic webpage.
There are other ways of doing this such as sending the down key n times to the dropdown element get the nth option element.

A: from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pyautogui

driver = webdriver.Chrome()

url: str = "http://kras.gb.go.kr/land_info/info/landprice/landprice.do"

driver.get(url)
time.sleep(1)

def option_click(city):
    driver.find_element(By.CSS_SELECTOR, city).click()
    time.sleep(1)

def option_select(pos):
    i = 0
    for i in range(pos):
        pyautogui.press("down")
        i += 1

    pyautogui.press("enter")
    time.sleep(1)

option_click('#sggnm')
option_select(10)

option_click('#umdnm')
option_select(3)


text:
Q: Adjusting div according to size of the screen Hello I'm developing an multipages web based hybrid mobile application. I'm having problem with div I need the div to adjust based on browser. That is when I minimize or reduce the size of browser I need my div to viewed same but my below code makes all elements position one above another when I minimize.

#viep {
  position:relative;
  width:100vw;
  height:100vh;
  margin:0;
  padding:0;
}
#viep1 {
  position:relative;
  width:100vw;
  height:100vh;
  overflow:auto;
  margin:0;
  padding:0;
}
#placehere {
  position:absolute;
  top:5%;
  left:30%;
}
#placehere img {
  border-radius: 50%;
  max-width:100%;
}
#my1 {
  width:100%;
  position:absolute;
  top:35%;
  left:0;
}
.appButtons {
  position:absolute;
  top:80%;
  left:35%;
}

    ...
    ..

      <input type="button" id="buttonid" class="appButtons" value="Reportees">

A: Okay, you will need to define the viewport in your html documents with <meta name="viewport" content="width=device-width, initial-scale=1" />. In your CSS for your divs, try doing width: 100%. If you want something centered on your page, in your CSS add: margin: auto
Additionally, you can just use a framework like Foundation or Bootstrap which will make everything much easier for you. But it's always better to try learning it yourself first.


text:
Q: command line arguments make file So I know how to create variables and store values from command line.
But normally, I would type my command this way: make run VAR="abc", and VAR will be assigned the new value "abc"
However, if I want to do something like this VAR="abc" make run, how can I change my make file? Right now, if I run this, VAR still has the initial value when it was created in the make file.
This is my make file:
VAR = ""

.PHONY : build run

build : program.c
   gcc -o prog -g program.c

run : build
   ./prog $(VAR)

A: When you write VAR = "", you're overwriting any value VAR might have had (e.g. from the environment, or the command line). You can use a conditional assignment instead, which looks like this:
VAR ?= ""

This sets VAR only if it wasn't set already. It's equivalent to e.g.
ifeq ($(origin VAR), undefined)
  VAR = ""
endif

A: VAR = ${VAR}

if i remember right


text:
Q: SpriteKit physicsBody effect lost Firstly I added
skView.showsPhysics = YES;

To see physics body circuit.
BUT
I have a problem with loosing physics effect O_o...
I have ball which affected by gravity and falls down.
// Ball
self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.size.height/2];
        self.physicsBody.categoryBitMask = ballCategory;
        self.physicsBody.contactTestBitMask = bottomCategory;

Also I've created bottom edged physical body to get collision messages:
// Bottom edge
    CGRect bottomRect = CGRectMake(self.frame.origin.x, self.frame.origin.y + 25, self.frame.size.width, 10);
        SKNode* bottom = [SKNode node];
        bottom.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:bottomRect];
        [self addChild:bottom];

which correctly interacted with each other before I added bitMask to bottom edge
bottom.physicsBody.categoryBitMask = bottomCategory;
bottom.physicsBody.collisionBitMask = ballCategory;

Masks:
static const uint32_t ballCategory  = 0x1 << 0;  // 00000000000000000000000000000001
static const uint32_t bottomCategory = 0x1 << 1; // 00000000000000000000000000000010

It stopped work. Hm...
I commented out assigning mask to bottom edge - it works.
Then I assigned to bottom edge another - ball mask - it doesn't work again.
I guess, I missed something in documentation but now I can't find answer why it happens.

A: bottom.physicsBody.categoryBitMask = bottomCategory;

This makes bottom only contact/collide with bodies whose contactBitMask contains the bottomCategory bit.
So if you add this category to your balls they should collide with the bottom again:
ball.physicsBody.contactTestBitMask = ballCategory | bottomCategory;

For more details refer to the Box2D manual Chapter 7.2 - Filtering.


text:
Q: Prolog double period What does ".." mean in Prolog?
I have this code:
Goal=.. [GoalPredicate|Pos]

and I don't know what the ".." means

A: This operator is called "univ" and described in for instance the GNU Prolog Manual here:

8.4.3  (=..)/2 - univ
Templates
=..(+nonvar, ?list)
=..(-nonvar, +list)

Description
Term =.. List succeeds if List is a list whose head is the atom corresponding to the principal functor of Term and whose tail is a list of the arguments of Term.
=.. is a predefined infix operator (section 8.14.10).

Other good resources describing this operator:

*

*PROLOG 12.1  More Useful Features of PROLOG

*http://wwwcgi.rdg.ac.uk:8081/cgi-bin/cgiwrap/wsi14/poplog/prolog/ploghelp/univ


text:
Q: How can I add new fileds in database in an already running project in FastAPI I made an endpoint in FastAPI, I am uisng mongoDB as a database. Before that I used to work in django. In django if we added new fileds in model we run migrations and new fields were added in database table for every entry, my question is there a way to do this in FastAPI. I am using pymongo to interact with mongoDB.
I have a configuration file like this:
config.py
REALM_SETTINGS = {
    "clientname": "",
    "signupDate": "",
    "clientLogoUrl": "",
    "clientType": None,
    "disAllowedCons": [],
    "maxAllPools": None,
    "maxActivePools": None,
    "maxAllPoolsByType": None,
    "maxActivePoolsByType": None,
    "maxAllPoolProcessMins": None,
    "maxActivePoolProcessMins": None,
    "maxFilesByPool": None
}

These are not final values it may changes on client requirements. Lets say if the project is on production and client wants new values I added new values in file and want them to be added also in mongodb.
right now this is how I am doing it.
main.py
@router.get('/realm_settings')
async def get_realms_settings(request: Request):
    from crain.projectmgmt import settings_collection_exist, get_realm_settings, REALMSETTINGS, get_existed_records
    from crain.realm_settings import REALM_SETTINGS
    from crain.uma import realm_name
    user, _, _, _ = await _fetch_and_authenticate_user(request)
    existed_records = get_existed_records()
    if settings_collection_exist():
        existed_realm_settings = get_realm_settings()
        existed_realm_settings.update(existed_records)
        return jsonable_encoder(existed_realm_settings, custom_encoder={ObjectId: str})
    else:
        REALM_SETTINGS['clientname'] = realm_name
        REALMSETTINGS.insert_one(REALM_SETTINGS)
        REALM_SETTINGS.update(existed_records)
        return jsonable_encoder(REALM_SETTINGS, custom_encoder={ObjectId: str})

it will first check if collection exist because on first time there will be no collection so the document will be insert in to collection with default values and after when user login he/she will be shown the saved values.
My Solution:
Every time this endpoint is called I will match the keys in file and in already saved MongoDB document if there is any keys in config file but not in MongoDB I update document with new keys and send response to user.
Is this the best way to do this?


text:
Q: Maven check for updated dependencies in repository Is there a Maven plugin that allows you to check if there are newer versions of dependencies available in the repository?
Say, you are using dependency X with version 1.2. Now a new version of X is released with version 1.3. I'd like to know, based on the dependencies used in my project, which dependencies have newer versions available.

A: If you want to receive email notifications when newer artifacts versions are available on Maven Central you can create an account on artifact-listener and choose which artifact you want to follow.
You can either search manually for artifacts or directly upload your pom.xml.
You will periodically received notifications like this one (available in english and french for now) :

A: The Maven Versions plugin and it's display-dependency-updates mojo are what you're looking for:
mvn versions:display-dependency-updates

Here is what the output looks like:
[INFO] ------------------------------------------------------------------------
[INFO] Building Build Helper Maven Plugin
[INFO]    task-segment: [versions:display-dependency-updates]
[INFO] ------------------------------------------------------------------------
[INFO] [versions:display-dependency-updates]
[INFO]
[INFO] The following dependency updates are available:
[INFO]   org.apache.maven:maven-artifact ........................ 2.0 -> 2.0.9
[INFO]   org.apache.maven:maven-plugin-api ...................... 2.0 -> 2.0.9
[INFO]   org.apache.maven:maven-project ....................... 2.0.2 -> 2.0.9
[INFO]   org.codehaus.plexus:plexus-utils ....................... 1.1 -> 1.5.6
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17 seconds
[INFO] Finished at: Fri Aug 15 10:46:03 IST 2008
[INFO] Final Memory: 10M/167M
[INFO] ------------------------------------------------------------------------

A: You can use the Versions Maven Plugin[1] to generate reports in your Maven site to get a list of possible updates. With regard to Spring's irregularity, it appears to use the Mercury versioning system[2]. When configuring the Versions plugin, you can add a special rule for Spring stuff:

*

*http://mojo.codehaus.org/versions-maven-plugin/

*http://docs.codehaus.org/display/MAVEN/Mercury+Version+Ranges

A: In projects with a large number of dependancies, you sometimes keep your versions in a properties section.
    <properties>
        <assertj.version>3.15.0</assertj.version>
        <aws-sdk.version>1.11.763</aws-sdk.version>
        <cxf.version>3.3.6</cxf.version>

In the case where you are only interested in updates to those versions, you can use the following command
mvn versions:display-property-updates
This gives a more condensed view and only returns the versions you need to update in the properties section.

A: The VersionEye Maven Plugin is doing the same: versioneye_maven_plugin.
VersionEye can notify you about new versions on Maven Repositories, too. It is a language agnostic tool and beside Java it supports 7 other languages. Beside the simple follow/notify feature it can also directly monitor GitHub and BitBucket repositories and notify your about out-dated dependencies in your projects.

There is also a REST JSON API, for tool integrations.
By the way, I'm the dude who started this project. Let me know if you have questions.

A: The ideal way to do it is to set dependency versions as properties in pom.xml and then running the below command to get the updated versions for your specific/custom dependencies.
<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <skip.tests>true</skip.tests>
    <spring-cloud-gcp.version>1.2.3.RELEASE</spring-cloud-gcp.version>
    <spring-cloud.version>Hoxton.SR6</spring-cloud.version>
    <spring-cloud-stream-schema.version>2.2.1.RELEASE</spring-cloud-stream-schema.version>
    <confluent.version>5.5.1</confluent.version>
    <avro.version>1.10.0</avro.version>
    <janino.version>3.1.2</janino.version>
    <swagger.version>2.9.2</swagger.version>
    <google-cloud-logging-logback.version>0.118.1-alpha</google-cloud-logging-logback.version>
    <spring-cloud-stream-binder-kafka.version>3.0.6.RELEASE</spring-cloud-stream-binder-kafka.version>
</properties>

mvn versions:display-property-updates

[INFO] The following version properties are referencing the newest available version:
[INFO]   ${avro.version} .............................................. 1.10.0
[INFO]   ${spring-cloud-stream-schema.version} ................. 2.2.1.RELEASE
[INFO]   ${janino.version} ............................................. 3.1.2
[INFO] The following version property updates are available:
[INFO]   ${spring-cloud-gcp.version} .......... 1.2.3.RELEASE -> 1.2.5.RELEASE
[INFO]   ${google-cloud-logging-logback.version}  0.118.1-alpha -> 0.118.2-alpha
[INFO]   ${spring-cloud-stream-binder-kafka.version}  3.0.6.RELEASE -> 3.0.8.RELEASE
[INFO]   ${confluent.version} ................................. 5.5.1 -> 6.0.0
[INFO]   ${swagger.version} ................................... 2.9.2 -> 3.0.0
[INFO]   ${spring-cloud.version} .................... Hoxton.SR6 -> Hoxton.SR8
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.572 s
[INFO] Finished at: 2020-10-06T09:35:08-07:00
[INFO] ------------------------------------------------------------------------

Another way to achieve this is by executing the command mvn versions:display-dependency-updates but the problem I face with this approach is that it also shows me updates for the nested dependencies which are not too useful for me.

A: I might be a bit late to join the party but a more clear way to get more readable html file or a xml file as report which can be taken for further automation using:
mvn versions:dependency-updates-report

This report plugin not just shows more comprehensive details on updates but also has options to update to latest versions. You can find the  documentation for it to use various parameters.

A: You can use Maven Check, a command line tool, which is standalone unlike the Versions Maven Plugin. It also works with Gradle projects.
Output example:
2 build file(s) found, checking for artifact updates

my-gradle-project\build.gradle
[COMPILE ONLY] com.google.guava:guava 31.0-android -> 31.1-android
1 artifact update(s) available

my-maven-project\pom.xml
[DEPENDENCY] org.apache.commons:commons-lang3 3.10 -> 3.12.0
[BUILD PLUGIN] org.apache.maven.plugins:maven-compiler-plugin 3.10.0 -> 3.10.1
2 artifact update(s) available

2/2 build file(s) checked, 3 artifact update(s) available

Disclaimer: I am the author of Maven Check.


text:
Q: Couchbase: How to delete item from list based on child value? Couchbase 2.5+
New to couchbase here. I'm looking to delete an item from a list where one of the child items of it based on the value of the child items. For example if I wanted to delete all records in the list scores where the child score < 0.2
This item has a key of "dim::100020891::2020-10-04"
I thought of running this, but it's not working
UPDATE Q1036628 USE KEYS "dim::100020891::2020-10-04" SET scores=ARRAY_REMOVE(scores, {
      "score"< "0.2"
    })

Couchbase item:
   [
          {
            "Q1036628": {
              "record_update_dt": "2020-10-04",
              "scores": [
                {
                  "name": "A",
                  "score": 0.01
                },
                {
                  "name": "B",
                  "score": 0.5
                },
                {
                  "name": "C",
                  "score": 0.26
                },
                {
                  "name": "D",
                  "score": 0.17
                }
              ],
              "id": "100020891"
            }
          }
        ]

A: You should use the ARRAY clause.
UPDATE Q1036628 USE KEYS "dim::100020891::2020-10-04"
SET scores = ARRAY s FOR s IN scores WHEN s.score >= 0.2 END

https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/collectionops.html#array
You might need to play around with the syntax a bit; I don't have an instance handy.

A: Just add one more addition to Johan Larson solution.
WHERE clause controls what documents to mutate. SET clause controls what to update. You have condition in the SET clause. If there is NO objects in scores array has score < 0.2 still mutates (i.e it updates same value). To avoid that you need to have WHERE clause.
UPDATE Q1036628 AS d USE KEYS "dim::100020891::2020-10-04"
SET d.scores = ARRAY s FOR s IN d.scores WHEN s.score >= 0.2 END
WHERE ANY s IN d.scores SATISFIES s.score < 0.2 END;


text:
Q: Method in trait not able to be called from controller I'm trying to use a trait to handle image upload on my Laravel application, but none of the functions in my Trait can be called from the controller.
It throws a BadMethodCallException and says that the function couldn't be found.
I've tried using really simple functions to test if it is a problem with the trait or whether the function itself has an issue, but even a simple return function that only contains
return "sampletext";

has the same issue.
The path of the trait is under App/Traits/UploadTrait
and I've already checked the spelling on the use statement in my controller, which says use App\Traits\UploadTrait;
namespace App\Traits;

trait UploadTrait
{
    public function test(){
        return "testtext";
    }
}

And the controller has
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

use App\User;
use App\Profile;
use App\Traits\UploadTrait;

use Image;

class UserProfileController extends Controller
{
...
    protection function updateProfile($args, Request $request){
    ...
        return $this->test();
...

Of course I expect the function in my trait to be called, but this does not happen.

A: You need to use the trait inside your controller and move the $this->test() inside a class function:
<?php

use App\Traits\UploadTrait;

class UserProfileController extends Controller
{
    use UploadTrait; // <-- Added this here

    public function index()
    {
        return $this->test(); // <-- Moved this into a function
    }
}

A: You have to put the use keyword to use that trait and its methods in the class
trait UploadTrait
{
  public function test(){
    return "testtext";
  }
}

class Controller{

}

class UserProfileController extends Controller
{
  use UploadTrait;

}

$ob = new UserProfileController();
echo $ob->test();

You can make a function to and call the trait function.
More Details

A: Use trait inside the class like:
use my/path/abcTrait;
Class My class{
      use abcTrait;
}

Now, you can call trait functions with $this->functionName () in functions.


text:
Q: The service "fos_user.group_manager" has a dependency on a non-existent service "fos_user.entity_manager" I am using symfony 2.8 i want to configure sonata user bundle and fosUserbundle
beolw is my image link:
image

A: Try adding this in config.yml
fos_user:
    service:
        user_manager: fos_user.user_manager.default

You can check this official config reference: http://symfony.com/doc/current/bundles/FOSUserBundle/configuration_reference.html


text:
Q: Value Not Changing In my Project I am Checking some conditions if it is true the action will Occur otherwise the Error message will be shown in the Label during the runtime.
My problem is that when the condition fails the cursor goes to the else block and the code also get Excecuted but the text of the Label is not changed.What could be the Problem?
The Condition part is,
    if (ds.Tables[0].Rows.Count > 0
                && DateTime.Parse(frmtxtdt.Text).ToString("dd/MM/yyyy") == DateTime.Today.ToShortDateString()
                && DateTime.Parse(totxtdt.Text).ToString("dd/MM/yyyy")  == DateTime.Today.ToShortDateString())
            {
                ds.Tables[0].TableName = "Passkeys";

                ds.WriteXml(Server.MapPath("~/XMLReports/_Passkeys.xml"));
                string filename = Server.MapPath("~/Upload/Pkey_rpt.rpt");
                rpt.Load(filename);
                rpt.SetDataSource(ds);
                rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Passkeys");

            }
            else if(frmtxtdt.Text.Trim() !=null && totxtdt.Text.Trim()!=null)
            {
                if (DateTime.Parse(frmtxtdt.Text).ToString("dd/MM/yyyy")   == DateTime.Today.ToShortDateString()
                     && DateTime.Parse(totxtdt.Text).ToString("dd/MM/yyyy") == DateTime.Today.ToShortDateString()
                     && ds.Tables[0].Rows.Count == 0)
                {

                    lblmsg.Text = "Pass Key Not Yet Delivered for the Selected Date...";
                    //The value(lblmsg.Text) not Changing when comes here.
                }
                else
                {

                    lblmsg.Text = "There is No Schedule for the Selected date....";
                    //The value(lblmsg.Text) not Changing when comes here.

                }

            }

        }
        catch
        {
            throw;
        }

Friends My problem is not about [Datetime] or [Datetime Picker] it is that, The text of the label is Changing at runtime but not dispalying.
And also in the [rpt.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Passkeys");
] Crystal Report Generator in PDF file format the Report is Loading and there is also data in XML file but it is not Converted into PDF file for Download.

A: What is the context of the error, Web or desktop?
The alternatives may be:

*

*If you are using any component to make an AJAX call this label is not within the content being sent to the server and it is not updated. (Web Only)

*You may be experiencing some event (postback) that is clearing the value of this label (Web Only)

*Check the visible property of the label, it may be being altered in some part of the code

*Make sure the color of the label is not the same color as the background of your screen, believe it can happen.

*Any component is overlapping this label or that label is the location / position outside the form

A: Also, if You don't know there are very handy controls, that are called "DateTimePicker", that are specifically created for choosing Dates. You should give them a try.
I wonder if you get an exception somewhere before the change?

A: It happens because the UI thread is too loaded
Add lblmsg.Refresh(); after setting the text
if it doesn't work move the method to background thread; beware of the cross threading though. For simple interthread operations you can use ReportProgress method of BackgroundWorker Class

A: I may assume that you have some watcher associated with changing values of Text fields of your labels, - so when changing text in your labels code block in this handler fails (or works fine, but doesn't assume changing actual value of label text), updating text fails.


text:
Q: How to update divider to the right place in a RecyclerView? I wrote the following layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="15dp" />

    <TextView
        android:id="@+id/full_name"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toRightOf="@id/avatar"
        android:layout_toEndOf="@id/avatar"
        android:textSize="20sp"
        android:textColor="@color/blackColor"
        android:layout_centerVertical="true" />

    <!-- Divider -->
    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@+id/avatar"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp" />

</RelativeLayout>

It's the item layout of the RecyclerView. Basicly it creates the following layout:
[avatar] [name]
---------------------
[avatar] [name]
---------------------
[avatar] [name]

The Java code:
public void onBindViewHolder(ViewHolder holder, int position) {
        // Code
        // Set avatar

        // Set name
        holder.fullname.setText((CharSequence) name);

        // Set visible/invisible divider
        if (position < getItemCount() - 1) {
            holder.viewDivider.setVisibility(View.VISIBLE);
        } else {
            holder.viewDivider.setVisibility(View.GONE);
        }
    }

The problem is that the divider is being set on top of the ImageView and the TextView and not on the bottom of each block. I think that I understand why it happens - the divider is already there so when I set ImageView and TextView dynamically, the divider is not being rendered to the right place. Or maybe it's related to android:layout_centerVertical? How should I fix it?
Also, In the activity which sets the adapter I call:
holder.users.setLayoutManager(new LinearLayoutManager(this.activity));

Is it ok that I call LinearLayoutManager when the layout (of the item) is RelativeLayout?

A: <!-- Divider -->
<View
    android:id="@+id/divider"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/avatar"
    android:layout_centerVertical="true"  <-- REMOVE THIS LINE :)
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp" />

A: Maybe you should enclose your image and textview in a layout preferably in a relative layout and then take a view and below that layout like this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <RelativeLayout

        android:id="@+id/rlLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="15dp" />

    <TextView
        android:id="@+id/full_name"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toRightOf="@id/avatar"
        android:layout_toEndOf="@id/avatar"
        android:textSize="20sp"
        android:textColor="#000000"
        android:text="Test String"
        android:layout_centerVertical="true" />

    </RelativeLayout>

    <!-- Divider -->
    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorPrimary"
        android:layout_below="@+id/rlLayout"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp" />

</RelativeLayout>


text:
Q: Converting float/double/decimal to (u)int, (u)long in C# without memory allocation I am working on the c# networking solution for my game, and I have a problem with serializing floats, doubles, and decimals.
My first attempt - BitConverter class. But each time I use that class, a new byte[] array is created, and this may be overkill for my net solution (for example - player position synchronization).
To summarize, my expectation is:

*

*Possibility to convert floats, doubles, and decimals into (u)int, (u)long without memory allocation.

*Possibility to read (u)int's and (u)longs from server & convert the, back to the original type (still without allocating additional memory).

Edit 1
This is method I use in my NetworkWriter method to store bytes to send:
public void WriteByte(byte value)
        {
            Buffer[_position++] = value;
        }

And those are my extensions for NetworkWriter:
public static void WriteUInt(this NetworkWriter writer, uint value)
        {
            writer.WriteByte((byte) value);
            writer.WriteByte((byte) (value >> 8));
            writer.WriteByte((byte) (value >> 16));
            writer.WriteByte((byte) (value >> 24));
        }

That's I want to cast 4-byte float to 4-byte (u)int, so I can pass the result int to the Write(U)Int serializer.
I haven't done the NetworkReader yet, so I cannot show you the exact code, but it's gonna revert the Write method.
I expect a lot of float/double operations, because:

*

*Vector3 (class that holds player position) is a pack of 3 floats,

*Latency measuring will send/receive double time

*Quaternion (class that holds player rotation) is also pack of 4 floats.

That's why I wanna reduce memory allocation for float/double/decimal as much as possible.
Edit 2
Important note: I know when to expect float, double, etc, let me quickly pseudocode how will reader look like:
static float ReadFloat():
- Get 4 int bytes from buffer
- Construct float from those

A: Lots of options:

*

*BitConverter has methods like Int32BitsToSingle(Int32) (from and to, 32-bit and 64-bit)  that does a bitwise coerce between primitives; from there you can get unsigned trivially

*BinaryPrimitives has read and write methods for many primitives that work on spans; spans can be on the stack for zero-allocation (or better: can be in your output buffer)

*your own unsafe code; take the address of a local/parameter/field/interior-pointer, and coerce the pointer before dereferencing it

*the Unsafe type (and the As method in particular) allows direct coercion between same-size primitives from a ref (like the unsafe option, but pre-written, and uses IL to avoid the unmanaged pointer)

*the MemoryMarshal type (and the Cast method in particular) allows the same direct conversion on spans of types, including between different sized types; in particular, this allows you to cast any primitive that doesn't contain a reference: to a Span<byte>


text:
Q: Is it faster to have one stored procedure with multiple if checks before one insert, or to split it out into multiple stored procedures I am trying to optimize the inserting of some data into our database, but I'm not too sure if this stored procedure would be more efficient if it was split out into multiple stored procedures.
I have a stored procedure that inserts data into multiple different tables.
The stored procedure will check a key in the provided data, and then go over the if statements to perform inserts into one table. It will never insert into more than one table each call.
Would it be quicker to split this logic, and have a stored procedure for each different if statement?
For scale, there are 11 if statements, and each one writes to a different table.
An example would be like so:
IF (@CakeKey = 'Chocolate')
BEGIN
INSERT INTO [CholocateCakeTable]
...
END
ELSE IF (@CakeKey = 'Vanilla')
BEGIN
INSERT INTO [VanillaCakeTable]
...
END
ELSE IF (@CakeKey = 'Strawberry')
BEGIN
INSERT INTO [StrawberryCakeTable]
...
END
ELSE IF (@CakeKey = 'Caramel')
BEGIN
INSERT INTO [CaramelCakeTable]
...
END

The change would mean each if is in a different stored procedure with the if clause no longer being needed.
(The stored procedure is called from C#, so the if checks would be done there instead.

A: The IF has to happen somewhere, either in C# or T-SQL. Neither is going to be measurably faster than the other. So the total latency the end user observes will be the same.
Now, if you were to instrument your environment and measure to the CPU clock tick then you may see a difference. Likely C# has a better compiler than T-SQL so may run IFs faster. The network packets will be shorter by not having @CakeId so may have better throughput and latency. Each new SP will be smaller so may be subject to fewer recompilations. But, frankly, I doubt it.
You'd be better off tuning individual queries or removing redundant indexes or optimising the number of calls the app makes.
Or, you know, team bonding over some of those cakes.


text:
Q: Using the MLE to select the prior distribution...empirical Bayes? It was requested that I read the following article for work:
https://support.sas.com/resources/papers/proceedings15/1400-2015.pdf
In Case II, the author starts by doing two things:
First, he computes the maximum likelihood estimator for the PD parameter $\lambda$, denoted $\hat \lambda$.
Second, he chooses the prior $p(\lambda)$ so that $E_{\lambda}[\lambda]=\hat\lambda$.
I am not an expert with Bayesian inference, but my understanding tells me that this is totally contrary to the philosophy of Bayesian inference. We are working with a very small data set, and so there is very little information contained in the data. By using the data to construct the prior, we are essentially building a posterior distribution by incorporating the information in the data with itself. I understand that there is a method called "empirical bayes", but from what I understand, this involves computing the MLE from the marginal distribution of the data $x$, not from the conditional distribution $p(x|\lambda)$. In other words, if we have subgroups within the data, I understand Empirical Bayes to be when we use data from all subgroups to build a prior regarding a particular subgroup. In the above article I cited, only the data from a particular subgroup is used to build the prior for that subgroup.
Can someone tell me if this is common practice in Bayesian stats? I have never seen anyone do this, and I would like to sound more informed if I tell my boss that the methodology is flawed.

A: This is called empirical Bayesian approach. Here you can find nice introductory blog post on this method or the An Introduction to Empirical Bayes Data Analysis paper by George Casella (1985). You are right with considering this approach to be inconsistent with proper Bayesian approach, since priors should not depend on the data. This is a little bit of cheating and can lead to overconfident, hence misleading, results. On another hand, some argue that "it works, so why not use it?". On yet another hand, modern Bayesians are often less purist, e.g. three prominent authors Andrew Gelman, Daniel Simpson, Michael Betancourt in their paper The prior can often only be understood in the context of the likelihood notice that we often do consider the data when choosing priors, so it is not that black-and-white as it could appear.


text:
Q: Regular and repetitive sudo alerts from several Linux hosts I've got several hosts running CentOS 5.11 on the LAN. Lately we've been getting fairly regular sudo alerts (via email) from attempted sudo commands by non-authorized users. Been Googling in case the attempted commands are known hacks, or known "tools" that can trigger these.
Pattern is pretty regular, usually about twice per hour alerted from a number of hosts--very unlikely a human, thus.
The alerts themselves are always one of these two:
myhost01 : Oct 29 17:50:41 : tzx : user NOT in sudoers ; TTY=pts/0 ; PWD=/home/tzx ; USER=root ; COMMAND=lsof -nP +c0 -i4TCP
or
myhost02 : Oct 29 18:16:39 : tzx : user NOT in sudoers ; TTY=pts/0 ; PWD=/home/tzx ; USER=root ; COMMAND=parted -l
where user "tzx" is a valid Linux user--typically used to run system services or cron jobs, but also permitted for SSH login (so as to prevent doing either function as root). I've used "last" on one or two of the affected hosts and I see shell sessions from user tzx, less than one minute each, roughly corresponding to the alerts we get. And, all those sessions appear to come from the same source host on the LAN (which I'm also digging at).
Has anybody seen this kind of traffic? Any known tools, hacks/probes or other "things" that tend to try this?
Half of me thinks I've got some user with some noisy (and nosey) tool of some kind and the other half thinks this is a more serious problem.

A: SOLVED: one of the admins had installed Spiceworks on the LAN, with access to this user account, and Spiceworks was trying to run these alerted commands to accomplish its monitoring tasks. That's a big relief--apparently no malicious traffic on this one anyway. Here now for posterity.


text:
Q: How to load 1TB of data into MySQL efficiently? I have 1TB worth of text data in several files. A 15GB file has around 700million rows, so I am estimating the total number of rows is nearing 100 billion. The data has the following structure:
+--------+--------+--------+--------+--------+
| label1 | label2 | value1 | value2 | value3 |
+--------+--------+--------+--------+--------+

The labels are strings, the values are ints. In the files, everything is divided using tab characters, making for an easy import.
Ultimately, I need to be able to search for rows where either "label1" or "label2" equals a certain string. I thought MySQL would be the perfect solution. Given the size of the data, I am doubting the efficiency of MySQL though.
Using "LOAD DATA LOCAL INFILE" seems to be the recommended way of importing data into MySQL. Even after toying around with the import settings, the import seems to take too long. Some answers on StackOverflow suggest the import speeds range from 200-400million rows per hour.
Is there any other import method that would be much faster? I was hoping to import all of the data in under 6 hours.
Is MySQL even a good solution for this kind of a task?


text:
Q: Edit a text in the / public / folder after a build just for info if you want to change a text after the gatsby build, you absolutely need the sources?
Can't we just edit the files in the public folder?
The developer deleted the sources from the project.
it's just a phone to modify,
THX :wink:

A: You can modify the files in the /public folder and you'll see the changes "live" or in a production environment, but as soon as you recompile/rebuild your project again, you'll lose those changes, since they aren't applied in the source code (/src folder).


text:
Q: ng:areq error (angularjs), only in Internet Explorer Edge I've got the following Error: ERROR: [ng:areq] when I want to start the index.html. This error only occurs in the Internet Explorer edge and not in Chrome.
Here is a code snippet from creating the controller:
app.js:
var jsWorkshopApp = angular.module('jsWorkshopApp', []);

jsWorkshopApp.run(function ($rootScope, $templateCache) {

    // prevent caching
    $rootScope.$on('$viewContentLoaded', function () {
        $templateCache.removeAll();
    });
});

controller.js:
if (!jsWorkshopApp) {
    var jsWorkshopApp = angular.module('jsWorkshopApp', []);
}

jsWorkshopApp.controller('JsWorkshopCtrl', function ($scope, $http, myService) {
    $scope.chapters;
...
..
});

I've got no idea, what is wrong. I even delete the [] but then it raises another error and in chrome it doesn't work either.

A: It may be an ordering problem. Have you added reference to script files in order of as :
The app.js should be added before controller.js
If above is correct then please check you have no typo while assigning ng-controller value in view. The cotnroller name is case sensitive.


text:
Q: Opencart 3.0.2.0 sending email with mail() funtion I want to send an email to everyone who subscribes to my newsletter. In order to do this i wrote the following code inside a method i created in catalog->controller->common->footer.php.
         $to = "mymail@yahoo.com";
         $subject = "-5% Έκπτωση στο ioannoustores.com";

         $message = "Χρησιμοποιήστε το εκπτωτικό κουπόνι στις αγορές σας και κερδίστε 5% έκπτωση. Ο κωδικός σας είναι: " . $res . " και ισχύει για 7 ημέρες.";

         $header = "From:info@ioannoustores.com \r\n";

         mail($to,$subject,$message,$header);

I used the exact same code in opencart 2.1 and it worked but in 3.0.2.0 it doesn't work. Can someone help me please?

A: $to = "mymail@yahoo.com";
         $subject = "-5% Έκπτωση στο ioannoustores.com";

         $message = "Χρησιμοποιήστε το εκπτωτικό κουπόνι στις αγορές σας και κερδίστε 5% έκπτωση. Ο κωδικός σας είναι: " . $res . " και ισχύει για 7 ημέρες.";

         $header = "From:info@ioannoustores.com \r\n";

try this:
$mail = new Mail($this->config->get('config_mail_engine'));
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

$mail->setTo($to);
$mail->setFrom('your@email.xxx');
$mail->setSender(html_entity_decode('Shop Name', ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($subject), ENT_QUOTES, 'UTF-8'));
$mail->setHtml($message);
$mail->send();


text:
Q: How could i replace negative values in this column to 0 SUM([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]) AS DAmount

how can i replace negative values with 0 in this column i tried
select sUM(IF ([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]  < 0, 0, X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)] )) as DAmount

A: You could use case when
select sum(case when [X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)] >0
  then [X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]  end ) as DAmount

A: Use a case expression:
(CASE WHEN SUM([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]) > 0
      THEN SUM([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)])
      ELSE 0
 END) AS DAmount

A: use case when
select case when SUM([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)])<0 then 0 else SUM([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]) end
  AS DAmount

A: I have noticed there are multiple answers with case statements but there is another option which might interest you (using a where clause).
Select SUM([X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]) AS DAmount
FROM Table
Where [X Limited$Detailed Cust_ Ledg_ Entry].[Amount (LCY)]>0