text:
Q: AlphabetIndexer with Custom Adapter managed by LoaderManager I am trying to implement AlphabetIndexer with Custom Adapter like this
AlphabetIndexer with Custom Adapter
My class ContactsCursorAdapter extends SimpleCursorAdapter and implements SectionIndexer
and I am using a LoaderManager to manage my adapter's cursor so i have overridden the swapCursor() method like the second answer to the example above indicates.
public class ContactsCursorAdapter extends SimpleCursorAdapter
    implements SectionIndexer{

    private LayoutInflater mInflater;
    private Context mContext;

    private AlphabetIndexer mAlphaIndexer;

    public ContactsCursorAdapter(Context context, int layout, Cursor c,
        String[] from, int[] to) {
        super(context, layout, c, from, to);

        mInflater = LayoutInflater.from(context);
        mContext = context;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        ...
    }

    @Override
    public int getPositionForSection(int section) {
        return mAlphaIndexer.getPositionForSection(section);
    }

    @Override
    public int getSectionForPosition(int position) {
        return mAlphaIndexer.getSectionForPosition(position);
    }

    @Override
    public Object[] getSections() {
        return mAlphaIndexer.getSections();
    }

    public Cursor swapCursor(Cursor c) {
        // Create our indexer
        if (c != null) {
            mAlphaIndexer = new AlphabetIndexer(c, c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME),
                " ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        }
        return super.swapCursor(c);
    }
}

However, this errors out if I set my listview to fastScrollEnabled = true
getListView().setFastScrollEnabled(true);
in my class ContactsCursorLoaderListFragment which extends ListFragment and implements LoaderManager.LoaderCallbacks .
Here is the stack trace:
04-25 01:37:23.280: E/AndroidRuntime(711): FATAL EXCEPTION: main
04-25 01:37:23.280: E/AndroidRuntime(711): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sendit/com.sendit.ContactManager}: java.lang.NullPointerException
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.os.Looper.loop(Looper.java:137)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.ActivityThread.main(ActivityThread.java:4424)
04-25 01:37:23.280: E/AndroidRuntime(711):  at java.lang.reflect.Method.invokeNative(Native Method)
04-25 01:37:23.280: E/AndroidRuntime(711):  at java.lang.reflect.Method.invoke(Method.java:511)
04-25 01:37:23.280: E/AndroidRuntime(711):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-25 01:37:23.280: E/AndroidRuntime(711):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-25 01:37:23.280: E/AndroidRuntime(711):  at dalvik.system.NativeStart.main(Native Method)
04-25 01:37:23.280: E/AndroidRuntime(711): Caused by: java.lang.NullPointerException
04-25 01:37:23.280: E/AndroidRuntime(711):  at com.sendit.ContactsCursorAdapter.getSections(ContactsCursorAdapter.java:222)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.widget.FastScroller.getSectionsFromIndexer(FastScroller.java:507)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.widget.FastScroller.init(FastScroller.java:269)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.widget.FastScroller.<init>(FastScroller.java:155)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.widget.AbsListView.setFastScrollEnabled(AbsListView.java:1144)
04-25 01:37:23.280: E/AndroidRuntime(711):  at com.sendit.LoaderCursor$ContactsCursorLoaderListFragment.onActivityCreated(LoaderCursor.java:107)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:847)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.BackStackRecord.run(BackStackRecord.java:622)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.Activity.performStart(Activity.java:4474)
04-25 01:37:23.280: E/AndroidRuntime(711):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1929)
04-25 01:37:23.280: E/AndroidRuntime(711):  ... 11 more

after the setFastScrollEnabled() method gets called it calls the custom adapter's getSections() method which is where it crashes.
public class LoaderCursor extends Activity {

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

        FragmentManager fm = getFragmentManager();

        // Create the list fragment and add it as our sole content.
        if (fm.findFragmentById(android.R.id.content) == null) {
            ContactsCursorLoaderListFragment list = new ContactsCursorLoaderListFragment();
            fm.beginTransaction().add(android.R.id.content, list).commit();
        }
    }

    public static class ContactsCursorLoaderListFragment extends ListFragment
        implements LoaderManager.LoaderCallbacks<Cursor> {

        ContactsCursorAdapter mAdapter;
        Cursor mCursor;
        String mCurFilter;

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

            populateContactList();

            // Prepare the loader. Either re-connect with an existing one,
            // or start a new one.
            getLoaderManager().initLoader(0, null, this);

            ListView lv = getListView();
            lv.setFastScrollEnabled(true);
            //lv.setScrollingCacheEnabled(true);
            lv.setDivider(getResources().getDrawable(R.drawable.list_divider));

        }

        // These are the Contacts rows that we will retrieve.
        final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.PHOTO_ID, };

        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            // This is called when a new Loader needs to be created. This
            // sample only has one Loader, so we don't care about the ID.
            // First, pick the base URI to use depending on whether we are
            // currently filtering.
            Uri baseUri;
            if (mCurFilter != null) {
                baseUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI,Uri.encode(mCurFilter));
            } else {
                baseUri = ContactsContract.Contacts.CONTENT_URI;
            }

            // Now create and return a CursorLoader that will take care of
            // creating a Cursor for the data being displayed.
            String selection = "((" + ContactsContract.Contacts.DISPLAY_NAME +
                " NOTNULL) AND (" + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1)
                AND (" + ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";
            String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";

            return new CursorLoader(getActivity(), baseUri,
                CONTACTS_SUMMARY_PROJECTION, selection, null, sortOrder);

        }

        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            // Swap the new cursor in.  (The framework will take care of closing the
            // old cursor once we return.)
            mAdapter.swapCursor(data);
        }

        public void onLoaderReset(Loader<Cursor> loader) {
            // This is called when the last Cursor provided to onLoadFinished()
            // above is about to be closed. We need to make sure we are no
            // longer using it.
            mAdapter.swapCursor(null);
        }

        /**
        * Populate the contact list
        */
        private void populateContactList() {

            // start mappings
            String[] from = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
            int[] to = new int[] { R.id.contactInfo };

            // Create an empty adapter we will use to display the loaded data.
            mAdapter = new ContactsCursorAdapter(getActivity().getApplicationContext(),
                R.layout.contact_manager, null, from, to);
            setListAdapter(mAdapter);
        }

    }
}

And if I comment the setFastScrollEnabled() call, then it does not error out, but I do not see the AlphabetIndexer working.
Does this need to be implemented differently because my custom adapter is set in a ListFragment and not a ListActivity?
Does anyone have suggestions about how to make this all work?

A: So I finally got this to work.  Here's how i did it:
I added:
ListView lv = getListView();
lv.setFastScrollEnabled(true);
lv.setScrollingCacheEnabled(true);

to the onLoadFinished() method after the new cursor was swapped in like so
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
 // Swap the new cursor in.  (The framework will take care of closing the
 // old cursor once we return.)
 mAdapter.swapCursor(data);

 ListView lv = getListView();
 lv.setFastScrollEnabled(true);
 lv.setScrollingCacheEnabled(true);

}

consequently these three statements were removed from the onActivityCreated() method of my custom ListFragment.


text:
Q: Using a CC2540 (BLE) in a PCB I am currently trying to place an CC2540 on my circuit. I have a circuit using an AT-09 module that uses a CC2540 but I am trying to separate the CC2540 from the AT-09. I am using this diagram, https://www.ti.com/lit/ds/symlink/cc2540.pdf?ts=1648786274233&ref_url=https%253A%252F%252Fwww.google.com%252F (PAGE 24). I see they define everything but the antenna. Is the antenna even required with the CC2540? I assume the CC2540 being BLE it should be able to transmit and receive data without external assistance. If I need the antenna (50 ohms). Where can I get one that can fit on a PCB?
If the antenna on the diagram provided above isn't required, where do I get Tx/Rx data?

A: If you are new to all this, I have some advice for you. Instead of trying to make the complete circuit on your own, try using some ready-made modules like this. These modules are designed by experts and companies focused on RF. You will have a higher chance of getting things working immediately.
You can use the module as a component in your schematics. The reason I am suggesting this is because doing RF layout takes some experience and testing will take some expensive equipment. If you want to do this and learn this stuff, please go ahead by all means but in most cases, a person is focused on a product, and spending too much effort on this might not be the most productive way to develop the product/prototype.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get number in properties as String (java.util.Properties, Android) I have a property
text=000.01

but using java.util.Properties's method
getProperty("text");

returns "0.01" (must be "000.01")
P.S. Methods:
get("text").toString();

returns "0.01" too.
P.S.S Take into account this is Android code.

some time later
The Properties#getProperty method works fine. The problem was in my incorrect definition of column in SQLite db. I declared column as integer which worked fine with String data. So when I stored "some string" I din't get any problem and forgot about integer type.

One of the biggest differences between hobbyists and professional programmers
is the difference that grows out of moving from superstition into understanding.
The word "superstition" in this context doesn't refer to a program that gives you
the creeps or generates extra errors when the moon is full. It means substituting
feelings about the code for understanding. If you often find yourself suspecting
that the compiler or the hardware made an error, you're still in the realm of
superstition. Only about 5 percent of all errors are hardware, compiler, or
operating-system errors (Ostrand and Weyuker 1984). Programmers who have
moved into the realm of understanding always suspect their own work first
because they know that they cause 95 percent of errors. Understand the role of
each line of code and why it's needed. Nothing is ever right just because it seems
to work. If you don't know why it works, it probably doesn't—you just don't
know it yet.
Steve McConnell (Code Complete)

A: getProperty() method always return String that doesn't know 000.01 = 0.01 in maths context. So this shouldn't happen.


text:
Q: Struts2 Localization with struts dojo autocompleter I have implemented autocomplete function using struts2 dojo autocompleter and I used localization for three languages. I have got some data from property files and the some data which I have got from backend to front end like list for drop down list, is not getting from other languages properties files when I change the language. It is always getting en_us (global.properties) file. Other data in Jsp file , which I have got from property file is coming properly.
Please help.

A: It's really hard to comment without looking into your configurations and code.
But if you could validate your application against following detailed example you might be able to find any misconfigurations or code issues.
http://www.tutorialspoint.com/struts_2/struts_localization.htm


text:
Q: Pandas: Calculated field can't be greater than value from another field I'm trying to create a calculated field (spend) where the value of this field cannot be greater than another field (budget). The spend field is calculated based on two other fields (CPM, Impressions) with the formula ((Impressions/1000)*CPM).
I've created the spend field using the following:
df['spend'] = df['CPM']*(df['Impressions']/1000)

From there, I'm not able to find a solution to apply an if/else condition to the rows within the spend field. If spend > budget, row value should be replaced with the corresponding value from budget. Else, pass and retain the calculated value within spend.
Thank you.

A: Use Series.mask or min with subset of columns:
df['spend'] = df['spend'].mask(df['spend'] > df['budget'], df['budget'])

df['spend'] = df[['spend', 'budget']].min(axis=1)

Sample:
df = pd.DataFrame({'spend':[1,2,8],
                   'budget':[4,5,6]})

print (df)
   budget  spend
0       4      1
1       5      2
2       6      8

df['spend'] = df['spend'].mask(df['spend'] > df['budget'], df['budget'])
print (df)
   budget  spend
0       4      1
1       5      2
2       6      6

df['spend'] = df[['spend', 'budget']].min(axis=1)
print (df)
   budget  spend
0       4      1
1       5      2
2       6      6

A: Just get the minimum value:
df['spend'] = np.minimum(df['spend'], df['budget'])

A: Another NumPy solution:
df['spend'] = np.where(df['spend'] > df['budget'], df['budget'], df['spend'])


text:
Q: Tkinter grid() with negative padding Is there a way to add negative padding when placing a Tkinter widget in a grid ?
Things such as myWidget.grid(padx=-10) do not work.
I am trying to display a Radiobutton and a Label side-by-side, my problem is the gap between the radio's text and the label's text is too wide, hence my question on adding a negative padding to the label.
Code:
rb = Radiobutton(text="foo")
rb.grid(row=row, column=0, sticky=W)
l = Label(text="bar")
l.grid(column=1, sticky=W)

Thanks !

A: No, you cannot add negative padding. There are probably better ways to solve your problem. For example, since your label is to the right of the radiobutton, have you tried using the anchor option on the label so that the text is left-aligned?


text:
Q: Logarithm deduction question Given that $\log_{10}2 = 0.3010$ to four decimal places and that $10^{0.2} < 2$, is it possible to deduce that:

*

*$2^{100}$ begins in a $1$ and is $30$ digits long;

*$2^{100}$ begins in a $2$ and is $30$ digits long;

*$2^{100}$ begins in a $1$ and is $31$ digits long;

*$2^{100}$ begins in a $2$ and is $31$ digits long.

Can someone walk me through this problem? If you log $10^{0.2}$ with base 10, you end up with $0.2<2$ which is kind of redundant... I've also never been taught about the number of digits thing...

A: Saying that a number $N$ has $k$ decimal digits means that the following equalities hold:
$$
10^{k-1}\le N<10^k
$$
Taking decimal logarithms, this is equivalent to
$$
k-1\le \log_{10}N<k.
$$
Since $\log_{10}2\approx0.3010$ (with four exact decimal digits), we can say for sure that
$$
\log_{10}2^{100}=100\log_{10}2\approx30.10
$$
with two exact decimal digits. Therefore $2^{100}$ has $31$ decimal digits.
For the initial digit, you need to compute $10^{0.1}\approx1.25$, so the leading digit in $2^{100}$ is $1$. How to compute $10^{0.1}$? Since $1/8>1/10>1/16$, you can do four times the square root of $10$:
\begin{align}
\sqrt{10}&\approx3.16\\
\sqrt{3.16}&\approx1.77\\
\sqrt{1.77}&\approx1.33\\
\sqrt{1.33}&\approx1.15
\end{align}
so you know that $1.15<10^{0.1}<1.33$ and therefore the leading digit of $2^{100}$ is $1$.

A: Take common log on $2^{100}$,
$$\log 2^{100} = 100 \log 2 \approx 30.10 < 30.2$$
Taking exponent again
$$2^{100} < 10^{30.2} = 10^{.2}\times10^{30} < 2\times10^{30}$$

A: $2^{100}=10^{100*lg2}=10^{30.10}=10^{0.10}\cdot 10^{30}$
We can see that
$2^{100}>1\cdot 10^{30}$ and
$2^{100}<2\cdot 10^{30}$
So $2^{100}$ begins with 1 and has 31 digits.


text:
Q: define global variables in a function and pass on to a class Can any one help please,
I am trying to sample data every x minute from the class PROCESS defined in the code below (which runs whenever called on by other functions not shown here)
to schedule this, I am running a scheduler function every X minute, started by the MAIN function and executed by function minmax_job.
however my function minmax_job doesn't seem to know the initial value of i
I have tried on and on about putting global variables and so on, but it still doesn't know that i = 0 (initially)
i = 0
atc,otc,tssc = 0,0,0
atf,otf,tssf = False,False,False

class Process(threading.Thread):
    def __init__(self, buffer3, broadcast_server):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.buffer3 = buffer3
        self.factory = broadcast_server

    def run(self):
        today = datetime.now()
        global time_of_last_run
        global atv1,atv2,atv3,otv1,otv2,otv3,tssv1,tssv2,tssv3
        global atf,otf,tssf
        global atc,otc,tssc

        if self.buffer3.startswith('kitchen aquarium: temp:'):
            self.temp = self.buffer3.replace('kitchen aquarium: temp:','')
            self.factory.broadcast("Aquarium temperature %s" % self.temp)

            if atc == 1 and atf:
                atv1 = float(self.temp)
                atf = False
            elif atc == 2 and atf:
                atv2 = float(self.temp)
                atf = False
            elif atc == 3 and atf:
                atv3 = float(self.temp)
                atf = False

def minmax_job():

    global atv1,atv2,atv3,otv1,otv2,otv3,tssv1,tssv2,tssv3
    global atf,otf,tssf
    global atc,otc,tssc,i

    if i == 3:
        i = 0
        atc = 0

    if i < 4:
        atc = atc + 1
        atf = True
        i = i + 1

if __name__ == '__main__':

    minmax_scheduler = Scheduler()
    minmax_scheduler.add_interval_job(minmax_job, seconds=10)
    minmax_scheduler.start()

A: i needs to be declared as global, then assigned a value at the outer scope as this demo shows
global i
i=0

def rabbit():
    global i
    print "rabbit ",i

#main here
if __name__ == '__main__':
    rabbit()

A: @Pillmuncher, above, had the right idea as a sub-comment. I'll make it a complete answer.  You're trying to share data between processes and/or threads by means of global variables.  This is a very INCORRECT method.  It might work or might not, some of the time, if the phase of the moon is right and you don't change where you put a comment, etc.
The reasons for this are complex, but suffice to say you should find a Comp. Sci. textbook on operating systems and look up the following terms:

*

*forking

*thread safety

*multiprocessing

*protected memory

*race condition

*message queues

*interprocess communication

*thread locks

*stack memory allocation

*heap memory

In Python, both the multiprocessing and threading modules provides many functions for declaring shared memory and keeping it safe.  You like safe (even if you don't know it yet).  Safe is good.  Safe can be (but isn't always) fast.
If you try to use global variables instead of features from multiprocessing and threading modules, you'll shoot yourself in the foot while hanging yourself from a yardarm:  slowly and painfully and you'll disdain life itself.
So, check out:  http://docs.python.org/2/library/multiprocessing.html
This has many fine examples of doing things the right way.  Declare your vars ahead of time, pass them into each thread/process, and live the upstanding life you really want to lead.
Generally speaking, prefer multiprocessing.  Multithreading is rife with trouble, and while it can be faster to execute, you almost never need that speed.  That speed comes with danger, and hassle, lots of debugging time (now and later), and being very, very, careful.  Better to do what the old-timers (like me) do:  make multiprocessing your friend and dump threading in the [primarily Microsoft-centric] trash-heap of don't-go-there.


text:
Q: Assign sequence of symbols into a variable/string in Python this sequence of symbols is required as a password in an app:

9h/#13/'!O!Nr},w_T0 6!ws%N\c^i,4"

How can store this to a variable/string?

A: Just declare a string as usual, and escape the special characters ' and " with \. The escape makes it act like a string literal, rather than a special character.

str = '9h/#13/\'!O!Nr},w_T0 6!ws%N\c^i,4\"'

Output is

'9h/#13/\'!O!Nr},w_T0 6!ws%N\\c^i,4"'

A: One easy way to store those characters in a string is to use Python's triple-quotes.
s = '''9h/#13/'!O!Nr},w_T0 6!ws%N\c^i,4"'''

If your sequence did not end with a double-quote, triple double-quotes could also have been used rather than the triple single-quotes above. The triple-quote way of showing a string is designed for tough cases like yours, with almost any combination of text characters allowed in the string. Executing the command print(s) gives the output that you want:
9h/#13/'!O!Nr},w_T0 6!ws%N\c^i,4"

A: Import strings
Strings = string.punctuation

Use this and thank me later


text:
Q: NServiceBus exceptions logged as INFO messages I'm running an NServiceBus endpoint on an Azure Workerrole. I send all diagnostics to table storage at the moment. I was getting messages in my DLQ, and I couldn't figure out why I wasn't getting any exceptions logged in my table storage.
It turns out that NSB logs the exceptions as INFO, which is why I couldn't easily spot them in between all the actual verbose logging.
In my case, a command handler's dependencies couldn't be resolved so Autofac throws an exception. I totally get why the exception is thrown, I just don't understand why they're logged as INFO. The message ends up in my DLQ, and I only have a INFO-trace to understand why.
Is there a reason why exceptions are handled this way in NSB?

A: NServiceBus is not logging container issue as an error because it's happening during an attempt to process a message. First Level Retry and Second Level Retry will be attempted. When SLR is executed, it will log a WARN about the retry. Ultimately, a message will fail processing and an ERROR message will be logged. NSB and Autofac sample can be used to reproduce this.
When endpoint is running with a scaled out role and MadDeliveryCount is not big enough to accommodate all the role instances and retry count that each instance would hold, this will result in DeliveryCount reaching it's max while NServiceBus endpoint instance still thinks it has attempts before sending message to an error queue and logging an error. Similar to the question here I'd recommend to increase MaxDeliveryCount.
There is an open NServiceBus issue to have a native support for SLR counter. You can add your voice to the issue. The next version of NServiceBus (V6) will be logging message id along with the exception so that you at least could correlate between message in DLQ and log file.


text:
Q: Programmatically set the UITabBarItem icon for every linked ViewController Currently we are changing the image shown in the UITabBarItem like this:
override func viewDidLoad() {
    super.viewDidLoad()

    // register additional NIB files
    tableView.registerNib(UINib(nibName: "WeekDayTableViewCell", bundle: nil), forCellReuseIdentifier: "WeekDayCell")

    tabBarItem.title = "Week".localized
    tabBarItem.image = UIImage.fontAwesomeIconWithName(FontAwesome.Calendar, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))
}

The problem with this is, that you have to click on every tab to load the corresponding images.
I thought I could change the images in the UITabBarViewController if I get the list of all UITabBarItems. But this list is always empty.
Which is the correct way to do this?

A: I found out, if I add this code to the viewDidAppear in the UITabBarController it will work.
let tabBarItems = tabBar.items! as [UITabBarItem]

tabBarItems[0].title = "Week".localized
tabBarItems[0].image = UIImage.fontAwesomeIconWithName(FontAwesome.Calendar, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))

tabBarItems[1].title = "Settings".localized
tabBarItems[1].image = UIImage.fontAwesomeIconWithName(FontAwesome.Gears, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))

A: An alternative—perhaps a more Swift-y—way to do this is to set the icons from a Dictionary of tabs. We have an enum TabTitles for the names of the tabs, and tabIcons to look it up.
This way, there's not so much to remember to change if you add a tab or change the order.
private enum TabTitles: String, CustomStringConvertible {
    case Stacks
    case Settings
    case Clusters
    case Services
    case Registries

    private var description: String {
        return self.rawValue
    }
}

private var tabIcons = [
    TabTitles.Stacks: FontAwesome.Clone,
    TabTitles.Settings: FontAwesome.Gears,
    TabTitles.Clusters: FontAwesome.Cubes,
    TabTitles.Services: FontAwesome.Exchange,
    TabTitles.Registries: FontAwesome.Institution
]

override func viewDidLoad() {
    super.viewDidLoad()

    if let tabBarItems = tabBar.items {
        for item in tabBarItems {
            if let title = item.title,
              tab = TabTitles(rawValue: title),
              glyph = tabIcons[tab] {
                item.image = UIImage.fontAwesomeIconWithName(glyph, textColor: UIColor.blueColor(), size: CGSizeMake(30, 30))
            }
        }
    }
}

A: Swift 5
You can set tabBarItems icons from your first controller 'viewDidLoad' method.
   func setupTabBar() {
    tabBarController?.tabBar.items![0].title = "Week"
    tabBarController?.tabBar.items![0].image = #imageLiteral(resourceName: "icons8-clinic")
    tabBarController?.tabBar.items![1].title = "Profile"
    tabBarController?.tabBar.items![1].image = #imageLiteral(resourceName: "icons8-phone_not_being_used_filled")
}

A: Use item.image = UIImage.fontAwesomeIcon(name: glyph, textColor: UIColor.black, size: CGSize(width: 30, height: 30)) for Swift 3.
Also remember to import FontAwesome_swift


text:
Q: Metric of the Universe As some of you know, there is a fundamental flat space-time metric that describes our universe without any energy or matter in it. Correct me if I am wrong, but this metric and existance of the limiting speed of signal propagation which is not dependent of the observer are the same thing. Or? Could we understand one as a consequence of the other? So, could we say that the constant $c$ is a consequence of the metric? And, could there be some other, fundamentally different flat spacetime metric which allowes other forms of motion? Eg, greater speeds, in a nutshell, a different causality? What do you think, is there some more fundamental physical reality which determines the metric?

A:
As some of you know, there is a fundamental flat space-time metric that describes our universe without any energy or matter in it.

It doesn't matter whether the universe has matter in it or not. The metric is locally always Minkowski.

Correct me if I am wrong, but this metric and existance of the limiting speed of signal propagation which is not dependent of the observer are the same thing.

Given any metric whose eigenvalues have the signs $+---$, we can choose coordinates such that at a particular point, the form of the metric is $\operatorname{diag}(1,-1,-1,-1)$, which is the Minkowski form and which implies a speed $c$ (equal to 1 in these units) that all observers agree on. The set of signs is called the signature of the metric. So logically, there is a universal speed that arises because the metric has a particular signature.

And, could there be some other, fundamentaly different flat spacetime metric which allowes other forms of motion?

No, the canonical form described above applies to all metrics with this signature. Any variation in $c$ can be absorbed into the change of coordinates that brings the metric into the canonical form.

What do you think, is there some more fundamental physical reality which determines the metric?

General relativity says that the metric is determined by the presence of mass-energy. What is physically observable about the metric is not $c$ or the signature, but the curvature.

A: The idea I think you're trying to get at is why a lot of people set $c=1$. As a sort of definition: as long as your pseudometric is (3,1) -- so, 3 space dimensions and 1 time -- and Riemannian, then you have an region locally looking like $\mathbb{R}^4$, and some cone of that space that has proper length of zero. The slope of that cone is then called $c$. But we could also just define our coordinate system locally to have that slope be $1$, and then you have the two coordinates on the same footing somewhat more equally.
In this sense, I guess you could say that $c$ is a consequence of the metric.
I don't think you can reasonably say that somewhere else a "different flat spacetime" could give "greater speeds". Speed is defined relative to that slope, of $c$. If you somehow rescaled spacetime so that $c$ was smaller, then all time would evolve slower, and the resulting physics would be the same.
The only way you can get different causal structure is on a larger scale (e.g. closed timelike curves), or a different local topology (at event horizons, extra time dimensions).

A: You seem to ask whether the laws of nature are governed by gravity, or vice versa. Spacetime existed at the big bang while one cannot speak of the big bang being a consequence of something else, since the big bang is the initial moment in time of our universe. So did gravity exist in its current form since the big bang, or were the fundamental constants of the universe determined shortly thereafter?
As for the cosmological constant: perhaps the nonzero vacuum energy density of spacetime acts as a limiting factor. We know for example that light travels slower in water than in air. Spacetime being a medium, might it have been "easier" to travel through with a smaller cosmological constant? This would make the cosmological constant more fundamental than the speed of light. In turn, the cosmological constant isn't even constant according to the theory of cosmic inflation.
To my knowledge it's unclear what the laws of physics were in the crazy energy regime of the big bang.

A:
As some of you know, there is a fundamental flat space-time metric that describes our universe without any energy or matter in it.

Yes, the FRW-universe "without any energy or matter", often called the "empty universe", is mathematically equivalent to Minkowski spacetime by coordinate transformation which is globally flat. This means that special relativity holds throughout Minkowski space.

So, could we say that the constant c is a consequence of the metric?

No, the metric measures - sloppy said - lengths and angles - Whereas the lightspeed c is a universal physical constant which has the same value measured locally in flat or curved spacetime independent of the metric.

What do you think, is there some more fundamental physical reality which determines the metric?

There are speculations that gravity could be an emergent phenomenon based on microscopic degrees of freedom. But if so that wouldn't affect general relativity and also not the FRW-metric.


text:
Q: How do I use an arithmetic expression in the where clause of a SQL query that has a Group By clause without getting arithmetic overflow? I have an Azure SQL DB and my query keeps throwing an arithmetic overflow error when it runs over too many rows. This is a sanitized version of my query (SET_END_TIME and SET_START_TIME are FLOAT type):
select t1.value1
from TABLE1 t1
    join TABLE2 t2
    on t1.ID = t2.ID
where
    (t1.SET_END_TIME - t1.SET_START_TIME) > 2
    and
    t2.CREATED_AT > '2017-06-11T00:00:00'
group BY
    t1.value1;

If I run this with another and in the where clause that restricts the date to two days, it runs fine. E.g. if I added
and t2.CREATED_AT < '2017-06-13T00:00:00'

So I know the issue is somehow related to the number of rows it is running over, but I don't understand why since the actual arithmetic operation should only be done row by row. Does anyone know what could be causing the overflow error and how I can fix my query to be able to run over many rows?
EDIT:
I know I have invalid values. I can see SET_START_TIME values of 1.79769313486232E+308 and -8.98846567431158E+307. Is there anyway I can tell the query to ignore invalid values (e.g. any Set start time > 100 and < 0) so it won't try to run the arithmetic on them?

A: I would be suspicious of the values in SET_END_TIME and SET_START_TIME and that calculation causing you the error.  Can you output each column and see if perhaps SET_START_TIME is negative at some point and that produces the error you get?

A: Try removing the group by.
If you want distinct values for t1.value add the distinct keyword in the select.
(just thinking out loud)

A: Turns out the root cause was invalid values in the columns I was using for the arithmetic in my where clause, and the solution was to use a case expression inside a subquery to first sanitize the values I want to perform the arithmetic on, then filter on them in the outer query. Example:
select
    t1.value1,
    count(*) as total_values
from
    (
        select
            t1.ID as innerID,
            (case when t1.SET_START_TIME < 10000 and t1.SET_START_TIME > 0 then t1.SET_START_TIME else 0 end) as set_start,
            (case when t1.SET_END_TIME < 10000 and t1.SET_END_TIME > 0 then t1.SET_END_TIME else 0 end) as set_end
        from TABLE1 t1
    ) innerTable
    join TABLE2 t2
    on innerID = t2.ID
where
    (set_end - set_start) > 2
    and
    t2.CREATED_AT > '2017-06-11T00:00:00'
group by
    t1.value1;


text:
Q: Power BI Top N Bottom Too Many Results New to Power BI, obvs.
I've got too many results showing up in my Top N bottom 10 and would like to eliminate the items that are only single units to clean up the chart. So it looks neat like the Top N top donut.
I haven't found any other questions about this, so I suspect the answer is easy.
Thanks in advance.


text:
Q: Mapping two argument function in Mathematica I want to archive:
Map2[f,{a,b,c,d}]
{f[a,b], f[b,c], f[c,d]}

But for some reason, I can only think of iterative approaches.
What's the functional way?
Edit:
Use of this, was to generate graph examples. If number list is given, following generates the graph of what it would mean, to sequentially visit all the nodes.
For example:
Map2 = # @@@ Partition[#2, 2, 1] &;
MG[elems_] := Graph[Map2[DirectedEdge, elems]]
nrs = RandomInteger[{1, 15}, 20]
MG[nrs]

{10,13,9,7,13,3,5,1,15,10,15,6,14,3,1,2,11,4,8,5}
Radial layout:

A: As explained in the Mathematica cookbook mapping a function over a moving sublist can  be elegantly solved with the ListConvole function:
Map2[f_, l_List] := ListConvolve[{1, 1}, l, {-1, 1}, {}, #2 &, f]

In[11]:= Map2[f, {a, b, c, d}]
Out[11]= {f[a, b], f[b, c], f[c, d]}

Mr.Wizard here, adding comparative timings as requested by sakra.

A: I like:
Map2[f_, l_List]:= MapThread[f, {Most@l, Rest@l}]

In[988]:= Map2[f,{a,b,c,d}]
Out[988]= {f[a,b],f[b,c],f[c,d]}

A: I recently re-read your question and saw your Graph[ ] application.
I think the natural way to do that is:
f[l_] := Graph[Thread[Most@l -> Rest@l]]

So
f[{10, 13, 9, 7, 13, 3, 5, 1, 15, 10, 15, 6, 14, 3, 1, 2, 11, 4, 8, 5}]

A: Following belisarius' lead, and addressing your Graph application, this should be a little faster:
f = Inner[Rule, Most@#, Rest@#, Composition[Graph, List]] &;

A: Most simply:
Map2 = # @@@ Partition[#2, 2, 1] &;

Or, possibly using less memory, but running a bit slower:
Map2[f_, lst_] := Developer`PartitionMap[f @@ # &, lst, 2, 1]

Also, be aware of Differences and Accumulate, which are related.

Other ways:
Inner[#, Most@#2, Rest@#2, List] &

Notice that in this one List could be a different function.
MapThread[#, {Most@#2, Rest@#2}] &

Most@MapThread[#, {#2, RotateLeft@#2}] &

Rest@MapThread[#, {RotateRight@#2, #2}] &

Table[# @@ #2[[i ;; i + 1]], {i, Length@#2 - 1}] &

Now, the timings.  I will make use of Timo's timeAvg.
f1 = # @@@ Partition[#2, 2, 1] &;
f2[f_, lst_] := Developer`PartitionMap[f @@ # &, lst, 2, 1]
f3 = Inner[#, Most@#2, Rest@#2, List] &;
f4 = MapThread[#, {Most@#2, Rest@#2}] &;
f5 = Most@MapThread[#, {#2, RotateLeft@#2}] &;
f6 = Table[# @@ #2[[i ;; i + 1]], {i, Length@#2 - 1}] &;

timings =
  Table[
   list = RandomReal[99, 10^i];
   func = Plus;
   timeAvg[#[func, list]] & /@ {f1, f2, f3, f4, f5, f6},
   {i, 6}
  ];

TableForm[timings,
 TableHeadings -> {10^Range@6, {"f1", "f2", "f3", "f4", "f5", "f6"}}]

ListLogPlot[timings\[Transpose], Joined -> True]

The numbers on the left side of the table are the length of the list of real numbers for each run.
Note that the graph is logarithmic.
Here are the bytes of memory used while processing the longest list (1,000,000):

After doing the timings above, I found I can make f6 faster by eliminating Apply (@@).  It is now clearly the fastest on longer lists.  I will not add it to the table above because that is already wide enough, but here is the function and its timings:
f7 = Table[#2[[i]] ~#~ #2[[i + 1]], {i, Length@#2 - 1}] &;

A: Wow, I saw the other solutions and they seem quite complex and obfuscate. This is a lot simpler to understand, at least if you like a more functional approach:
MapApplyImpl[fun_] := Function[{args}, Apply[fun, args]]
MapApply[fun_, argList_] := Map[MapApplyImpl[fun], argList]

and a usage example:
ff := Function[{t, phi}, t*phi]
MapApply[ff, {{0, Pi/4}, {(Pi/4)/(10^3) , 0}, {(2*Pi/(10^3)),
   Pi/4}}]


text:
Q: What happens after we assign to a dereferenced pointer an another dereferenced pointer? I can't understand what happens after line *p1=10, what happens with *p2 variable, and in the end how does secondvalue variable gets 20.

#include <iostream>
using namespace std;

int main ()
{
  int firstvalue = 5, secondvalue = 15;
  int * p1, * p2;

  p1 = &firstvalue;
  p2 = &secondvalue;
  *p1 = 10;
  *p2 = *p1;
  p1 = p2;
  *p1 = 20;

  cout << "firstvalue is " << firstvalue << '\n';
  cout << "secondvalue is " << secondvalue << '\n';
  return 0;
}

Output of command
firstvalue is 10
secondvalue is 20

I can't understand how the secondvalue variable gets a value of 20.
If we assigned *p2=*p1 mustn't secondvalue variable get 10?

A: p1 = p2;

This doesn't copy the value pointers point to, just "address" the p2 points to. Thus at this point both p1 and p2 point to the secondvalue, and changing either of them applies changes to the secondvalue

A:
If we assigned *p2=*p1 mustn't secondvalue variable get 10?

It sure does. And if that was the last assignment, then that what would happen. But perhaps you've noticed that there are more assignments, that follow this one:
p1 = p2;

p1 is now pointing to the same value that p2 is pointing to. p2 is pointing to secondvalue, so p1 is now pointing to secondvalue, too.
*p1 = 20;

The value that p1 points to gets assigned 20. And that's how secondvalue gets assigned 20.

A: Lets see this step by step:
int firstvalue = 5, secondvalue = 15;

This initializes two 4 byte integers.
---------------------------------------
|                 |                   |
|  firstvalue (5) |  secondvalue (15) |
|                 |                   |
---------------------------------------

*Initializes int pointers and sets their values

int * p1, * p2;
p1 = &firstvalue;
p2 = &secondvalue;

p1 now stores the address of firstvalue, and p2 stores the address of secondvalue
---------------------------------------
|           (*p1) |             (*p2) |
|  firstvalue (5) |  secondvalue (15) |
|                 |                   |
---------------------------------------
      p1                  p2

*Now you assign 10 to *p1. What this does is that it modifies the value at the memory address which was stored in p1:

*p1 = 10;

---------------------------------------
|           (*p1) |             (*p2) |
| firstvalue (10) |  secondvalue (15) |
|             ^^  |                   |
---------------------------------------
      p1                  p2

*Now you assign *p1 to the memory address stored in p2. *p1 dereferences the pointer p1 and returns you the value it is pointing to.

*p2 = *p1;

---------------------------------------
|           (*p1) |             (*p2) |
| firstvalue (10) |  secondvalue (10) |
|                 |               ^^  |
---------------------------------------
      p1                  p2

*Now you change the memory address p1 is pointing to. Now p1 and p2 points to the same variable

p1 = p2;

---------------------------------------
|                 |    (*p1) (*p2)    |
| firstvalue (10) |  secondvalue (10) |
|                 |                   |
---------------------------------------
                        p1  p2

*Finally, you modify the value at the memory address stored by p1, (that is also p2).

*p1 = 20;

---------------------------------------
|                 |    (*p1) (*p2)    |
| firstvalue (10) |  secondvalue (20) |
|                 |               ^^  |
---------------------------------------
                        p1  p2

A: Yeah, but when you p1 = p2; you make so p1 now stores the reference to second value, and in the line below you assing *p1 (this is secondvalue) to 20.
So in your code flow firstvalue is assigned to 10 on *p1 = 10; and secondvalue is assigned to 20 on *p1 = 20;

A: So, pointers and references (and de-referencing, oh my!)
Alas, this is where vocabulary makes a difference, and people love this particular selection of vocabulary. So here it is, explained in all its glory.
Values
A value is something that exists somewhere in memory (like a variable, though not necessarily). To be useful, we programmers like to give values both a type and a name.
int    x    = 74;
double pi   = 3.141592;
string name = "Hannah";

References
A direct reference is an alias, another name, if you will, for a value.
int  x = 7;  // type:int, name:x, value:7
int& z = x;  // z = another name for x
z = 12;      // x = 12;

Using aliases is something we do in normal life.

*

*I call my father "Dad".

*Dad's friends call him "Bill".

*My friends call him "Mr. Greer".

Different names. Same person.
Now, some C++ purists will tell you these are just plain references. Well, yes... and no. Yes, as far as the C++ Language is concerned. No, as far as understanding things is concerned. Just remember that when talking to C++ people, the word "reference", unless otherwise qualified with some adjective, always means direct reference, or alias.
Pointers
Before C++ introduced "references" as part of the language abstraction, we had indirect references — also called pointers.
It is indirect because a pointer is not itself a reference. But you can get a reference from a pointer's value by dereferencing it using the * operator.
The term is a bit wonky (because it looks like you are "un"-referencing it), but the opposite is true: you are taking that indirect reference (the pointer value) and effectively converting it into an (unnamed) direct reference, an alias for the "pointed-to" (or "referenced") value.
int  x  = 7;
int* px = &x;  // type=(pointer to int)  name="px"  value=(address of x)
*px = 12;      // (direct reference to x) = 12

In other words px is a pointer with an indirect reference to — i.e. address of — x.
Thus when we dereference px with the * operator, we transform the expression into a direct reference to x — at which point we have access to read or modify x's value just as if we had x in hand to begin with.
I suspect the term "dereference" came about because we are "un"-indirect referencing a pointer value to obtain a direct reference, but all the people who created the term are dead now and I don't know of any place they felt the need to explain it.
WHAT YOU MEANT TO ASK
So, a dereferenced pointer is an alias for the target object. You want to know what happens if you don't dereference the pointers, which would be:
"What happens if we assign an un-dereferenced pointer to another un-dereferenced pointer?"
... and un-dereferenced means not dereferenced, so you are basically asking:
What happens when we assign one pointer to another?
The answer at this point should not be a surprise: the same thing that happens whenever we assign any variable's value to another.
int  x  = 7;
int* p1 = &x;  // p1 now "points to" x
int* p2 = p1;  // and now p2 also "points to" x

Remember, the value of a pointer is the address of another object in memory, and you can copy values around however you like.
*p2 = 42;  // x = The Answer


text:
Q: How does the keras functional API model knows about layers when are only passing inputs and outputs of the network I am new  to Keras and my looking into the functional api model structure.
1-
As mentioned here in docs. The keras.Model takes only input and the output argument, and the layers are listed before the Model. Can someone please tell me how the keras.Model knows about the layers structures and the multiple layers between input and output, when all we are passing is just the input and output arrays.
2 -
Also, what is output of layers.output or layers.input. Is the output not a simple tensor? I see below output when I print layers.output using syntax from this example for some other layer. Looks like layers.output and layers.input contains the layer info as well, like dense_5/Relu:0.  Can someone please clarify what the components of below output stand for
print [layer.output for layer in model.layers]

output:
 [<tf.Tensor 'input_6:0' shape=(None, 3) dtype=float32>,
  <tf.Tensor 'dense_5/Relu:0' shape=(None, 4) dtype=float32>,
  <tf.Tensor 'dense_6/Softmax:0' shape=(None, 5) dtype=float32>]

A: *

*You should describe model first, before compiling/fitting/evaluation. You make a sequence: first layer is input, next a bunch of intermediate layers and then output layer.

Like in your example:
inputs = keras.Input(shape=(784,))          # input layer
dense = layers.Dense(64, activation="relu") # describe a dense layer
x = dense(inputs)                           # set x as a result of dense layer with inputs
x = layers.Dense(64, activation="relu")(x)  # "update" x with next layer which has previous dense layer as input
outputs = layers.Dense(10)(x)               # set your output
model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model") # incorporate all layers in a model

So basically Keras already know what is inside model.

*You was looking at obtaining outputs of intermediate layers. This is common principle in transfer learning (when you use pre-trained model as feature extractor) or for some architectures as skip-connections. In this case you will get multiple outputs. Also network can has multiple outputs at the end of model, depending on model purpose. On your example they are just for demonstration purposes and do not have some meaning. Take a look at more meaningful feature extraction

A: To answer your first question about how the model knows about the layers that were called on the intermediate tensors, I think it's helpful to take a look at help(keras.Input):

Input() is used to instantiate a Keras tensor.
A Keras tensor is a symbolic tensor-like object, which we augment with
certain attributes that allow us to build a Keras model just by
knowing the inputs and outputs of the model.

So basically, Keras is using Python to do some magic under the hood.
Each time you call a Keras layer on a Keras tensor, it outputs a Keras tensor that has been mathematically transformed according to the layer's functionality, but also adds some information about that layer to this Keras tensor (in Python attributes of the object).


text:
Q: Ruby on Rails - Simple calculations shown in the view and stored in database First of all sorry for this simple question, after spending a lot of time I have given up finding it without any help :(.
Simplified I have the following situation: one table rates with columns rate and converted generated with the scaffold statement within ruby. The column rate will be shown in the view, but the converted column not which will only be used in the background of the application.
Now it's my goal to ask the user for a rate given in the field rate so the application can calculate the converted and store this value in the database. It's a simple calculation: converted = 1 / rate.
Please advice :).

A: Well there are a ton of ways to do that, including but not limited to putting the logic in the model (probably cleanest), in the controller and in the view itself with a hidden field and javascript.
I would do it at the model level with a callback. For example, add this to your rates.rb model:
before_save :calculate_converted_rate

private

def calculate_converted_rate
  self.converted = 1.0 / self.rate
end

Which as the code might suggest sets the converted field to the inverse of the rate field each time before a Rates instance is saved.
More information on ActiveRecord callbacks: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

A: Define your own mutator method in your model. This will allow you to take the input from your user, do what you want with it, then store it in the database. To illustrate:
class Rate < ActiveRecord::Base

    def rate=(value)
        write_attribute :rate, value
        write_attribute :converted, 1.0 / value
    end

end

This will override Rails' default rate= method, which is what gets called when your model is passed your rate data from (assumedly) your form. Construct your model's form normally, with a <%= f.text_field :rate %> or whatever you need to do.
Note the 1.0 / value, not 1 / value - this will ensure the result of that expression is a float, and that you won't lose any precision. If you divide an integer by an integer in Ruby, you'll always get an integer.


text:
Q: Alter Users Table in Wordpress Currently in the WP-ADMIN the Users Table show info like Gravatar, Name, Email, Role and Posts. How can I alter this table to display other info like Phone, Company, etc?
PS: These metadata infos already exists and are displayed when I click on a user but I want it to be displayed in the table too.

A: You're probably going to have to manually rewrite the html table in wp-admin/users.php as currently it's produced via an object which doesn't contain the User's meta data.
You'd need to access the meta data using the function get_user_meta:
<?php get_user_meta($user_id, $key, $single); ?>

Be aware, changing this isn't a great idea as it may break next time you upgrade Wordpress.


text:
Q: Sencha Touch: onUpdated() function + Ext.MessageBox pop-ups freeze my Sencha app
*

*Am building a Sencha Touch app. Each time I build a new app version and the function below is called
my app freezes on all web browsers, iOS device and Android device. I cannot press anything after the Ext.Message.Box
is show whether i want to update the app.

onUpdated: function() {
                Ext.Msg.confirm(
                        "Application Update",
                        "This application has been updated to a new version. Reload now?",
                        function(buttonId) {
                            if (buttonId === 'yes') {
                                window.location.reload();
                            }
                        }
                    );
                },

*

*Whenever an Ext.MessageBox opens it freezes my app, when I click on any of the options (No Ok), nothing happens.
The app is basically frozen.

I have added in requires: ['Ext.MessageBox'] in app.js
I have read multiple online pages on it, but to no avail
Does somebody have experience with these 2 errors? They seem to be related.


text:
Q: [ERROR]org.springframework.beans.factory.BeanCreationException when i run Java Web in tomcat6.0. i found this problem in time !
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CaseCache' defined in file [D:\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\tpcPo\WEB-INF\classes\applicationContextCache.xml]: Cannot resolve reference to bean 'CaseDAO' while setting bean property 'caseDAO'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CaseDAO' defined in file [D:\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\tpcPo\WEB-INF\classes\applicationContextDao.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'CaseDAO' defined in file [D:\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\tpcPo\WEB-INF\classes\applicationContextDao.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:883)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:839)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:440)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:269)
... 33 more
Caused by: java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:100)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:61)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:877)
... 44 more

My applicationContextCache.xml
<bean id="CaseCache" class="com.aboveE.tpcPo.service.CacheService">
    <property name="caseDAO" ref="CaseDAO"/>
    <property name="offDocDAO" ref="OffDocDAO"/>
    <property name="caseQueryMap" ref="caseQueryCache" />
    <property name="officialQueryMap" ref="officialQueryCache" />
</bean>

My applicationContextDao.xml
<bean id="CaseDAO"
    class="com.aboveE.tpcPo.dao.CaseDAO">
    <property name="sessionFactory">
        <ref bean="sessionFactory" />
    </property>
</bean>

I'have already done a lot of research in google , but I can't resolve my problem...
please somebody can help me :(

A: The error message boils down to the following:
Error creating bean with name 'CaseDAO' defined in file:
The problem is with the CaseDAO bean.
Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError:
The problem is with the constructor.
Can you check whether the following is the case:

*

*Does com.aboveE.tpcPo.dao.CaseDAO have a no-args constructor?

*Is the constructor accessible (i.e. not private or protected, though Spring tries to make these constructors accessible)

*Could the constructor have thrown an exception?

*Is com.aboveE.tpcPo.dao.CaseDAO an abstract class?

A: it looks like you have an issue with your DAO. During its initialization(read, inside the constructor/initialization block, its own or its parent) there is an issue.
Why don't you just debug it?


text:
Q: issue with File variables The payRate hourWorked and employNum variables say they are not uninitialized. Not sure what is going wrong here. I'm trying to gather info from a file and then calculate data and show it on screen.
 {
        int x;
        double y;
        double employNum;
        double payRate;
        double hourWorked;
        double grossAmount;
        bool employChecker;
        double netCalc;
        cout << "Welcome to the employee data menu!" << endl;
        employChecker = false;
        do

        {

            cout << "Please enter :" << endl << "1: To view  an employees Data" << endl << "0: To retirn to the main menu" << endl;
            cin >> x;
            if (x = 1)
            {
                cout << "Please enter the employee number that you would like data on" << endl;
                cin >> y;
                cout << "Employee Num" << setw(10) << "Hours" << setw(20) << "Rate" << setw(30) << "Gross" << setw(40) << "Net" << setw(50) << "Fes" << setw(60) << "State" << setw(70) << "Soc Sec" << setw(80) << endl;
                ifstream  myFileIn("inText.txt");
                while (myFileIn, employNum, payRate, hourWorked)
                {
                    if (employNum == y)
                    {
                        employChecker = true;
                        if (hourWorked >= 35)
                        {
                            grossAmount = ((hourWorked * payRate)*.15);
                        }
                        else if(hourWorked < 40)
                        {
                            grossAmount = ((40 * payRate) * ((hourWorked - 40)*1.5));
                        }
                        else
                        {
                            grossAmount = (hourWorked * payRate);
                        }
                        netCalc = grossAmount - (grossAmount * STATE_TAX) + (grossAmount * SOC_TAX) + (grossAmount * FEDERAL_TAX);
                        cout << employNum << setw(10) << hourWorked << setw(20) << payRate << setw(30) << grossAmount << setw(40) << netCalc << setw(50) << (grossAmount * FEDERAL_TAX) << setw(60) << (grossAmount * STATE_TAX) << setw(70) << (grossAmount * SOC_TAX) << setw(80) << endl;
                    }
                }
                if (employChecker == false)
                {
                    cout << "Employee does not exist or there was an error computing epmloyees data!" << endl;
                }

            }
        } while (x != 0);
        return(0);
    }

A:
The payRate hourWorked and employNum varibles say they are not uninitialized

The compiler tells you what you've done wrong: you did not initialize these variables, so they might have any value, including things like 0.0 (which would be false in your while loop), but you use them in your while loop.
You could do something like
double payRate = 0.0;
to solve that ambiguity.
All in all, I haven't thoroughly read your code, but it's almost never correct to simply use a concatenated list of floating point expressions in a while loop:
while (myFileIn, employNum, payRate, hourWorked)

I really don't know what you wanted to do, but this clearly indicates you will have to go back and learn C++ basics. The content of (myFileIn, employNum, payRate, hourWorked) is always the value of hourWorked, and I'm pretty sure that's not what you wanted to test for in your loop iteration condition.


text:
Q: calculate cells in range if user changes any value of the cell in range i have this code that works and calculates A1 based on what's in A2:A5. if i have "1" in A2:A5 then A1 is 4. now i change A1 to "3" and want to see what A2:A5 will be, but it bounces back to "4". how do i modify this macro to make this happen? i need this to work for any cell in A1:A5 range.
Private Sub Worksheet_Change(ByVal Target As Range)'

Dim A(1 To 5) As Range

Set A(1) = Range("A1")
Set A(2) = Range("A2")
Set A(3) = Range("A3")
Set A(4) = Range("A4")
Set A(5) = Range("A5")

If Intersect(Range("A1:A5"), Target) Is Nothing Then Exit Sub

Application.EnableEvents = False
    A(1) = A(2) + A(3) + A(4) + A(5)
    A(2) = A(1) - A(3) - A(4) - A(5)
    A(3) = A(1) - A(2) - A(4) - A(5)
    A(4) = A(1) - A(2) - A(3) - A(5)
    A(5) = A(1) - A(2) - A(3) - A(4)
Application.EnableEvents = True
End Sub

A: Something like this:
Private Sub Worksheet_Change(ByVal Target As Range) '

    Dim A(1 To 5) As Range

    Set A(1) = Range("A1")
    Set A(2) = Range("A2")
    Set A(3) = Range("A3")
    Set A(4) = Range("A4")
    Set A(5) = Range("A5")

    If Intersect(Range("A1:A5"), Target) Is Nothing Then Exit Sub

    Application.EnableEvents = False
        If Intersect(A(1), Target) Is Nothing Then A(1) = A(2) + A(3) + A(4) + A(5)
        If Intersect(A(2), Target) Is Nothing Then A(2) = A(1) - A(3) - A(4) - A(5)
        If Intersect(A(3), Target) Is Nothing Then A(3) = A(1) - A(2) - A(4) - A(5)
        If Intersect(A(4), Target) Is Nothing Then A(4) = A(1) - A(2) - A(3) - A(5)
        If Intersect(A(5), Target) Is Nothing Then A(5) = A(1) - A(2) - A(3) - A(4)
    Application.EnableEvents = True
End Sub


text:
Q: Select a postgres database after onnect on java This code connects abd create a database ,how can I select the created database to use it?
public class Connect {

    public static void main(String[] args) {
        Connection connection = null;
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection(
            "jdbc:postgresql://localhost:5432/","postgres", "12345");

            Statement statement = connection.createStatement();
            statement.execute("CREATE DATABASE mydb");
            //now I hav to connect to mydb

            connection.close();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(OracleToPostgres.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(OracleToPostgres.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

A: Something like this will do ...
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb", "user", "password");


text:
Q: Div acting like panel I have a div with grooved border.
I want it to look like this panel: http://www.devmanuals.com/images/images1/444Panel1.gif
The panel on the image has title "User registration".
How to make my div has a title like the panel?

A: That is called a fieldset, and it is a basic HTML tag.
  <fieldset>
    <legend>User Registration</legend>
    User name: <input type="text" />

    Password: <input type="text" />

  </fieldset>

I cringe at giving you a link to this site, but it does have the ability for you to try out your HTML right there.

A: Try a "fieldset":
<fieldset>
    <legend>caption goes here</legend>
</fieldset>

A: You could do some styling on the fieldset.
Stylesheet.css
fieldset.panel
{
    border: 1px solid #000;
    width: 200px;
}
fieldset.panel input[type=text]
{
    width: 170px;
}

Usage
<fieldset class="panel">
    <legend>User Registration</legend>
    User name:
<input type="text"/>

    Email-id:
<input type="text"/>

    Password:
<input type="text"/>

    Confirm password:
<input type="text"/>

    <input type ="submit" value="Register"/>
</fieldset>

Basically it's using a fieldset but with some basic styling, the css class panel will make the border 1px solid black and the inputs are all going to be 170px width, since the css style will only be applied to the inputs which type is text and being inside a fieldset whose class attribute is panel, translated to css like this: fieldset.panel input[type=text].


text:
Q: использование тега section он связывает содержимое по смыслу, знаю. Можно использовать для верстки комментариев, постов и так далее. Но видел недавно верстку, которая имела примерно следующую структуру:

         любого рода блок кода

         любого рода блок кода

         любого рода блок кода

         любого рода блок кода

был сайт магазина, и верстка была вся в section, то есть каждый блок. Есть ли смысл в такой верстке?


text:
Q: Git: Get changes from master to a remote branch I am working on a project and we have development branches. Lets say we have branches: master, A, B
Let's say that history looks like this right now:
   7
   |
   6  merge commit
   |/ |
   4  |
   |  |
   3  |
   |  |
   a  5   b
    \ | /
      2
      |
      1
      |
      m

where m, a and b are the branches and numbers are just commits. So I did some work on master, then created branch a, then did some work on a AND some work on master and then some work on a and then merged.
**Question is: ** What is the right way to get the commit 5 into branch a?
If it was a local branch I could just
git checkout a
git rebase master

But a is a remote branch and I know it is not safe to mess with remote history like that. What is the correct way of getting changes from master?

A: *

*create a local branch a tracking remote/a

*git checkout a

*git merge master

*git push

You already merged one way; was there a specific reason you reached straight for rebase instead of merge in the other direction?
Is it because you previously used some other VCS with broken merges? If so I can reassure you that git is perfectly capable of finding the common ancestor and performing a sane merge here.

A: Just merge master into a:
git checkout a
git merge master

Done a thousand times, no problem.


text:
Q: MyBatis foreach: there is no getter for property error I'm getting 'there is no getter for property' error while executing foreach loop in mybatis. From the form I am gettin an array of strings (hashtag). In my PostInfoVO, I have a list of string like this:
private List<String> hashtags;

and its getters and setters like this:
public List<String> getHashtags() {
    return hashtags;
}
public void setHashtags(List<String> hashtags) {
    if (this.items == null)
        this.items = new ArrayList<String>();
}

I checked that the list of hashtags is passing data to cotroller by logging postvo.getHashtags().toString().
In my MyBatis file, I have the following foreach loop which is returning 'there is no getter for property hashtag in PostInfoVO.
<![CDATA[
  BEGIN
  <foreach collection="hashtags" item="hashtag" separator=",">
  INSERT INTO TBL_HASHTAG_INFO(post_id, hashtag)
  VALUES
  ((SELECT post_id FROM TBL_POST_INFO ORDER BY post_id DESC LIMIT 1), #{hashtag})
  </foreach>;
  ]]>
  END;

List of things I tried:

*

*Removing Begin and end

*Taking Insert statement out of foreach loop

*Open="(", Close=")"
Any advice would be appreciated! Thank you so much.

A: There are two problems in your code : your field name is hashtags but you used this.items in setter method and with this setter method you implemented the argument of setter method never assigns to the hashtags(field) ,Edit it as below :
public void setHashtags(List<String> hashtags) {
    this.hashtags = hashtags;
}


text:
Q: Why does the plastic constant appear in the snub icosidodecadodecahedron? The golden ratio,
$$\phi =\frac{1+\sqrt{5}}{2}$$
appears (among other polyhedra) in the Platonic solids icosahedron and dodecahedron, and it's quite easy to see the significance of the discriminant $d_\phi = 5$ in those two solids. Both $\phi$ and the plastic constant,
$$P=\frac{(9+\sqrt{3d})^{1/3}+(9-\sqrt{3d})^{1/3}}{2^{1/3}\cdot9^{1/3}}=1.324717\dots$$
with $d = 23$, can be found in the vertices of the snub icosidodecadodecahedron,
$\hskip2.8in$
$\hskip1.3in$(Image courtesy of wikipedia and Robert Webb's Stella software)
This may be a silly question, but why does $P$ appear here? And does $d = 23$ have any geometric significance to that solid? Note that $P$ is also,
$$P = \frac{e^{\pi i/24}}{\sqrt{2}}\frac{\eta(\tau)}{\eta(2\tau)}=1.324717\dots$$
$$\tau = \frac{1+\sqrt{-23}}{2}$$
where $\eta(\tau)$ is the Dedekind eta function.


text:
Q: How to show avatar and username (not only full name) on the login screen? I used ubuntu tweak to change the login background, but I need these other things as well:

*

*Show username (not only full name) and avatar if possible, in the login screen

Any ideas how to achieve this?

A: Try this.

*

*Get your image or avatar, make sure its a sensible size e.g. 96×96 pixels. If not, edit with your preferred image manipulator program, such as GIMP.

*Copy it to your home directory

*Rename it .face

*Logout and then see your new avatar on the login in screen.

*The same icon also shows up when you go into Users and Groups.


text:
Q: XSLT: Image Link I have been supplied with a XSLT feed by link which belongs to a agency we do work for.
The part I am stuck on is displaying the images and making them into links which go to the image in full view.
I have managed to display the image, but because I am cycling through the images, I am then unable to reuse that node as the link. Sorry if this does not make much sense. Here is the code:
 <xsl:for-each select="PHOTOS/IMAGEFILENAME">
 <xsl:element name="a">
 <xsl:attribute name="href">
 <xsl:value-of select="IMAGEFILENAME" />
 </xsl:attribute>

 <xsl:attribute name="target">_blank</xsl:attribute>

 <xsl:attribute name="src"><xsl:value-of select="IMAGEFILENAME" />
 <xsl:apply-templates/>
 </xsl:attribute>
 <xsl:attribute name="width">63px</xsl:attribute>
 <xsl:attribute name="cursor">pointer</xsl:attribute>
 <xsl:attribute name="border">0</xsl:attribute>
 <xsl:attribute name="id"></xsl:attribute>

 </xsl:element>

 </xsl:for-each>

And here is the data it is trying to access:
      -<PHOTOS>
      <IMAGEFILENAME>http://test.co.uk/test1.jpg</IMAGEFILENAME
      <IMAGETHUMBFILENAME/>
      <IMAGECAPTION>Reception area (Main)</IMAGECAPTION>
      <PRINTQUALITYIMAGE>hhttp://test.co.uk/test2.jpg</PRINTQUALITYIMAGE>
      <IMAGEFILENAME>http://test.co.uk/test3.jpg</IMAGEFILENAME>
      <IMAGETHUMBFILENAME/>

So I need to establish how to use the <IMAGEFILENAME> as a link. Thanks

A: Does
<xsl:for-each select="PHOTOS/IMAGEFILENAME">

</xsl:for-each>

do what you want?


text:
Q: Pass style attribute to less mixin Is it possible to pass a generic string to a mixin in less? I am used to passing values like:
.border-radius (@radius) {
    -webkit-border-radius: @radius;
    -moz-border-radius: @radius;
    -ms-border-radius: @radius;
    -o-border-radius: @radius;
    border-radius: @radius;
}

However I now find I want to do something like this:
.makeRed (@style) {
    @style: red;
}
.makeRed('border-color');

I have tried the above but it does not work, it doesn't throw a compile error it just doesnt compile anything.
Ideas?

A: Yes, you can pass property names to a mixin and assign values to it using property name interpolation in Less.
The mixin value should be referenced like a string within curly braces (@{style}). Also, the mixin call should be made from within a selector block because otherwise parameteric mixins would not produce any output when compiled.
.makeRed (@style) {
    @{style}: red; // using the parameter
}

#id{ // selector block
    .makeRed(border-color); // mixin call with no quotes
}

Note: This method will work only from Less v1.6.0 and above.


text:
Q: firefox-headless contol box is missing from screenshot - selenium - linux I am facing exactly same problem https://github.com/mozilla/geckodriver/issues/1358.
Firefox-headless mode screenshots taken from linux are missing  input box
Question:
Do we have any alternative to solve this problem. I am using FF 83

A: You saw it right. For Selenium driven GeckoDriver initiated firefox Screenshot in headless mode doesn't show form controls correctly.
This issue was closed as the original issue is with Firefox and being tracked through Some input field are black when taking screenshot in headless mode is specific to linux platform where @Michael Smith mentioned:

It looks like this is a result of an nsITheme object not being created
in headless mode under
GTK,
as nsNativeThemeGTK depends on APIs which we can't access in headless
mode. As a result this shouldn't affect the Windows and macOS
platforms.

Further he detailed:

We have existing fallback paths for when a nsITheme object is
unavailable, but it looks like they're not being exercised on any of
Windows, macOS, or Linux under normal conditions. For example, the
width of the dropdown button is determined by the width of the
scrollbar in the dropdown list. This is measured by
GetNondisappearingScrollbarWidth,
which boils down to asking the vertical scrollbar nsBoxFrame what its
preferred width
is.
Normally this ends up being calculated using
nsITheme::GetMinimumWidgetSize which calls out to platform-specific
code; in the absence of a theme, we rely on the computed size from the
CSS applied to the scrollbar XUL element and its children. Note that
vertical scrollbar thumbs have a minimum height
assigned,
but no minimum width, so the computed scrollbar width ends up being 0,
and the dropdown buttons end up being 0-width. Adding a minimum width
to thumb[orient="vertical"] causes the dropdown buttons to show up
under headless mode. It also causes the scrollbar to show up along the
side, but there's no color set for the slider, so it's just a white
strip.

Conclusion
This issue was assigned Priority 3 and is still in Open state with no alternatives.

A: This can be solved using firefox settings.
widget.disable-native-theme-for-content to true
Reference :
https://www.reddit.com/r/firefox/comments/k2nghh/any_alternatives_for_firefoxlinuxheadless/
PS: Credit goes to reddit user who answered my question :)
I verified it is working.


text:
Q: Turn off mouse LED lights on linux I have a Logitech G302, a fine mouse. However, it glows blue, and the intensity increases and decreases. This can be distracting and I would like to turn off the lighting inside the mouse. How can I do this? The software that normally controls it is only available for OSX and Windows.

A: I couldn't get Piper installed. However, this worked for me, for a G102 Mouse:
git clone https://github.com/smasty/g203-led.git
cd g203-led
virtualenv ./env
env/bin/pip install -r requirements.txt
sudo ./g203-led.py solid 000000

I presume it'll work for the G203, since that's what it's designed for, and presumably it'll work for other G-series mice, including the G302.

A: Since most Logitech gaming mice store the mouse profile and settings on the mouse, you can use a Windows or Mac OS to install the Logitech Gaming Software and configure your mouse how you want it. Once you're done, you can unplug the mouse and plug it into the Linux system, and it will still have the same desired behavior.
If you only have access to a Linux OS and you want to change your mouse configuration, you can try to download and install Piper mouse configuration utility.

A: https://github.com/green5/g102-dpi-color

Logitech G102 dpi to mouse color mapper


text:
Q: Assign a particular id for dataframe matching a regex pattern Need to assign a particular id for each dataframe matching the below conditions
fd = df[(df['B'].str.match('.*Color:.*') | df['B'].str.match('.*colorFUL:.*')) & df.A.isnull()]
fd2 = df[(df['B'].str.match('.*Type:.*')) & df.A.isnull()]

In the output file, both dataframes are getting written one below other. Need to add a column C where ID '1' is assigned to fd and ID '2' is assigned to fd2. This would be helpful in filtering the dataframes.
This is the current output
A   B
nan this has Color:Red
nan Color: Blue,red, green
nan Color: Yellow
nan This has many colors. Color: green, red, Yellow
nan Filter oil Type: Synthetic Motor oil
nan Oil Type : High Mileage Motor oil

Expected Output
A   B   C
nan this has Color:Red  1
nan Color: Blue,red, green  1
nan Color: Yellow   1
nan This has many colors. Color: green, red, Yellow 1
nan Filter oil Type: Synthetic Motor oil    2
nan Oil Type : High Mileage Motor oil   2

A:
Adding a new column C and assigning ID '1' or '2' to that column based on the dataframe matching the regex.

In [17]: df
Out[17]:
    A                                                B
0 NaN                               this has Color:Red
1 NaN                           Color: Blue,red, green
2 NaN                                    Color: Yellow
3 NaN  This has many colors. Color: green, red, Yellow
4 NaN             Filter oil Type: Synthetic Motor oil
5 NaN                Oil Type : High Mileage Motor oil

You constructed two conditions:
In [18]: one = (df['B'].str.match('.*Color:.*') | df['B'].str.match('.*colorFUL:.*')) & df.A.isnull()

In [19]: one
Out[19]:
0     True
1     True
2     True
3     True
4    False
5    False
dtype: bool

In [20]: two = (df['B'].str.match('.*Type:.*')) & df.A.isnull()

In [21]: two
Out[21]:
0    False
1    False
2    False
3    False
4     True
5    False
dtype: bool

Here is one way to make a new column.
In [22]: df['C'] = 0

Use the boolean series of your conditions to assign values based on those conditions.
In [23]: df.loc[one,'C'] = 1

In [24]: df.loc[two,'C'] = 2

In [25]: df
Out[25]:
    A                                                B  C
0 NaN                               this has Color:Red  1
1 NaN                           Color: Blue,red, green  1
2 NaN                                    Color: Yellow  1
3 NaN  This has many colors. Color: green, red, Yellow  1
4 NaN             Filter oil Type: Synthetic Motor oil  2
5 NaN                Oil Type : High Mileage Motor oil  0

if df is the input dataframe and fd is the output dataframe matching the pattern, how to directly assign an id to fd without the boolean check

fd = df.loc[one]
fd['C'] = 1


text:
Q: Keep R from automatically grabbing latest version of already installed package? I'm trying to install R package A into a Singularity container with R 3.6.0. Package A needs R package B as a dependency. I originally installed package A with version 1 of package B, and things worked fine. Now, however, I need to rebuild this setup, and it appears that version 2 of package B has come out. For some reason, package B version 2 doesn't build on my machine, and gives random compiler errors that I can't find any reference to online. I can still install version 1 of package B no problem. However, when I try to install package A, it pulls version 2 of package B from CRAN, even though the correct version (version 1) of package B is already installed, thus making the whole thing not work as version 2 of package B fails to build.
How can I tell R to not grab the latest version of package B, and to just use the one already installed? This is on CentOS 7 building inside of a Singularity container. I'm using the standard "install.packages" function to install package A, and the "install_version" command from devtools to install the specific version of package B. I want to stress that package A is still being installed as the same version, and that the entire issue here stems from R pulling the version 2 of package B, even though the same version of package A originally worked fine with version 1 of package B.

A: I would:

*

*Install the older version of package B using install_version

*Install the new package without dependencies using install.packages("A", dependencies=FALSE)

A: The easiest way is to use packages in versions that worked for you before. For that find out the date when it worked at put into repo url.
install.packages(
  "A",
  repos="https://cran.microsoft.com/snapshot/2019-05-15/"
)

Before running that command ensure that B is removed.


text:
Q: Proof that for 2 integers of which their product is 1, then each integer is 1. I am working through my Real Analysis' exercises and have run into one that conceptually is very straight forward but has proven to be somewhat difficult for me. I suppose it is less "Real Analysis" and more just learning to create proofs.
The claim is:
$$\forall p,q\in \mathbb{Z} \:(p>0 \wedge q>0 \wedge pq=1) \implies p=q=1$$
Now my issue is that I'm not really sure what it is appropriate to assume in this circumstance, as I suppose the goal is being able to prove it in the most fundamental way possible.
For example, we know for most elements in the integers, they do not possess a multiplicative inverse, except for 1 and -1. If we applied this, the proof would be pretty easy, but I would say we would be able to extend the proof of our claim to prove this fact itself.
Here's my attempt at a proof:
$$
Assume \:p,q\in\mathbb{Z} \: such \: that \: pq=1 \; and \; p>0 \; and \; q>0
\\Assume  \: for \; a\;contradiction \;that\;p\neq1 \; or \; q\neq1 \; or \; p\neq1 \; and\; q\neq1
\\Then \; 1=|pq|=|p||q|\geq |p| \; and\; 1=|pq|=|p||q|\geq |q|
\\ Then \; 1\geq p\; and \; 1\geq q
\\ p=1 \; or \; p=0 \; and \; q=1\; or\; q=0
\\ But \; this \; is \; a \; contradiction \; as \; p>0\; and \; q>0\; and\; both\; p,q\; cannot \; simultaneously \; be\; 0.
\\ Hence \; \forall p,q\in \mathbb{Z} \:(p>0 \wedge q>0 \wedge pq=1) \implies p=q=1 \; $$
(Sorry can't figure out the QED symbol in LaTeX, clearly not very good at it).
Is this proof solid or would there be a more fundamental method of reaching the conclusion.
Also, would anyone have any good resources that assisted them in really grasping Real Analysis and Proofs in general?
Thanks!

A: Comments:
You never actually use the hypothesis that $p,q\neq 1$ and you're argument doesn't require the use of absolute value signs, since by hypothesis, we have $p,q>0$. Besides, if you start off with the assumption that $p,q\neq 1$ and $p,q>0$, then you should conclude that $p,q\geq 2$. The contradiction you should have reached is $1\geq 2$, which actually utilizes the additional assumption that $p,q\neq 1$ and would make for a sound proof by contradiction.
Alternative Solution (1):
To be more general however, lets just say $p,q\in\mathbb{Z}$ and suppose we have $pq=1$. Aiming for a more direct approach, we notice that if one of $p$ or $q$ were $0$, then we would have $pq=0\neq 1$, so we can assume $p,q\neq 0$. Now, $|p|,|q|\geq 1$, since $p,q\in\mathbb{Z}$. From your argument, we have $$1=|pq|=|p||q|\geq |p|\geq 1\text{ and }1=|pq|=|p||q|\geq |q|\geq 1 $$
so we must have $|p|=|q|=1$.
Now we can immediately check off the four cases that satisfy the previous relation, those being $$p=1,q=1\tag{1}$$ $$p=-1,q=-1\tag{2}$$ $$p=1, q=-1\tag{3}$$ $$p=-1,q=1\tag{4}$$
and conclude that we must have either case $(1)$ or case $(2)$. The cases come directly from the definition of $|\cdot|:\mathbb{R}\to\mathbb{R}$, that being $|x|=\max\{x,-x\}$.
In fact, once you have $|p|=1$, then you can conclude that $p=1$ or $p=-1$ so that $1=q$ or $1=-q$.
Alternative Solution (2):
Let that $p,q\in\mathbb{Z}$ with $p,q>0$ and $pq=1$. We immediately see that $p,q\geq 1$. Assume for contradiction that  $p$ or $q$ is larger than $1$. Without loss of generality, suppose $p > 1$. Write $p$ in terms of its prime factors:
$$p=p_1^{k_1}\cdot p_2^{k_2}\cdots p_n^{k_n}$$
We must have $p_1\geq 2$ since $p_1$ is a positive prime, hence $$1=pq\geq p_1q\geq 2\cdot 1=2$$ a contradiction. Our assumption that $p$ or $q$ was greater than one must be false, hence $p=q=1$.
Alternative Solution (3):
Let $p,q\in\mathbb{Z}$ with $p,q>0$ and $pq=1$. Then $p,q\geq 1$ $\ln(p),\ln(q)\geq\ln(1)=0$. Now we see that $$0=\ln(1)=\ln(pq)=\ln(p)+\ln(q)\geq\ln(p)\geq 0$$
hence $\ln(p)=\ln(1)=0$. Since $\ln$ is injective, then we must have $p=1$. Now $1=pq=q$ so $q=1$.
Alternative Solution (4):
Assuming the same hypothesis as the first solution, we have that $p\mid q$ and $q\mid p$, so there exists non-zero integers $t_1,t_2$ such that $$p=t_1q\text{ and }q=t_2p$$Now, $$t_1q^2=1=t_2p^2$$ and we conclude that because $q^2,p^2>0$, then we must have $t_1,t_2>0$, or equivalently $t_1,t_2\geq 1$. But we also see that if $t_1,t_2>1$, then so are $t_1q^2$ and $t_2p^2$, hence $t_1=t_2=1$. Now we see that $pq=p^2=q^2=1$. Since the only solutions to the polynomial $f(x)=x^2-1$ are $x=\pm 1$, then the result follows.
Alternative Solution (5):
Let $p,q\in\mathbb{Z}$ with $pq=1$. Consider matricies
$$R
=
\begin{bmatrix}
1 && -p\\
q && 1
\end{bmatrix}
,\,\,\,
R^{-1}
=
\frac{1}{1-(-pq)}
\begin{bmatrix}
1 && p\\
-q && 1
\end{bmatrix}
$$
Then $RR^{-1}=I$ so we have
$$RR^{-1}=
\frac{1}{2}
\begin{bmatrix}
2 && p-q\\
0 && 2
\end{bmatrix}
=
\begin{bmatrix}
1 && 0\\
0 && 1
\end{bmatrix}$$
Now we must have $p=q$, implying $p^2-1=0$ and the result follows.
Final Comment:
It would be cool to see a proof done using group or ring theory to show this result as well. I cannot fully see through a proof by those means as of right now, but I believe its likely that it can be done.


text:
Q: Reverse Words at odd position only C# This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?
        for (int i = input.Length - 1; i >= 0; i--)
        {
            if (input[i] == ' ')
            {
                result =  tmp + " " + result;
                tmp = "";
            }
            else
                tmp += input[i];
        }

        result = tmp + " " + result;
        Console.WriteLine(result);

Example input:

"How are you today"

to output:

"How era you yadot"

Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse

A: You can achieve it with the help of LINQ:
var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ",
                 inputWords.Select((w, i) =>
                                         i % 2 == 0
                                         ? w
                                         : new string(w.Reverse().ToArray())
                 ));

Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.
Try it online

A: So far you have a string, like this:
  string input = "I want to reverse all odd words (odd words only!).";

And you, naturally, want to perform the task. Now it's the main question what's an odd word?
If you mean word's position (I at position 0, want at 1 - should be reversed etc.)
then you can use regular expressions to match words and Linq to process them:
  using System.Linq;                     // To reverse single word
  using System.Text.RegularExpressions;  // To match the words within the text

  ...

  // Let's elaborate the test example: add
  //  1. some punctuation - ()!. - to preserve it
  //  2. different white spaces (spaces and tabulation - \t)
  //     to add difficulties for naive algorithms
  //  3. double spaces (after "to") to mislead split based algorithms
  string input = "I want to  reverse all\todd words (odd words only!).";

  int index = 0;                                // words' indexes start from zero

  string result = Regex.Replace(
    input,
   "[A-Za-z']+",                                // word is letters and apostrophes
    match => index++ % 2 == 0
      ? match.Value                             // Even words intact
      : string.Concat(match.Value.Reverse()));  // Odd words reversed

  Console.WriteLine(result);

If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to
    match => match.Value % 2 == 0

Outcome:
  I tnaw to  esrever all    ddo words (ddo words ylno!).

Please, notice, that the punctuation has been preserved (only words are reversed).

A: OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
public static void Main()
{
    string input = "How are you today Laken-C";

     //As pointed out by @Dmitry Bychenko string input = "How are you today";
    //(double space after How) leads to How are uoy today outcome

    input = Regex.Replace(input, @"\s+", " ");
    var inp = input.Split(' ').ToList();

    for (int j = 0; j < inp.Count(); j++)
    {
       if(j % 2 == 1)
       {
           Console.Write(inp[j].Reverse().ToArray());
           Console.Write(" ");
       }
       else
           Console.Write(inp[j] + " ");
    }
}

OUTPUT:

DEMO:
dotNetFiddle

A: try this is perfect working code..
 static void Main(string[] args)
    {
        string orgstr = "my name is sagar";
        string revstr = "";
        foreach (var word in orgstr.Split(' '))
        {
            string temp = "";
            foreach (var ch in word.ToCharArray())
            {
                temp = ch + temp;
            }
            revstr = revstr + temp + " ";
        }

        Console.Write(revstr);
        Console.ReadKey();
    }

Output: ym eman si ragas


text:
Q: kendo grid is not filtered properly I have a kendo grid,and treeview with checkboxes in my application.I want to filter the grid based on treeview checkbox selection,i tried this one but its not working properly
my treeview code is
    $("#treeview").on("change", function (e) {
   var ds = $("#grid").data("kendoGrid").dataSource;
    ds.filter([
    {"logic":"or",
     "filters":[
         {
            "field":"OrderId",
            "operator":"eq",
             }
     ]}    ]);
  });

my fiddle is http://jsfiddle.net/RHh67/66/

A: In treeview on change event you need to catch the checked nodes,and then filter the grid datasource based on your condition with field,operator and value of the treeview selected node.
 $("#treeview").on("change", function (e) {
    var selected = $('#treeview :checked').closest('li');
    var ds = grid.dataSource;
    var filter = {
        logic  : "or",
        filters: []
    };

This is the updated fiddle:
http://jsfiddle.net/RHh67/87/
Cheers,
Happy coding


text:
Q: extjs how to get selected html from textarea I have extjs htmleditor with textarea. ANd i want to get selet html value.
Fiddle is here:
http://jsfiddle.net/DCGRg/76/ - you can trigger event by entering something and adding styles and then clicking on the combobox at toolbar right.
i saw the code like that, but it's not getting me html, just text is getting:
content = selection.extractContents();
        //create span and wrap it around selection
        fontEl = document.createElement("span")
        fontEl.appendChild(content);
        text = fontEl.innerHTML

The question is: how to get html from textarea?

A: InnerHTML only returns only the child contents, outerHTML is return with current note.
For Example:
"sample text" => using innerHTML => sample text
"sample text" => using outterHTML => sample
text
I changed in your code innerHTML as outerHTML like bellow please check the sample
text = fontEl.outerHTML;


text:
Q: Getting DNN Site To Run Locally I am trying to get a DotNetNuke site running locally.
At the moment the site is hosted on a server and is functional.
I downloaded the website to my local computer and tried to compile it in Visual Studio.
I am getting all sorts of build errors and I am having alot of trouble getting it to run.
The version of DotNetNuke is very old. i believe it is version 05.06.02.
Any help or advice would be much appreciated.

A: While you can access some of the DNN code via Visual Studio, first you need to get the site running without Visual Studio.
Here is a good set of instructions on copying and running a site on another computer.
http://www.ifinity.com.au/2012/09/05/Creating_a_test_copy_of_your_DotNetNuke_website
The main things to pay attention too are getting a connection to your database, and making the  IIS site accessible locally.


text:
Q: Scatter plot with colors from dark to bright I want to scatter plot some data with different colors. The first row should be  dark blue and for every row it should get a little bit brighter. Currently I only accomplished to make it from dark blue through some other colors to yellow.
Here is my code:
c = linspace(1,10,length(x));
sz = 25;
scatter(x,y, sz,c,'filled');
colorbar

With the resulting plot.

How can I make a gradual color scale from dark blue to light blue?

A: The reason your points go from blue to yellow is because they use the default colour map: parula. There are various colour maps available, but there isn't a built-in colour map for blues. However, you can easily define it yourself using an RGB-triplet:
n = 30;  % The higher the number, the more points and the more gradual the scale
x = rand(n,1);
y = rand(n,1);
c = linspace(0,1,length(x)).';  % Range from 0 to 1
RGB = zeros(length(x),3);  % Red is zero, green is zero, blue builds up
RGB(:,3) = c;
sz = 25;

scatter(x,y, sz,RGB,'filled');
colormap(RGB) % Sets the correct colours for the colour bar
colorbar

An RGB triplet is a row-vector of three elements: [red green blue], where [0 0 0] is black and [1 1 1] is white. Leaving the first two elements at zero, and letting the third run from 0 to 1 will result in a colour scale from black to pure blue.
Alternatively, if you want to go from black to pure blue to pure white, you can first saturate the blue as before, then leave that at 1 and increase the red and green to 1 gradually and simultaneously in the second half:
n = 30;
x = rand(n,1);
y = rand(n,1);
c = linspace(0,1,floor(length(x))./2).';  % Go to 1 in half the length
RGB = zeros(length(x),3);
RGB(1:floor(length(x)/2),3) = c; % Sets the blue
RGB(floor(length(x)/2)+1:end,1) = c; % Sets the red
RGB(floor(length(x)/2)+1:end,2) = c; % Sets the green
RGB(floor(length(x)/2)+1:end,3) = 1; % Leaves blue at 1
sz = 25;

h1 = scatter(x,y, sz,RGB,'filled');
colormap(RGB);
colorbar