text:
Q: Xcode duplicate symbol '_main' I have a bunch of .O files that I generated from a makefile.u which compiles some .C files. I put all of the .O files into my Xcode project and I receive the below error when it builds:
duplicate symbol '_main' in:
     /Users/.../Objects-normal/arm64/AppDelegate.o
     /Users/.../LIBF2C/main.o
ld: 1 duplicate symbol for architecture arm64

I think I am bit confused because the main.o file is needed for my library, but the error seems to be telling me that I cannot have _main declared twice. So is there a solution for this, am I supposed to rename something to get it to build or any other ideas for how this can get resolved?
For some added context, this is specifically for the f2c libraries. So main.c(->main.o) from libf2c is:
/* STARTUP PROCEDURE FOR UNIX FORTRAN PROGRAMS */

#include "stdio.h"
#include "signal1.h"

#ifndef SIGIOT
#ifdef SIGABRT
#define SIGIOT SIGABRT
#endif
#endif

#ifndef KR_headers
#undef VOID
#include "stdlib.h"
#ifdef __cplusplus
extern "C" {
#endif
#endif

#ifndef VOID
#define VOID void
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifdef NO__STDC
#define ONEXIT onexit
extern VOID f_exit();
#else
#ifndef KR_headers
extern void f_exit(void);
#ifndef NO_ONEXIT
#define ONEXIT atexit
extern int atexit(void (*)(void));
#endif
#else
#ifndef NO_ONEXIT
#define ONEXIT onexit
extern VOID f_exit();
#endif
#endif
#endif

#ifdef KR_headers
extern VOID f_init(), sig_die();
extern int MAIN__();
#define Int /* int */
#else
extern void f_init(void), sig_die(const char*, int);
extern int MAIN__(void);
#define Int int
#endif

static VOID sigfdie(Sigarg)
{
Use_Sigarg;
sig_die("Floating Exception", 1);
}

static VOID sigidie(Sigarg)
{
Use_Sigarg;
sig_die("IOT Trap", 1);
}

#ifdef SIGQUIT
static VOID sigqdie(Sigarg)
{
Use_Sigarg;
sig_die("Quit signal", 1);
}
#endif

static VOID sigindie(Sigarg)
{
Use_Sigarg;
sig_die("Interrupt", 0);
}

static VOID sigtdie(Sigarg)
{
Use_Sigarg;
sig_die("Killed", 0);
}

#ifdef SIGTRAP
static VOID sigtrdie(Sigarg)
{
Use_Sigarg;
sig_die("Trace trap", 1);
}
#endif

int xargc;
char **xargv;

#ifdef __cplusplus
    }
#endif

 int
#ifdef KR_headers
main(argc, argv) int argc; char **argv;
#else
main(int argc, char **argv)
#endif
{
xargc = argc;
xargv = argv;
signal1(SIGFPE, sigfdie);   /* ignore underflow, enable overflow */
#ifdef SIGIOT
signal1(SIGIOT, sigidie);
#endif
#ifdef SIGTRAP
signal1(SIGTRAP, sigtrdie);
#endif
#ifdef SIGQUIT
if(signal1(SIGQUIT,sigqdie) == SIG_IGN)
    signal1(SIGQUIT, SIG_IGN);
#endif
if(signal1(SIGINT, sigindie) == SIG_IGN)
    signal1(SIGINT, SIG_IGN);
signal1(SIGTERM,sigtdie);

#ifdef pdp11
    ldfps(01200); /* detect overflow as an exception */
#endif

f_init();
#ifndef NO_ONEXIT
ONEXIT(f_exit);
#endif
MAIN__();
#ifdef NO_ONEXIT
f_exit();
#endif
exit(0);    /* exit(0) rather than return(0) to bypass Cray bug */
return 0;   /* For compilers that complain of missing return values; */
        /* others will complain that this is unreachable code. */
}
#ifdef __cplusplus
}
#endif


text:
Q: Is there a way to use QMetaEnum with Q_ENUMS belonging to non Q_OBJECT or Q_GADGET class? For example I have the following class:
namespace someName
{
    class someClass
    {
        Q_ENUMS(ESomeEnum)

        public:
        enum ESomeEnum {ENUM_A, ENUM_B, ENUM_C};

        // ... some other things ..
    }
}

Q_DECLARE_METATYPE(someName::someClass)

Is there a way to use QMetaEnum::valueToKey or QMetaEnum::keyToValue ?
Tried the method in this answer but got the following error:

error: static assertion failed: QMetaEnum::fromType only works with enums declared as Q_ENUM or Q_FLAG
#define Q_STATIC_ASSERT_X(Condition, Message) static_assert(bool(Condition), Message)

I can employ X-Macros to get my desired output but it would also be nice to learn  more tricks in Qt.

A: No, there isn't, because Q_ENUM's functionality is implemented in code generated by moc, and moc ignores classes that are neither Q_OBJECT nor Q_GADGET. There's no reason for not using a Q_GADGET since it has no effect on object size: adds no virtual methods nor data fields.
The following demonstrates this:
#include <QtCore>

namespace Ns {
class Class {
   Q_GADGET
public:
   enum ESomeEnum {ENUM_A, ENUM_B, ENUM_C};
   Q_ENUM(ESomeEnum)
};
}

int main() {
   auto metaEnum = QMetaEnum::fromType<Ns::Class::ESomeEnum>();
   qDebug() << sizeof(Ns::Class) << metaEnum.valueToKey(Ns::Class::ENUM_A);
}
#include "main.moc"

Output:
1 ENUM_A

On this particular platform (and many others), empty classes are of size 1.

A: Yes, since 5.8 you can do:
namespace MyLibrary
{
Q_NAMESPACE

enum class MYLIBRARYSHARED_EXPORT MyEnumClass
{
...
};

Q_ENUM_NS(MyEnumClass)

...
} // namespace MyLibrary

A: Q_ENUM is like the old Q_ENUMS but with these differences:

*

*It needs to be placed after the enum in the source code.

*Only one enum can be put in the macro.

*It enables QMetaEnum::fromType<T>().

*These enums are automatically declared as a QMetaTypes (no need to
add them in Q_DECLARE_METATYPE anymore).

*enums passed to qDebug will print the name of the value rather than
the number.

*When put in a QVariant, toString() gives the value name. The value name
is printed by QCOMPARE (since Qt 5.6)

Taken from WOBOQ blog post on the topic, read it for additional information regarding Q_ENUM vs Q_ENUMS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modified Knapsack/Subset-Sum with same weight/values I was working on a problem that has to deal with a special case of the Knapsack/Subset-Sum Problem. The problem is as follows:
You have a set of bundle sizes in decreasing sizes that are random like: {47, 35, 22, ...}. You have value that is the quantity of widgets like: #widgets = 33.
Find the least number of bundles that can make up the number of widgets for the bundle. If there is no way to return set that equals quantities then return null.

*

*Example 1:

*

*Bundle Sizes: 46, 25, 12, 4, 3

*quantity: 30

*Returned Value: {46:0, 25:0, 12:2, 4:0, 3:2} (bundle size:# of bundles)

*Example 2:

*

*Bundle Sizes: 46, 25, 12, 4, 3

*quantity: 17

*Returned Value: {46:0, 25:0, 12:0, 4:2, 3:3}

*Example 3:

*

*Bundle Sizes: 46, 25, 12, 4, 3

*quantity: 47

*Returned Value: {46:0, 25:1, 12:1, 4:1, 3:2}

*Example 4:

*

*Bundle Sizes: 46, 25, 12, 4, 3

*quantity: 5

*Returned Value: null

How would go about this problem?
I have written a program in C# that does close enough job but resets an index in a for loop to dump bundle sizes that will not work with the rest of the set. Will post source if requested for how far it goes.
Requested code:
public List<int> BreakDown(List<int> bunSize, int buySize)
    {
        List<int> tempBunSize = bunSize.ToList();
        tempBunSize.RemoveAll(e => e > buySize);

        List<int> ammountNeeded = new List<int>();
        int result = buySize;

        for (int index = 0; index < tempBunSize.Count; index++)
        {
            int size = tempBunSize[index];
            int tempResult = 0;
            double calcResult = 0;
            int addAmmount = 0;

            if (index == tempBunSize.Count - 2)
            {
                tempResult = result % size;

                if ((tempBunSize.Count > 2 || result % tempBunSize[tempBunSize.Count - 1] == 0))
                {
                    if (result % size != 0)
                    {
                        ammountNeeded.Add(0);
                        tempResult = result % tempBunSize[tempBunSize.Count - 1];

                        if (tempResult != 0)
                        {
                            tempResult = result;
                            int sizeInc = 0;
                            while (tempResult != 0)
                            {
                                tempResult = tempResult - size;
                                sizeInc++;
                                if (tempResult < 0)
                                {
                                    int decreaseOne = ammountNeeded.First();
                                    ammountNeeded[0] = --decreaseOne;
                                    result = result + tempBunSize.First();
                                    if (ammountNeeded[0] <= 0)
                                    {
                                        tempBunSize.RemoveAt(0);
                                        index = 0;
                                        ammountNeeded = new List<int>();
                                    }
                                    ammountNeeded.Remove(0);
                                    --index;
                                    break;
                                }
                                if (tempResult % tempBunSize[tempBunSize.Count - 1] == 0)
                                {
                                    ammountNeeded.Remove(0);
                                    ammountNeeded.Add(sizeInc);
                                    ammountNeeded.Add(tempResult / tempBunSize[tempBunSize.Count - 1]);
                                    break;
                                }
                            }
                            if (tempResult < 0) continue;
                            break;
                        }
                        else
                        {
                            calcResult = result / tempBunSize[tempBunSize.Count - 1];
                            addAmmount = (int)Math.Floor(calcResult);
                            ammountNeeded.Add(addAmmount);
                            break;
                        }
                    }
                    else if (result % size == 0)
                    {
                        tempResult = result % size;
                        if (tempResult != 0 && result % tempBunSize[tempBunSize.Count - 1] != 0)
                        {
                            int decreaseOne = ammountNeeded.First();
                            ammountNeeded.Insert(0, --decreaseOne);
                            result = result + tempBunSize.First();
                            continue;
                        }
                        else
                        {
                            calcResult = result / size;
                            addAmmount = (int)Math.Floor(calcResult);
                            ammountNeeded.Add(addAmmount);

                            if (result % size == 0)
                            {
                                ammountNeeded.Add(0);
                                break;
                            }
                            calcResult = result / tempBunSize[tempBunSize.Count - 1];
                            addAmmount = (int)Math.Floor(calcResult);
                            ammountNeeded.Add(addAmmount);
                            break;
                        }
                    }
                }
                else if (tempResult % tempBunSize[tempBunSize.Count - 1] != 0)
                {
                    tempResult = result;
                    int sizeInc = 0;
                    while (tempResult != 0)
                    {
                        tempResult = tempResult - size;
                        sizeInc++;
                        if (tempResult % tempBunSize[tempBunSize.Count - 1] == 0)
                        {
                            ammountNeeded.Add(sizeInc);
                            ammountNeeded.Add(tempResult / tempBunSize[tempBunSize.Count - 1]);
                            break;
                        }

                    }
                    break;
                }
                else if (result == 0)
                {
                    while (ammountNeeded.Count < bunSize.Count)
                    {
                        ammountNeeded.Add(0);
                    }
                    break;
                }
                else
                {
                    calcResult = result / size;
                    ammountNeeded.Add((int)Math.Floor(calcResult));

                    calcResult = tempResult / tempBunSize[tempBunSize.Count - 1];
                    ammountNeeded.Add((int)Math.Floor(calcResult));
                    break;
                }
            }
            ammountNeeded.Add((int)Math.Floor((decimal)result / size));
            result = result % size;
            if (result == 0) continue;

        }

        if (ammountNeeded.Count < bunSize.Count)
        {
            ammountNeeded.Reverse(0, ammountNeeded.Count);
            while (ammountNeeded.Count < bunSize.Count)
            {
                ammountNeeded.Add(0);
            }
            ammountNeeded.Reverse(0, ammountNeeded.Count);
        }
        if (ammountNeeded.FindLast(e => e < 0) < 0 || ammountNeeded.Sum() == 0)
            return null;
        return ammountNeeded;
    }
}

A: This was a FUN problem to solve.  Geek points all around.
Your main problem I believe is in trying to loop through a single list.  Really what you want here is to test all variations of the list then find the one with the highest values.
Also, as is stated in the comments, recursion is your friend here.  I recursed through each permutation of the bundle amounts.
One problem that your data has is that of your 17 example.  The math used in this example is greedy.  Meaning, 4 is going to try to get as many as it can before it hands off the remainder to 3.  4 therefore gets 4 bundles and with 1 remainder a null is returned.  For this reason I think the correct answer to 17 should be null.  You might be able to figure out how to balance between numbers, but that'll be a whole lot more logic IMO.
Here is the code:
public class test
{
    public static void Main()
    {
        var bundleSizes = new List<int> { 46, 25, 12, 4, 3 };

        var quantity = 30;
        var bundleResults = Begin(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        quantity = 17;
        bundleResults = Begin(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        quantity = 47;
        bundleResults = Begin(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        quantity = 5;
        bundleResults = Begin(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        Console.Read();
    }

    static void Output(List<int> bundleSizes, int quantity, Dictionary<int, int> bundleResults)
    {
        var fullResults = new Dictionary<int, int>();
        bundleSizes.ForEach(
            delegate(int e)
                {
                    var result = 0;
                    if(bundleResults != null)
                        bundleResults.TryGetValue(e, out result);
                    fullResults.Add(e, result);
                });
        Console.WriteLine("Bundle Sizes: {0}", string.Join(",", bundleSizes));
        Console.WriteLine("Quantity: {0}", quantity);
        Console.WriteLine("Returned Value: {0}", bundleResults == null ? "null" : fullResults.Aggregate("", (keyString, pair) => keyString + pair.Key + ":" + pair.Value + ","));
    }

    static Dictionary<int, int> Begin(List<int> bundleSizes, int quantity)
    {
        var bundleCombinations = GetCombination(bundleSizes);
        var tempBundleSizes = new List<Dictionary<int, int>>();
        foreach (var bundleCombination in bundleCombinations)
        {
            var tempBundleSize = new Dictionary<int, int>();
            bundleCombination.ForEach(e => tempBundleSize.Add(e, 0));
            var results = Bundle(bundleCombination, quantity);
            if (results == null)
                continue;
            foreach (var result in results)
            {
                tempBundleSize[result.Key] = result.Value;
            }
            tempBundleSizes.Add(tempBundleSize);
        }
        var longest = tempBundleSizes.OrderByDescending(x => x.Count).FirstOrDefault();
        return longest;
    }

    static List<List<int>> GetCombination(List<int> list)
    {
        var retValue = new List<List<int>>();
        var count = Math.Pow(2, list.Count);
        for (var i = 1; i <= count - 1; i++)
        {
            var retList = new List<int>();
            var str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
            for (var j = 0; j < str.Length; j++)
            {
                if (str[j] == '1')
                {
                    retList.Add(list[j]);
                }
            }
            retValue.Add(retList);
        }
        return retValue;
    }

    static Dictionary<int, int> Bundle(List<int> bundleSizes, int quantity)
    {
        var bundleQuantities = new Dictionary<int, int>();
        bundleSizes.ForEach(delegate(int k)
        {
            if (k <= quantity)
                bundleQuantities.Add(k, 0);
        });
        return bundleQuantities.Count == 0 ? null : RecurseBundles(quantity, bundleQuantities.Keys.ToList(), bundleQuantities);
    }

    static Dictionary<int, int> RecurseBundles(int quantity, List<int> bundleSizes, Dictionary<int, int> bundleQuantities)
    {
        var bundleSize = bundleSizes.First();
        var bundles = (int)Math.Floor((double)quantity / bundleSize);
        var remainingQuantity = quantity % bundleSize;
        bundleQuantities[bundleSize] = bundles;
        var remainingBundles = bundleSizes.Skip(1).ToList();
        if (!remainingBundles.Any() && remainingQuantity > 0)
            bundleQuantities = null;
        if (remainingBundles.Any())
            bundleQuantities = RecurseBundles(remainingQuantity, remainingBundles, bundleQuantities);
        return bundleQuantities;
    }
}

Here is the output:
Bundle Sizes: 46,25,12,4,3
Quantity: 30
Returned Value: 46:0,25:0,12:2,4:0,3:2,
Bundle Sizes: 46,25,12,4,3
Quantity: 17
Returned Value: null
Bundle Sizes: 46,25,12,4,3
Quantity: 47
Returned Value: 46:0,25:0,12:3,4:2,3:1,
Bundle Sizes: 46,25,12,4,3
Quantity: 5
Returned Value: null

Special thanks to these fantastic SO answers:
All Possible Combinations of a list of Values
How do I combine the keys and values of a Dictionary into one List using LINQ?
Find max count of a list of custom types
EDIT: Made a small change for a better formatted output in the Output method

A: Worked more on the solution and thanks to a co-worker and paqogomez's answer we got the correct code that works for all my examples and more! My co-worker showed me that you can use a stack in place of recursion and use the stack to keep track of the index that looks to the left and right of the bundle list. This code uses a Greedy Brute-force solution, if there is a faster way I will be interested!
C# Code:
class Program
{
    public static void Main()
    {
        List<int> bundleSizes = new List<int> { 46, 25, 12, 4, 3 };
        int quantity = 30;
        Dictionary<int, int> bundleResults = StackThis(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        quantity = 17;
        bundleResults = StackThis(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        quantity = 47;
        bundleResults = StackThis(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        quantity = 5;
        bundleResults = StackThis(bundleSizes, quantity);
        Output(bundleSizes, quantity, bundleResults);

        Console.Read();
    }

    // Reused paqogomez output
    static void Output(List<int> bundleSizes, int quantity, Dictionary<int, int> bundleResults)
    {
        var fullResults = new Dictionary<int, int>();
        bundleSizes.ForEach(
            delegate(int e)
            {
                var result = 0;
                if (bundleResults != null)
                    bundleResults.TryGetValue(e, out result);
                fullResults.Add(e, result);
            });
        Console.WriteLine("Bundle Sizes: {0}", string.Join(",", bundleSizes));
        Console.WriteLine("Quantity: {0}", quantity);
        Console.WriteLine("Returned Value: {0}", bundleResults == null ? "null" : fullResults.Aggregate("", (keyString, pair) => keyString + pair.Key + ":" + pair.Value + ","));
    }

    static private Dictionary<int, int> StackThis(List<int> usableBundle, int currentQuantity)
    {
        // Order the list from largest bundle size to smallest size
        List<int> arrUsableBundles = usableBundle.OrderByDescending(x => x).ToList();

        // Key: Bundles | Value: Quantity
        Dictionary<int, int> hmBundleToQuantity = new Dictionary<int, int>();

        // Create the hashmap table structure
        foreach (int Bundle in arrUsableBundles)
        {
            hmBundleToQuantity.Add(Bundle, 0);
        }

        // Keep track of our index of the bundles we need to figure out
        Stack<int> stBundleIndex = new Stack<int>();

        // Used to calculate the left and right of bundle list
        int ixCursor;

        // Our remaining quantity after calculations
        int iRemaining;

        /*
            This will act as the midpoint of the bundle list
            Will update the right of the cursor, decrement the
            cursor, don't touch the left, and since the loop
            hasn't started we'll consider everything updatable
            and on the right of the cursor
        */
        stBundleIndex.Push(-1);

        // Keep working till there is no more ways to solve the solution
        while (stBundleIndex.Count > 0)
        {
            // The current cursor is always removed and needs to
            // be added back if we want to check it again
            ixCursor = stBundleIndex.Pop();

            iRemaining = currentQuantity;

            for (int ixBundle = 0; ixBundle < usableBundle.Count; ++ixBundle)
            {
                //Left of current scope, values remain the same
                if (ixBundle < ixCursor)
                {
                    iRemaining -= (hmBundleToQuantity[usableBundle[ixBundle]] * usableBundle[ixBundle]);
                }

                //At the cursor stack scope – decrement current quantity
                if (ixBundle == ixCursor)
                {
                    --hmBundleToQuantity[usableBundle[ixBundle]];
                    iRemaining -= (hmBundleToQuantity[usableBundle[ixBundle]] * usableBundle[ixBundle]);
                }

                //Right of current scope gets calculated
                if (ixBundle > ixCursor)
                {
                    hmBundleToQuantity[usableBundle[ixBundle]] += iRemaining / usableBundle[ixBundle];
                    iRemaining = iRemaining % usableBundle[ixBundle];
                }
            }

            if (iRemaining == 0) return hmBundleToQuantity;

            // Otherwise… We have nothing left on the stack we'll check
            // back to the beginning for non-zero values
            int iNonEmptyStart = 0;

            //Keep the current scope on the stack if the quantity is still bigger than zero
            if (ixCursor >= 0 && hmBundleToQuantity[usableBundle[ixCursor]] > 0)
            {
                stBundleIndex.Push(ixCursor);

                // Maximum cursor on the stack
                // (this way we don't decrement further back than we want)
                iNonEmptyStart = stBundleIndex.Max();
            }

            //Add last non-empty value to the stack to decrement and recalculate from there
            for (int ixNonEmpty = usableBundle.Count - 1; ixNonEmpty >= iNonEmptyStart; ixNonEmpty--)
            {
                if (hmBundleToQuantity[usableBundle[ixNonEmpty]] > 0)
                {
                    stBundleIndex.Push(ixNonEmpty);
                    break;
                }
            }
        }
        return null;
    }
}

Once again thanks for all the help on this and special thanks to my co-worker and paqogomez on some help to the solution!


text:
Q: How to change titles/contents for TabSpec in TabHost? I have been developing application which uses following code for making TabHost:
TabHost.TabSpec spec=mTabHostCategories.newTabSpec("Main");
spec.setIndicator("Main");
spec.setContent(R.id.listViewMain);
mTabHostCategories.addTab(spec);

mTabSpecFirst=mTabHostCategories.newTabSpec("First");
mTabSpecFirst.setContent(R.id.listViewFirst);
mTabSpecFirst.setIndicator(mCategoryFirst);
mTabHostCategories.addTab(mTabSpecFirst);

mTabSpecSecond=mTabHostCategories.newTabSpec("Second");
mTabSpecSecond.setContent(R.id.listViewSecond);
mTabSpecSecond.setIndicator(mCategorySecond);
mTabHostCategories.addTab(mTabSpecSecond);

mTabHostCategories.setCurrentTab(0);

But then I need to change titles (indicators) and content for TabSpecs. How can I do it? Thank you.

A: you need to change title in your mCategoryFirst
or simple pass a new TextView with your desired title to your TabSpec objects

A: Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = getTabHost(); // The activity TabHost
    TabHost.TabSpec spec; // Resusable TabSpec for each tab
    Intent intent; // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, TodaysTakeDemoActivity.class);
    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("todaystake").setIndicator("Todays Take",
            res.getDrawable(R.drawable.icontodaystake)).setContent(intent);
    tabHost.addTab(spec);

    // Do the same for the other tabs
    intent = new Intent().setClass(this, WhatsCasting.class);
    spec = tabHost.newTabSpec("whatscasting").setIndicator(
            "What's Casting", res.getDrawable(R.drawable.iconwhatscasting))
            .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, Contacts.class);
    spec = tabHost.newTabSpec("contacts").setIndicator("Contacts",
            res.getDrawable(R.drawable.iconcontact)).setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, TopListActivity.class);
    spec = tabHost.newTabSpec("actortools").setIndicator("Actor Tools",
            res.getDrawable(R.drawable.icontop10)).setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);


text:
Q: spdlog custom log tags I would like to add some extra data to my log output depending on where it was logged. For instance I might have System A and System B, both spitting out log data, but perhaps I'm only interested in System B's log lines now so I could filter based on the tag.
In a previous system I had a log function that looked like LOG(level, tag, message) but I could also see a solution that could involve instantiating a logger with a tag for each system that would pipe to a default logger that catches all messages. So spdlog::tagged_logger systemALogger("System A");
This is almost the answer since loggers can have names, I could use the names as a tag, but can loggers redirect to a default logger? The default logger has several sinks that I would have to attach to the named logging solution.
So the final question would be, is there a way to add a custom tag to log messages in spdlog?

A: Once you have your log configured, you can clone() it and pass a custom logger name that will appear in the log output (given you have not change the formatting).
  auto logger = spdlog::default_logger()->clone("my_logger");
  logger->info("message from custom logger");
  spdlog::info("message from default logger");

The contents of the basic-log.txt is as follows:
[2020-12-02 09:35:58.801] [my_logger] [info] message from custom logger
[2020-12-02 09:35:58.802] [info] message from default logger


text:
Q: SourceBuffer's appendBuffer() not appending arrayBuffer Context:
1.) Confirmed that the backend is returning a range of bytes using StreamingResponseBody (I'm using spring boot) via 206 response code
2.) Confirmed that the received data makes sense, I think, by comparing the logs displayed here chrome://media-internals/ with the logs displayed when I play any YouTube video. I attached some pictures to show this.
3.) On the frontend, byte stream gets converted into an arrayBuffer via response.arrayBuffer()
4.) Confirmed that the video's codec profile is video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41" . Used mp4box (https://github.com/gpac/mp4box.js) to get the codec and profile and confirmed that the browser supports this MediaSource.isTypeSupported('video/mp4; codecs="avc1.64002a"; profiles="mp42,mp41"'); I'm using google chrome to test this.
Issue:
1.) It looks like buffered isn't getting updated, because it's TimeRange length is not changing and that sourceBuffer.buffered.end(0) and sourceBuffer.buffered.start(0) remains undefined
2.) And because of the previous issue, <video /> doesn't play.
Using a callback getVideoStreamResourceAPI to receive the arrayBuffer, the following is my code
getVideoStreamResourceAPI(pathVariables, identityPayload, resp => {
                    const mediaSource = new MediaSource();
                    videoRef.current.src = URL.createObjectURL(mediaSource);
                    mediaSource.addEventListener('sourceopen', sourceOpen, {once: true});

                    function sourceOpen() {
                        URL.revokeObjectURL(videoRef.current.src);
                        var sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41"');

                        sourceBuffer.addEventListener('update', sourceBufferUpdate, { once: true });
                        sourceBuffer.appendBuffer(resp);
                        sourceBuffer.addEventListener('updateend', updateEnd, { once: true });
                    }

                    function sourceBufferUpdate(e) {
                        console.log("updated: ", e);
                    }

                    function updateEnd(e) {
                        console.log("updatedEnded: ", e);
                        console.log("buffered: ", videoRef.current.buffered);
                        videoRef.current.addEventListener('playing', fetchNextSegment, { once: true });
                    }

                    function fetchNextSegment() {
                        console.log("fetching next segment");
                    }

                    setSpinner(null);
                });

NOTE:
resp contains the arrayBuffer and fetchNextSegment() isn't getting called.
Any suggestions, ideas, and help would be greatly appreciated. Thanks for taking the time to read this.


text:
Q: Sum up Kills of Player List Basically I have a List of Players:
    final List<String> members = getClanMembers(clan);

Each of the Player has a number of KILLS.
I want to sum that up and get the TOTAL KILLS of all players.
This is what I am doing now:
    Integer kills = 0;
    for (final String plr : members) {
        try {
            final PreparedStatement sel = conn.prepareStatement("SELECT kills FROM Stats WHERE player=?");
            sel.setString(1, plr);
            final ResultSet rs = sel.executeQuery();
            kills += rs.getRow() != 0 ? rs.getInt("kills") : 0;
        } catch (final SQLException e) {
            e.printStackTrace();
        }
    }

However, I think this code is not efficient and I know that you can create variables in MySQL to do that better. (Bad stuff: try catch inside a for-loop, doing too many queries at once)
Could someone give me some tips?
Thanks in advance.
EDIT: I forgot to mention that I ONLY want to sum up the Kills of the Players in the ArrayList, not all Players in the Table.

A: Yes, you can use MySQL to perform the entire SUM() in a single row and column with
SELECT SUM(kills) FROM Stats

Then rs.getInt(1) will return the total across all players.
Edit
Convert the members list into a comma separated list of player_ids, and add a "WHERE player IN" clause to the query above and you'll get the totals only for those players.

A: Use the SUM() function in conjunction with a WHERE player IN ... clause that restricts the summing to only those records in the specified clan.
SELECT SUM(kills) FROM Stats WHERE player IN (?, ?, ?)

Note: You need to insert the correct number of '?' for the number of players in your array, then set those parameters to the player names from your array.
Integer kills = 0;
if(members.size() > 0) {
    StringBuilder sql = new StringBuilder("SELECT SUM(kills) FROM Stats WHERE player in (?");
    for(int index = 1; index < members.size(); index++) {
        sql.append(",?");
    }
    sql.append(")");
    try {
        final PreparedStatement sel = conn.prepareStatement(sql.toString());
        for (int index = 0; index < members.size(); index++) {
            sel.setString(index + 1, members.get(index));
        }
        final ResultSet rs = sel.executeQuery();
        kills = rs.getRow() != 0 ? rs.getInt(1) : 0;
    } catch (final SQLException e) {
        e.printStackTrace();
    }
}


text:
Q: Store character pointer in map in order std::map mymap. Storing it as character or string not an option std::map<char*, int> mymap;
mymap['a'] = 1;
mymap['b'] = 2;
mymap['c'] = 3;

How to print 1, 2, 3 in that particular order  if order of insertion gets changed?
I don't know the insertion order . But the order of output should be same everytime.

A:
I don't know the insertion order . But the order of output should be same everytime.

This is exactly how std::map works. The iterators go through the element in the strict weak ordering induced by the comparator of the map. Insertion order does not affect the order of the iteration.

std::map<char*, int> How to print 1, 2, 3 in that particular order.

The problem here is that a map is ordered by the key rather than by value.
If you need to iterate over elements of a map in value-order, then it seems that you need a multi-index container. Such container can be looked up by one index, and iterated using another index. The C++ standard library does not provide such multi-index containers however.
The idea of multi-index container is quite simple. It consists of nodes just like a list or a tree does, but each node contains multiple sets of links - one for each index. A generic implementation of such container is not quite as simple as the idea is.

mymap['a'] = 1;

You cannot use a char as a lookup argument to a map whose key type is char*.

A: This is probably what you need:
std::map<char, int> mymap;
mymap.emplace(make_pair('a', 1));
mymap.emplace(make_pair('c', 3));
mymap.emplace(make_pair('b', 2));

for(auto& it : mymap)
    cout<<it.second<<endl;

map is sorted based on the keys not the values,  If you need a variable size char then use string
if char* is not optional use shared_ptr:
std::map<std::shared_ptr<char>, int> mymap;
mymap.emplace(make_shared<char>(char('a')), 1);

The main problem you have here is inserting a pointer as key means you always have unique key, for example two pointers point to different addresses in memory but the char stored in those addresses are the same which is not what you want from a map.
if you wanted to keep it sorted based on the values just change the key and value.
sort map by value:
#include <iostream>
#include <memory>
#include <algorithm>
#include <map>
using namespace std;

template<typename A, typename B>
std::pair<B,A> flip_pair(const std::pair<A,B> &p)
{
    return std::pair<B,A>(p.second, p.first);
}

template<typename A, typename B>
std::multimap<B,A> flip_map(const std::map<A,B> &src)
{
    std::multimap<B,A> dst;
    std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()),
                   flip_pair<A,B>);
    return dst;
}

int main(void)
{
    std::map<std::shared_ptr<char>, int> mymap;
    std::shared_ptr<char> a;
    a.reset(new char('a'));
    std::shared_ptr<char> b;
    b.reset(new char('b'));
    std::shared_ptr<char> c;
    c.reset(new char('c'));
    mymap.emplace(make_pair(a, 1));
    mymap.emplace(make_pair(c, 2));
    mymap.emplace(make_pair(b, 3));

    std::multimap<int, std::shared_ptr<char>> dst = flip_map(mymap);
    // dst is now sorted by what used to be the value in src!
    for(auto& it : dst)
       cout<<it.first<<endl;
}

credit of sorting map by value: https://stackoverflow.com/a/5056797/10933809


text:
Q: Why does create-react-app adds specific version of "react-scripts" such as "2.1.3"? npm list -g create-react-app
# 2.1.3
npx create-react-app blah and blach/package.json will be like
# package.json
{
  "name": "blah",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-scripts": "2.1.3" # <==== why no ^ here
  },

SO asks me to add some more as "plain text" is less than pasted package.json bits. Therefore these lines are just to make that algorithm happy.

A: It's just the current version of create-react-app, see https://github.com/facebook/create-react-app/releases
You can upgrade to the latest version with: npm install react-scripts@latest


text:
Q: sqlalchemy query ignoring some rows I have a sqlalchemy query that goes basically like this
for row in session.query(Message).order_by(Message.ts):
    print(row)

This should print both of these rows:
             ts             |    uts     | user  |    message
----------------------------+------------+-------|---------------
 2016-01-20 06:07:38.905547 | 1453270059 | user1 |  REDACTED
 2016-01-20 06:07:39.029675 | 1453270059 | user2 |  REDACTED_UNIQUE

but it is only printing one of them. I can filter by user1 or user2 and get each row individually, but I can't get both of the rows. I am trying to iterate over all rows (6.5 million) and process each one. But ones with similar timestamps like this one keep getting skipped.
Here is the Message class:
class Message(Base):
    __tablename__ = 'log'
    __init__ = Base.__init__

    ts = Column(DateTime)
    uts = Column(BigInteger, primary_key=True)
    user = Column(String(24))
    message = Column(String(512))

A: I figured out that the Message class was what was wrong. Somehow the primary_key got moved from ts to uts. sqlalchemy wasn't choking on my incorrect primary key but was assuming that there were no duplicates in the uts column (which was a problem because the uts column isn't unique). Moving it back to ts (which is a unique column) fixed the problem. The Message class should be:
class Message(Base):
    __tablename__ = 'log'
    __init__ = Base.__init__

    ts = Column(DateTime, primary_key=True)
    uts = Column(BigInteger)
    user = Column(String(24))
    message = Column(String(512))

A: I think You need to add a call to all()
http://docs.sqlalchemy.org/en/latest/orm/query.html
all()
Return the results represented by this Query as a list.
This results in an execution of the underlying query.


text:
Q: How to save Document Reference from Cloud Function in Cloud Firestore? Firestore allows me to add a field with the type "Reference" to a document. It's a reference "link" to other documents inside the Store.
While I imagine this is very handy, I'm missing documentation on it.
I'm having some trouble saving a reference from a Firebase Cloud Function for example.
On the client side, I just send a regular "ref" object via the client SDK and it saved the document-reference. In nodeJS (cloud function), I get an error that the object is too deep.
What's the proper way to save a field with the type reference from the admin SDK (and/or JS client SDK)?

A: The Firebase Admin Node SDK was updated today and fixes this problem. https://github.com/firebase/firebase-admin-node/releases/tag/v5.4.2


text:
Q: How to turn hex code into x86 instructions I'm trying to make a script or program that will take given bytes (given in hexadecimal), and convert them into a x86 instructions (For example c3 -> retq)
I've tried doing it by calling gcc -c on an assembly file just containing
retq
retq

and then using a script to insert bytes where it says "c3 c3", then using objdump -d to see what it says now. But it seems that it messes up the format of the file unless I only pass an instruction of the same size as the original instruction bytes.
I'm running it on a Raspbian Pi (A linux based operating system) using SSH, BASH terminal. I'm using BASH shell scripts and python, as well as the tools listed here, and gdb.

A: Disassemble flat binary file: objdump -D -b binary -m i386 foo.bin. Or create an object file using .byte directives from assembly source, e.g. put .byte 0xc3 into foo.s then gcc -c foo.s then objdump -d foo.o


text:
Q: Routing problem in Ubuntu server 17.10 I'm pretty new to Linux and im trying to set up a virtual lab in Hyper-V with a Ubuntu server 17.10 as a router between physical network and my lab network. The server has two interfaces external and private (external being the WAN and internal being LAN)
I have modified my /etc/network/interfaces so that it looks like:
auto eth0
iface eth0 inet dhcp

auto eth1
iface eth1 inet static
        address 192.168.1.1
        network 192.168.1.0
        netmask 255.255.255.0
        broadcast 192.168.1.255

after that i edited the /etc/sysctl.conf and removed the comment in net.ipv4.ip_forward=1
All instructions I have found imply that after you done this and restart networking (I just reboot server) the second interface should have the ip that it was given, BUT in my case the interface does not come up after reboot and I need to manually raise it up with sudo ifconfig eth1 up. After that when I check my ifconfig the eth1 is shown but is does not have the address I set up but instead it has a ipv6 address
Seems to me that the OS is not reading the /etc/network/interfaces file.
Any help would be appreciated.

A: ifupdown which uses /etc/network/interfaces was deprecated in 17.10.
https://wiki.ubuntu.com/Netplan
Instead use /etc/netplan/*netcfg.yaml


text:
Q: CSS hover over on thumbnails in wordpress I am trying to create a grid of thumbnails in wordpress, which I've managed to do. Then when the user hovers over an image, I want it to go a semi transparent colour and show the post title underneath. I think I've begun to make some way with the code, but at present the hover over appears underneath the image instead of ontop of the thumbnail. I was wondering if somebody could help me with this? I think it is the CSS that is the problem. I tried position: absolute but that just sticks in one place to the top of the grid.

<?php
$c = 1; //init counter
$bpr = 3; //boxes per row
if(have_posts()) :
    while(have_posts()) :
        the_post();
?>

<div class="post" id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('grid-post-image'); ?>

<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?>

<?php
if($c == $bpr) :
?>

<?php
$c = 0;
endif;
?>
<?php
        $c++;
    endwhile;
endif;
?>

And here is the CSS, which is what I think needs altering.
.post {
    float: left;
    width: 275px;
}

.clr {
    clear:both;
}

.hover {
      width: 275px;
   height: 185px;
    top: 0;
    z-index: 1;
        background: #fff;
      opacity:0;
}

.hover:hover{
      opacity:0.9;
}

A:

Put both elements (image and h1) in the same div

    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail('grid-post-image'); ?>

<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?>


text:
Q: Pandas apply & map to every element of every column How to apply a custom function to every element of every column if its the value is not null?
Lets say I have a data frame of 10 columns, out of which I want to apply a lower() function to every element of just 4 columns if pd.notnull(x), else just keep none as value.
I tried to use like this,
s.apply(lambda x: change_to_lowercase(x), axis = 1)

def change_to_lowercase(s):

    s['A'] =  s['A'].map(lambda x: x.lower() if pd.notnull(x) else x)
    s['B'] = s['B'].map(lambda x: x.lower() if pd.notnull(x) else x)
    s['C'] = s['C'].map(lambda x: x.lower() if pd.notnull(x) else x)
    s['D'] = s['D'].map(lambda x: x.lower() if pd.notnull(x) else x)
    return s

But since my columns are mixed datatype(which is NaN as float, rest as unicode). This is throwing me an error -
float has no attribute map.

How to get rid of this error?

A: I think you need DataFrame.applymap because working elementwise:
L = [[1.5, 'Test', np.nan, 2], ['Test', np.nan, 2,'TEST'], ['Test', np.nan,1.5,  2]]
df = pd.DataFrame(L, columns=list('abcd'))
print (df)

      a     b    c     d
0   1.5  Test  NaN     2
1  Test   NaN  2.0  TEST
2  Test   NaN  1.5     2

cols = ['a','b']
#for python 2 change str to basestring
df[cols] = df[cols].applymap(lambda x: x.lower() if isinstance(x, str) else x)
print (df)
      a     b    c     d
0   1.5  test  NaN     2
1  test   NaN  2.0  TEST
2  test   NaN  1.5     2

A: You are trying to map a Series and then in lambda you take the entire row.
You should also check for integers, floats etc that don't have a method .lower(). So the best is to check if it is a string, not just if it is not a notnull, in my opinion.
This works:
s = pd.DataFrame([{'A': 1.5, 'B':"Test", 'C': np.nan, 'D':2}])
s

        A   B   C   D
0   1.5 Test    NaN 2

s1 = s.apply(lambda x: x[0].lower() if isinstance(x[0], basestring) else x[0]).copy()

s1
    A     1.5
    B    test
    C     NaN
    D       2
    dtype: object

For python 3 to check if string isinstance(x[0], str)
To be able to select columns:
s1 = pd.DataFrame()
columns = ["A", "B"]
for column in columns:
    s1[column] = s[column].apply(lambda x: x.lower() if isinstance(x, str) else x).copy()
s1

    A   B
0   1.5 test


text:
Q: TinyMCE strips inline style with valid-elements: *[*] with Codeigniter I have read Tinymce strips attributes on submit,  TinyMce Allow all Html tag, TinyMCE valid elements: only allow specific CSS rules, how to prevent tinymce from stripping the 'style' attribute from input element?, TinyMCE, allow data attribute and many others...
But none of them work.
This is my code:
valid_elements : '+*[*]',
cleanup: false,
inline_styles : true

I have also tried
valid_elements : '*[*]'

(without + before *[*])
and even
valid_children : '+body[style]'

But when I add the styles manually like style="color: #fff;" and submit the form, TinyMCE removes the returned output.
In other words: I want TinyMCE to stop 'removing' any code automatically.

A: No, it was not TinyMCE that was preventing inline styles.
CodeIgniter did that.
Even now that I had manually disabled XSS filtering using:
$body = $this->input('body', FALSE);

, that was still being removed because I had enabled XSS filtering in application/config/config.php:
$config['global_xss_filtering'] = TRUE;

But when I changed it to
$config['global_xss_filtering'] = FALSE;

the problem was resolved and I got rid of the Server Side filtering.

I post the answer here and I hope no one else be such crazy and mad that I became!


text:
Q: AttributeError: 'list' object has no attribute 'lower' I get above error for following 2 scripts, what could be reason.
*** Settings ***
Resource          resource.txt

*** Variables ***
@{ExpectedCookieValue}    selenium1234
@{ExtractedCookieValue}    ${Empty}

*** Test Cases ***
CookieTest
    Open Browser    http://www.google.com     ${Browser}
    Maximise Browser Window
    Add Cookie    SeleniumTest    selenium1234
    Get Cookie Value    SeleniumTest
    ${ExtractedCookieValue}    Get Cookie Value    SeleniumTest
    Log    "Extracted Cookie Value"
    Log    ${ExtractedCookieValue}
    Should Be Equal    ${ExtractedCookieValue}    ${ExpectedCookieValue}    'Cookie Should Be Equal'
    Close Browser

2nd Script
*** Settings ***
Resource          resource.txt

*** Test Cases ***
AlertTest
    Open Browser    http://www.seleniummaster.com/robotframeworktest/alerttest.html    ${Browser}
    Sleep    5s
    Click Button    name=alert_button
    Sleep    5s
    Alert Should Be Present    This is an alert box
    Close Browser

A: I had defined a List Variable instead of Scalar. Went to resource file and defined Scalar Variable ${Browser}        Firefox
and Removed  the following
 List Variable @{Browser}        Firefox

A: Context: Robot Framework 4.1 (Python 3.9.6 on win32)
Similar to what Maq Said noted re "list vs scalar" - I had same error while iterating in a FOR loop through a list which I had defined using ${listname}. When I changed notation to @{listname} ($ to @) I got no error, and contents were listed. Code below, super simple, I hope this note helps someone:
 FOR     ${each_item}    IN   @{element_attribute_list}  #list of href URLs
     log to console    "element ===>" ${each_item}
 END

OUTPUT:
"element ===>" https://www.example.org/terms-of-use
"element ===>" https://www.example.org/contact_us
"element ===>" https://www.example.org/group-sales
... etc ...

Also to help with clarity here is cross-reference post and excerpt from Stackoverflow, another instance: In Robot Framework, what is the difference between a List Variable and a Scalar Variable containing a list?
| @{list} =   | Create List | a | b | c |
| ${scalar} = | Create List | a | b | c |


text:
Q: Start Time in TestNG default Report I have used TestNG for my Project.
The default report generated after the execution shows: Start Time as 1486475432046.
How can I interpret this?

A: The start time in TestNG's default report is displayed in unixtimestamp. It is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds. Refer to this link to know more about unix time stamp.


text:
Q: How to weight other factors when using Dijkstra I'm solving this problem where we have a graph, and are trying to get from node 1 to node N. The edge weights are the "cost" and each edge also has a "flow" value. For any path from node 1 to node N, the total cost would be the sum of all the costs of the edges on the path, and the flow would be the minimum flow value among the edges. We want to maximize the ratio of flow/cost.
I had the idea to use Dijkstra to find the smallest cost path from 1 to N, and when I tried finding the path this way I realized I wasn't accounting for flow. I want to perform modified Dijkstra where I take into account the flow of each edge when calculating the best path, but I'm not sure how to do this.
Should I manipulate the edge costs by subtracting or adding extra flow, or would this not work because we are looking at the ratio?
I also tried finding every path through BFS, but there is a time constraint and I am unable to do that as well.
Could anyone give me some tips on how to solve this problem?
Edit:
An example is having 3 nodes, 1, 2, and 3. 1 and 2 have an edge cost of 2, and a flow of 4. 2 and 3 have an edge cost of 5, and a flow of 3. In this example, there is only one path from 1 to N. Its flow is min(3,4)=3 and its cost is 2+5=7. So the ratio would be 3/7. But in most cases we will have several possible paths.

A: Follow Dijkstra's algorithm and maintain for each node v a distance label D[v] (as usual), and additionally a flow label F[v]. The goal is to maximize the ratio F[v] / D[v]. The vertex u the algorithm should select next is the one which maximizes this ratio.
Then, during the relaxation of any incident edge e=(u,v), perform the following computation to see if the ratio of a new possible path from the starting vertex to v that uses u as an intermediate vertex is better than any previously found path.
// relaxing edge e = (u,v)
newDistance = min{ D[u], D[v] + cost(e) }
newFlow = min{ F[u], flow(e) }

if ( (newFlow / newDistance) > (F[v] / D[v]) )
    v.parent = u
    F[v] = newFlow
    D[v] = newDistance

A: I'm not completely sure, but you can just use your flow/cost ration as a node weight. It's ok for Dijkstra algorithm.
By the way, I've got a coursework on the same topic, I've got length and speed costs, and using length/speed ratio worked for me. You can see all the sources on GitHub.


text:
Q: Is there package for Sublime Text 2 that displays git branch in side bar after root folder's name? Googled this topic unsuccessfully. May be you guys can help me out.
Title is the question:
?? Is there package for Sublime Text 2 that displays git branch in side bar after root folder's name ??
Just as convenience rather then anything else.

A: I just discovered this myself. As noted in ST forum the SideBarGit plugin places current branch in the statusbar:


text:
Q: Обработка исключения на Селениум мне нужно в Селениуме прописать условие что если элемент не кликабельный, то прекращаем скрипт, как я мог бы это сделать? Я знаю про команду ElementToBeClicable, есть ли антоним  у это команды?
Вот код где я хочу это прописать:
 try:
                a_next_page = driver.find_element_by_class_name('back_pagin')
                a_next_page.click()

            except NoSuchElementException:
                break

Почему NoSuchElementException не работает, все потому что как оказалось элемент пагинации после того как код прошелся по всем страницам, никуда не девается, он просто становится некликабельным, но, если это будет полезно, когда все страницы прогружены, и элемент пагинации становится некликабельным, появляется новый css selector, а именно .pages .disabled-arrow, никак не получается обработать исключения, помогите пожалуйста)


text:
Q: Show miniframes with split outer themes I'd like to combine the split and miniframes themes of beamer. For example, I would have the miniframes appear in the right half of the title bar (where the subsections appear). If there are any subsections, I'd have the miniframes below or next to the subsection title. This is a sample document.
\documentclass[compress,aspectratio=43]{beamer}

\useoutertheme{miniframes}
\useoutertheme{split}
%\setbeamertemplate{headline}[miniframes theme]
\usecolortheme{whale}

\begin{document}

\section{First Section}
\frame{} \frame{} \frame{}

\section{Second Section}

\subsection{sub1}
\frame{} \frame{} \frame{}

\subsection{sub2}
\frame{} \frame{} \frame{}

\end{document}

I won't ask if it's possible, because everything is possible with TeX, but rather whether someone can help me :)
To show what I mean, these are the headlines with miniframes:

These are with split:

And I want something like this mockup:

A: This seems to be working as I indended. It's a bit hackish, and it only works with the compress option.

\documentclass[compress,aspectratio=43]{beamer}

\useoutertheme{miniframes}
\useoutertheme{split}
\usecolortheme{whale}

% For convenience, move this to a style or theme file
\makeatletter

\newcount\beamer@xoff
\newcount\beamer@prev@section
\newcount\beamer@prev@miniframes
\beamer@xoff=0
\beamer@prev@section=0
\beamer@prev@miniframes=0

\def\insertsubsectionnavigationhorizontalminiframes#1#2#3{%
  \hbox to #1{{%
    \usebeamerfont{subsection in head/foot}\usebeamercolor[fg]{subsection in head/foot}%
    \beamer@currentsubsection=0%
    \def\sectionentry##1##2##3##4##5{}%
    \def\slideentry##1##2##3##4##5##6{%
      \ifnum##1>\beamer@prev@section%
        \beamer@xoff=##3\relax%
        \beamer@prev@miniframes=0\relax%
      \fi
      \ifnum##6=\c@part\ifnum##1=\c@section%
      \ifnum##2>\beamer@currentsubsection%
      \beamer@xoff=0\relax%
      \beamer@currentsubsection=##2%
      \box\beamer@sectionbox\hskip1.875ex plus1fill%
      \ifnum\beamer@prev@miniframes>0\relax%
        \beamer@tempdim=\beamer@boxsize%
        \multiply\beamer@tempdim by \beamer@prev@miniframes%
        \advance\beamer@tempdim by -\beamer@boxsize%
        \advance\beamer@tempdim by 2pt%
        \ifnum##2>1%
          \advance\beamer@tempdim by 1.875ex%
        \else
          \advance\beamer@tempdim by -\beamer@boxsize%
        \fi
      \else
        \beamer@tempdim=0pt%
      \fi
      \setbox\beamer@sectionbox=
      \hbox{\def\insertsubsectionhead{\kern\beamer@tempdim##5}%
         \def\insertsectionheadnumber{##1}%
         \def\insertsubsectionheadnumber{##2}%
         \def\insertpartheadnumber{##6}%
         \ifnum\c@subsection=##2%
        \beamer@link(##4){{\usebeamertemplate{subsection in head/foot}}}\else%
        \beamer@link(##4){{\usebeamertemplate{subsection in head/foot shaded}}}\fi}%
      \ht\beamer@sectionbox=1.875ex%
      \dp\beamer@sectionbox=0.75ex%
      \else%
      \beamer@prev@miniframes=##3%
      \fi%
      \setbox0=\hbox{\insertsectionhead\unskip}\ifdim\wd0>0pt\ifnum##3>0%
      \beamer@xpos=##3\relax%
      \advance\beamer@xpos by -\beamer@xoff%
      \hbox to 0pt{%
        \beamer@tempdim=0.5pt%
        \raise\beamer@tempdim\hbox{%
          \ifnum##2>0%
            \beamer@tempdim=\beamer@boxsize%
            \multiply\beamer@tempdim by\beamer@xpos%
            \advance\beamer@tempdim by -\beamer@boxsize%
            \advance\beamer@tempdim by 2pt%
            \advance\beamer@tempdim by \wd\beamer@sectionbox%
          \else%
            \beamer@tempdim=\beamer@boxsize%
            \multiply\beamer@tempdim by\beamer@xpos%
            \advance\beamer@tempdim by 1.875ex%
          \fi%
          \kern\beamer@tempdim\hbox{\beamer@link(##4){%
              \usebeamerfont{mini frame}%
              \ifnum\c@section=##1%
                \ifnum\c@subsection=##2%
                  \usebeamercolor[fg]{mini frame}%
                  \ifnum\c@subsectionslide=##3%
                    \usebeamertemplate{mini frame}%
                  \else%
                    \usebeamertemplate{mini frame in current subsection}%
                  \fi%
                \else%
                  \usebeamercolor{mini frame}%
                  \usebeamertemplate{mini frame in other subsection}%
                \fi%
              \else%
                \usebeamercolor{mini frame}%
                \usebeamertemplate{mini frame in other subsection}%
              \fi%
            }}}\hskip-10cm plus 1fil%
          }\fi\fi%
      \else%
      \fakeslideentry{##1}{##2}{##3}{##4}{##5}{##6}%
      \fi\fi%
      \beamer@prev@section=##1%
      \ignorespaces}%
    #2\hskip.3cm\setbox\beamer@sectionbox=\hbox{}%
    \hskip-1.875ex plus-1fill\dohead%
    \box\beamer@sectionbox\hfil\hskip.3cm%
    #3}}}

\setbeamercolor{mini frame}{parent=subsection in head/foot}

\ifbeamer@compress

\defbeamertemplate*{headline}{split theme miniframes}
{%
  \leavevmode%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex]{section in head/foot}%
    \insertsectionnavigationhorizontal{.5\paperwidth}{\hskip0pt plus1filll}{}%
  \end{beamercolorbox}%
  \begin{beamercolorbox}[wd=.5\paperwidth,ht=2.5ex,dp=1.125ex]{subsection in head/foot}%
    \insertsubsectionnavigationhorizontalminiframes{.5\paperwidth}{}{\hskip0pt plus1filll}%
  \end{beamercolorbox}%
}

\else

\defbeamertemplatealias{headline}{split theme miniframes}{split theme}
\setbeamertemplate{headline}[split theme miniframes]

\fi

\makeatother

% This is to enable the feature
\setbeamertemplate{headline}[split theme miniframes]

\begin{document}
\frame{\titlepage}
\frame{\tableofcontents} % no miniframes in the front matter (good)
\section{First Section}
\frame{} \frame{} \frame{} % miniframes without subsections (good)
\section{Second Section}
\subsection{Subsection 1}
\frame{} \frame{}
\subsection{Subsection 2}
\frame{} \frame{} \frame{}
\section{Third Section} % correct miniframes with mixed sections/subsections
\frame{} \frame{} \frame{}
\subsection{Subsection 3}
\frame{} \frame{} \frame{}
\section*{} % no miniframes in back matter (good)
\frame{End}
\end{document}

A: There is a special theme available to combine the split and miniframes outer themes, called splitwithminiframes. It is available from http://mirrors.ctan.org/macros/latex/contrib/beamer-contrib/themes/beamerauxtheme/themes/beamerouterthemesplitwithminiframes.sty
Caveat: it won't recognise the compress option
\documentclass[aspectratio=43]{beamer}

\useoutertheme{splitwithminiframes}
\usecolortheme{whale}

\begin{document}

\section{First Section}
\frame{} \frame{} \frame{}

\section{Second Section}

\subsection{sub1}
\frame{} \frame{} \frame{}

\subsection{sub2}
\frame{} \frame{} \frame{}

\end{document}


text:
Q: Safeguarding against multiple manual executions of an external PHP script My application calls external PHP files to retrieve and submit information to an SQL database.  Each request made is visible in the developer panel of what I assume to be any browser, and can easily be re-executed manually.  It is my understanding that trying to detect the "source" of the request is not the right way to go about restricting manual invocation of scripts.
My main reason for wanting to prevent re-execution of these scripts is that they could either lead to the user giving themselves more than they've earned (UPDATE user_scores SET score = score + x) or returning themselves to a previous state as many times as they want (UPDATE user_scores SET score = x).
What is a tried and true method of ensuring that a query within a script that is only intended to execute once is executed the first time and never again?

A: You should never rely on client-side controls like this. Your PHP script should be checking who the user is, and validating that they should 'get' whatever it is they are getting, before doing it.
What ever code you are running that is calculating that score in the first place should be where your UPDATE code is... it should never leave the server.


text:
Q: React, focus() triggers submit I have Routes:
export const Routes = (props) => {
  return(
//----------
<Switch>
        <Route exact path='/:id' render={props => <AdvFormEditContainer/>}/>
        <Route path='/' render={props => <Main/>}/>
</Switch>
//----------
    )
}

And there is <AdvFormContainer/> inside of <Main/>:
export class AdvFormContainer extends React.Component {
  constructor(props) {
    super(props);
    this.submitForm = this.submitForm.bind(this);
    this.onChange = this.onChange.bind(this);
    this.state = {
      titleError: '',
      textError: ''
    }
  }

  componentDidMount() {     // Comment it out and no titleError message
    this.focusForm.focus();
  }

  onChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    })
  }

  submitForm(e) {
    e.preventDefault();
    const {title, text} = this.state;
    const {logged, addAdv} = this.props;
    const author = logged[0].name;
    if (title && text) {
      addAdv(author, title, text);
      setTimeout(() => {
        this.setState({
          title: '',
          text: ''
        })
      }, 2000);
      this.resetForm.reset();
    } else if (!title) {  // Get fired because there is no title yet!
      this.setState({
        titleError: 'Please, enter title!'
      });
      setTimeout(() => {
        this.setState({
          titleError: ''
        })
      }, 2000);
    } else if (!text) {
      this.setState({
        textError: 'Please, enter the text!'
      });
      setTimeout(() => {
        this.setState({
          textError: ''
        })
      }, 2000);
    }

  }

  render() {
      return (
  <div>
    <AdvForm
  {...this.props}
  onChange={this.onChange}
  submitForm={this.submitForm}
  resetRef={el => this.resetForm = el}
  focusRef={el => this.focusForm = el}
  titleError={titleError}
  textError={textError}
  />
  </div>
)
  }
}

And <AdvForm> component:
export const AdvForm = (props) => {
  const {......., resetRef, focusRef} = props;
  return (<form action="post"
    ref={resetRef}
    >
                            <MuiThemeProvider>
                              <TextField
    ref={focusRef}
    //---------------------
    />

                     </MuiThemeProvider>
//----------------------
                    </form>)}

Everything works fine if <Main/> and <AdvFormContainer/> mounted the first time.
But if there is a Route change from path="/:id"  to path="/", <AdvForm/> inside of
<AdvFormContainer/> get submitted with empty inputs, which triggers Error message.
Such behavior occurs because of
componentDidMount() {     // Comment it out and no titleError message
    this.focusForm.focus();
  }

If there is no focus(), there is no empty submitting.
<Button/> has nothing to do with it. I tried to get out onSubmit from <Button/> and attach it to <form>. The same behavior.
Please, out of curiosity, what's going on?


text:
Q: When exactly does the velocity of a cart change? I have done many problems where where a small body is thrown from a moving cart and we have to use conservation of momentum to find the final velocities of the cart and the thrown object. To find the velocity of the thrown body with respect to the ground frame, we have to add the velocity with which it is thrown and velocity of the cart with respect to the ground. But in this scenario we always add the final velocity of the cart, not the initial velocity. Why is it so?

A: The cart does not accelerate further after the men jump. The same goes for the men. So just as the men leave the cart, it's velocity is $v_f$. That's why you add the final velocity and not the initial one.


text:
Q: How do I see what [object Object] refers to in Chrome Tools? In chrome tools, how can i view what [OBJECT object] represents?  Testing out function context of keyword 'this'
 var Calculator = function (eq) {

            // private members...
            var eqCtl = document.getElementById(eq),
                foo = function () { };

            return {
                add: function (x, y) {
                    var val = x + y;
                    eqCtl.innerHTML = val;

                },

                print: function () {
                    console.log("print:  this" + this);
                    this.test(this);
                },

                test: function (obj) {
                    console.log("test: this " + this);
                    console.log("this: obj" + obj);
                }

            }

        };

A: Don't convert it to a string. console.log() it separately:
console.log("test: this ", this);
console.log("test: obj ", obj);

A: Pass multiple parameters to console.log method
console.log("this: obj", obj);

A: Try console.dir instead. It should be more informative than console.log under certain situations.


text:
Q: How do I serve a .ttf file in node.js using the http and fs libraries? I have a simple node server and I have a CSS file that requests a font from my server:
@font-face{
     font-family: 'NiagaraSolid-Reg';
     src: url('http://localhost:1111/NIAGSOL.TTF');
}

This is what I attempted to do. It normally works with .html, .css, and .js files:
http.createServer(function(request,response){
    var arguments=request.url.slice(1).split("/");
    switch(arguments[0]){
        case "NIAGSOL.TTF":
            response.end(fs.readFileSync("website/NIAGSOL.TTF").toString());
            break;
        //etc
})

But when I do this, in Chrome I get the error message: Failed to decode downloaded font:  http://localhost:1111/NIAGSOL.TTF
In searching for an answer, everything I came across was too complicated for me to understand becuase it required prerequisite knowledge of a lot of things. I'm completely illiterate when it comes to buffers and streams and binaries and encodings etc. I need a simple "explain-like-I'm-five" answer for how to serve a .tff file.
Thanks!

A: How to serve an image using nodejs
This link helped me figure out what to do. On a whim I decided to try response.end(fs.readFileSync("website/NIAGSOL.TTF"),"binary"); and it worked. Not sure why exactly but hey!

A: If you're coding a raw http server in node, you must set the "Content-Type" header in the response.  So if you're serving an html file you set the header content type to "text/html".  Likewise you must tell node to serve .ttf files as such, by setting the header on the response thats serving the ttf file.   You can do so by setting the content type to "application/x-font-ttf".
http.createServer(function (req, res) {
    res.writeHead(400, { "Content-Type": "application/x-font-ttf" });
});

You'll need to write you're own code for handling the different file types you're server may be serving.  Just remember that if its a .ttf, set the header as above.


text:
Q: Group strings together and calculate total Have a group of email address and numbers together that are taken out of database in sql using join.
SELECT ost_ticket.email, ost_ticket_response.time_taken
FROM ost_ticket
INNER JOIN ost_ticket_response
ON ost_ticket_response.ticket_id=ost_ticket.ticket_id
WHERE time_taken > 0

Output
('log@tome.ie', 100)
('log@tome.ie', 100)
('log@tome.ie', 10)
('log@tome.ie', 2)
('temp@eircom.net', 30L)
('john@tome-ireland.com', 20L)
('1234567@tome.ie', 1234567L)
('log@tome.ie', 2L)
('log@tome.ie', 2L)
('valerie@tome.ie', 30L)
('john@cmi-tome.com', 10L)
('john@cmi-tome.com', 40L)

Want to be able to take all the email address and have total so
log@tome.ie = 216
temp@eircom.net = 30
john@tome-ireland.com = 70
1234567@tome.ie = 1234567
john@cmi-tome.com = 50

Is it possible to do through sql or after output to do it in python?

A: When you pull the data from the database, use a query like this:
select emailaddress, sum(number) as total
from t
group by emailaddress


text:
Q: Import error: No module named "utils" when using pickle.load I firstly dump some stuff into a pickle file using pickle.dump. in utils.load_data, my project hierarchy looks like this
project1
  -utils
     -__init__.py
     -load_data.py
  -data
  (other folder...)

Then it outputs a pickle file into a data folder. Then I move the .pickle file to another project, the project hierarchy is
project2
   -data
   -main.py

When I run a pickle.load() operation in this main.py, it prompts the error as the title. However, if I move main.py back to project1 folder, then the error disappears. So the issue must be from the file.
My question is, why does pickle try to import the package from where it was born? Could anyone share a good explanation for this? I got quite confused.

A: By default, unpickling will import any class that it finds in the pickle data. This means if you have pickled a custom class and you are unpickling it somewhere, pickle will try import the module (utils in this case). So you need to have the utils module inside project2 folder
Follow this for more information


text:
Q: Join a particular column in @JoinColumns @ManyToOne
@JoinColumns
({
    @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
    @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
public Address getAddress() { return address; }

How to join a particular column in @JoinColumns? For instance, if there is a composite PK in Address class containing ID and ZIP, how can I join only the "ID" column so that only a ADDR_ID column is created and not ADDR_ZIP?
@MapsId("ID") is not working to refer to only ID and exclude ZIP.
Is it possible in hibernate?

A: If you only want to join one column, you should try:
@ManyToOne
@JoinColumns
({
    @JoinColumn(name="ADDR_ID", referencedColumnName="ID")
})
public Address getAnotherAddress() { return address; }

A: JPQL is where you define join criteria and get desired results back
entity definition maps java to your db world
if ID matches multiple Address, you get a List<> back


text:
Q: How should I structure the data layer of a node.js server using node-postgres client? I am working on a server in Node.js that uses node-postgres database client. I am trying to follow the 3 layer architecture (controllers, services, models). So far I have been using a Pool for all queries. However, now I need to perform transactions and that requires a single client throughout the whole transaction. I came up with a solution to pass an optional client parameter into the query function (without supplying the client, the query will be performed on the default pool). This way, the service layer can create a client and call other services that perform database operations with the created client in order to perform a transaction. However this means I will also have to add the optional client parameter into every service that is responsible for retrieving the data. Is the solution I came up with a good approach or are there any better solutions? Iam also unsure how should the model layer look like without using an ORM and wasn't able to find any examples. Would you say I should use an ORM like sequalize? I will appreciate any advice, so feel free to point out anything.
Code example:
./db/index.js
const { Pool, Client } = require("pg");
const config = require("../config");

const pool = new Pool({
  connectionString: config.databaseURL,
  max: 20,
  ssl: {
    rejectUnauthorized: false,
  },
});

/**
 * @param {object} obj
 * @param {string} obj.query
 * @param {any[]} [obj.values]
 * @param {Client} [obj.client]
 */
exports.query = ({ query, values, client }) => {
  return client === undefined
    ? pool.query(query, values)
    : client.query(query, values);
};

// returns the client
exports.connect = () => {
  return pool.connect();
};

./models/pipe.model.js
const db = require("../db");

/**
 * @param {number | string} id ID of the pipe
 * @param {import("pg").Client} [client]
 */
exports.getById = (id, client) => {
  const query = `SELECT id, price, state, tone_id, rank_id FROM pipe
    WHERE id = $1`;
  return db.query({ query, values: [id], client });
};

./services/pipe.service.js
const pipeModel = require("../models/pipe.model");
const StatusError = require("../helpers/error");

/**
 * @param {number | string} id
 * @param {import("pg").Client} [client]
 */
exports.getById = async (id, client) => {
  let rows, rowCount;
  try {
    ({ rows, rowCount } = await pipeModel.getById(id, client));
  } catch (err) {
    throw new StatusError(500, "Error retrieving data");
  }
  if (rowCount !== 1) {
    throw new StatusError(404, "Pipe with gived ID not found");
  }
  return rows[0];
};


text:
Q: Simple separation steering I' ve a java application that creates 150 random rectangles with random width, height, X- and Y- coordinate.
Most of them are overlapping and this is my problem. I want to seperate all the rectangles, but I don' t know what I have to do.
Here you see a screenshot of the rects:

All rects are stored in an ArrayList (private ArrayList<DungeonCell> dungeonCells;)
The DungeonCell-Class is something like a vector with the following fields:
public int positionX;
public int positionY;

public int width;
public int height;

I hope that you understand my problem.

A: Instead of adding the triangles without any concern, first check if it fits. If not, skip it and create another one. This would be possible with a do-while.
Rectangle r;
do
{
   r = createRandomRect();
} while (overlaps(r))
add(r);

Note: This is going to be very slow if the amount of rectangles keeps increasing and the available space gets smaller and smaller. Also make sure that rectangles are not occupying the whole area. This algorithm may fail if there literally all space is used, but this is unlikely, since you work with floats, I think.

A: If you want to avoid generating overlapping random rectangles you can do this:

*

*Generate the values for your next rectangle

*Check if any of the corners of the new rectangle lies within any of the existing rectangles

*Then either add the rectangle or generate new random values

*Don't forget to avoid infinite loops by setting a maximum number of tries!

A: If you need to check whether two rectangles intersect each other you need to write something like the following:
public static boolean Intersects(Rectangle rect1, Rectangle rect2)
{
    if (rect1.positionX >= rect2.positionX &&
rect1.positionY>=rect2.positionY &&
rect1.positionX <= rect2.positionX+rect2.height &&
rect1.positionY <= rect2.positionY + rect2.width
  || rect1.positionX+rect1.height >= rect2.positionX
&& rect1.positionY+rect1.width>=rect2.positionY
&& rect1.positionX+rect1.height <= rect2.positionX+rect2.height
&& rect1.positionY+rect1.width <= rect2.positionY + rect2.width)
        return true;
    else return false;
}


text:
Q: How to avoid displaying the results of an API query when assigning a variable I am using the google-api-client gem to interact with Google Calendar.
When saving a list of events like this:
@events = calendar.list_events(@tmpcalendar)

The output of calendar.list_events(@tmpcalendar) is huge. I just want to save the result to @events (don't need the huge content displayed).
I have tried: $output.close, redirecting to /dev/null, appending ;nil; but the huge result is displayed anyway.
To replicate this (with a solution that works) you can
large_text = <<~EOS
  ...huge text here
  ...huge text here
  ...huge text here
  ...
  ...huge text here
EOS

eventos_good = large_text ; nil  # Assigns the content, does not display it
eventos_annoying = large_text    # Assigns the content, but displays the huge text

This works for that case, but does not work with the above scenario (API call).
Is it possible to avoid that huge output just for that variable assignment above?
Thanks.

A: According to the docs, the Google API gem has debug logging enabled by default. To decrease the output, set the logging lever to something higher:
Google::Apis.logger.level = Logger::FATAL
# INFO, WARN, ERROR, FATAL each decrease the output.
# FATAL is the most restrictive.

A: From your code, it looks like you're using the Google API Client gem? Which version?
If you're not using this gem in a Rails application, then it will default all logging to $stdout: https://github.com/googleapis/google-api-ruby-client/blob/1135e74c4896d4ec8aa02c14e3532d9a14514815/lib/google/apis.rb#L34-L40
If you want to completely silence the logging, then override the logger:
require 'logger'

Google::Apis.logger = Logger.new(nil)


text:
Q: In Devil May Cry 3, what's the point of fighting the optional midboss Jester? I've had the option to fight him twice now before the second encounter with Vergil. The battles feel so out of context with what's happening storywise. There is no apparent reward either when you win?
I'm playing the recently released HD-version.

A: Orbs, Style Points and Experience. There isn't a really good reason to bother with the optional fights even though the first of the 3 is mandatory.
The Jester fights were additions to the Special Edition which have apparently also been migrated to the HD release. As they were apparently not part of the original game, that may be why they feel out of place.

A: The reason for fighting Jester in the HD version is for an achievement


text:
Q: setwd() works weird inside a function? I have a function for choosing files using file.choose(). When I call it inside a script I want it open certain directory where I wish to choose files. There is a cycle inside the function as I need to choose a bunch of files. First time it opens in the working directory, which is predictable. I put setwd() inside to make the needed directory as working directory so I can choose files there. But when dialog box opens next time it is again the old working directory. But next time it is the directory I need. If I choose different folders it works the same - next time the old directory but after that the new one. I wrote a short function that reproduces behavior:
foo <- function() {
  files <- NULL
  for (i in c(1,2,3,4,5)) {
    x <- file.choose()
    y <- dirname(x)
    setwd(y)
    print(y)
    print(getwd())
  }

}

Just call this function and try to choose files in different or same directories. You can see that directory name is new and getwd() says that new working directory is set but next file choice dialog opens in previous directory.
Please keep in mind that I need to use file.choose() function as it works on a headless OS, both Windows and Unix-like.
When I don't use setwd() it is always the old working directory.


text:
Q: git submodule for zxing (iPhone version)? I need a qrcode library for an iphone project. Zxing seems the obvious choice and I've used it previously. However, this will be a project that I will have to support for quite a while and  I'm very deep in git.
Zxing officially only provides an svn repo, and gitorious has a few old zxing submodules but those that I've found are for android and even they don't get touched anymore.
I did some looking and there doesn't seem to be a git submodule for iphone. Does anyone know of a good one?

A: https://github.com/joelind/zxing-iphone - seems to be the latest one on the github.
However, you can make the git repo on your own - just by mirroring google svn.

A: I maintain
https://github.com/zxing/zxing
It's a git-svn clone and is updated automatically within a few minutes of any svn commit. It's not officially official but I am a zxing committer.
It's not just the iphone directory, though. That's too complicated to maintain separately. The iphone directory requires the cpp (C++) directory and the C++ code is tested against the java tests in the core directory. There's also a generic objc directory for lower level code that works on both OS X and iOS.


text:
Q: BigNumber math in Postgres to compute Ethereum transactions Is there any way to handle math over BigNumber in Postgres? I'm especially interested in uint256 (32 bytes) and having SUM over rows.
Right now I'm just storing such numbers as strings then load all rows and manually do reduce over them. But I pretty always need to do SUM over such data. It might be some extension that can introduce unsigned integer math over bytea for example?

A: Thanks to @a_horse_with_no_name
numeric type can be used to store pretty big numbers. To know what precision should be used this formula can be used:
# Example for uint256 in julia lang
max_value = BigInt(1) << (256 + 1) - 1
print( ceil( log10(max_value) ) )
# 78.0

So formula says we should use numeric(78).


text:
Q: Don't understand my mounted partitions
I plugged a samsung phone in my ubuntu pc, and it didn't want to mount automatically.
So, i had a look in fdisk, i found it, but by typing df -h, i found all those lines...
I have removed anbox, but can you explin me please those lines and if i can remove them (i thonk from /etc/fstab).
Thank you in advance.

A: udisks2 is likely the utility which is auto-mounting your removable storage devices. There's Ubuntu documentation about how it works, and how to disable it if you'd like.
As for the mounted filesystems, in short, that's how linux works. Here's an overview of the filesystems you have mounted:

*

*/dev - This is a pseudo-filesystem which presents device files.

*/run - This is an in-memory (RAM) filesystem used for temporary files used during runtime.

*/ - This is your root filesystem.

*/snap/* - These are filesystem image files being mounted via loop devices, which in your case are being used to mount filesystems containing various Snap programs.

*/run/cgmanager - cgmanager is used to manage Linux cgroups (control groups), typically for containers.

While it may be possible to remove some of those filesystems, unless you know precisely what you are doing, I recommend leaving them as-is. Otherwise you may accidently cause some of your programs to stop working.


text:
Q: Evaluate EL expression from string as bean in JSF page I am fairly new to JSF and am currently a frontend developer for a new project. I do not have access to the backend code and need to create a solution with the data I have access to on the page.
Currently I have a menu and there are security controllers on HTML elements to control visibility.
Example:
style="#{security.ConfigMenu?'visibility:visible':'visibility:hidden;width:0px;height:0px;padding-bottom: 0px;'}"
This page is hardcoded and need to make it more dynamic.
I need to evaluate this expression but use an array of beans stored as strings
var security = ["security.ConfigMenu", "security.AdminMenu", "security.Dashboardmenu"];
Need to handle #{mappSec.insightsConfigMenu'} with #{security[0]}
Is this possible?
I tried to replace the bean call with a string using the bean name
#{bean.method}
with
var bean = "bean.method";
#{bean}


text:
Q: K8s cannot schedule new pods to worker nodes even though there are enough resources Currently, I am facing an issue when K8s scale up new pods on old deployment and Rancher shows stuck on scheduling pods into K8s worker nodes. It eventually will be scheduled but will take some time, as I understand is to wait for the scheduler to find the node which fits the resource request.
In the Event section of that deployment, it shows:
Warning  FailedScheduling    0/8 nodes are available: 5 Insufficient memory, 3 node(s) didn't match node selector.
Then I go to the Nodes tab to check if there is any lack of memory on the worker nodes, and it shows my worker nodes like this:
STATE   NAME        ROLES   VERSION     CPU             RAM             POD
Active  worker-01   Worker  v1.19.5     14/19 Cores     84.8/86.2 GiB   76/110
Active  worker-02   Worker  v1.19.5     10.3/19 Cores   83.2/86.2 GiB   51/110
Active  worker-03   Worker  v1.19.5     14/19 Cores     85.8/86.2 GiB   63/110
Active  worker-04   Worker  v1.19.5     13/19 Cores     84.4/86.2 GiB   53/110
Active  worker-05   Worker  v1.19.5     12/19 Cores     85.2/86.2 GiB   68/110

But when I go into each server and check memory with top and free command, they output smimilar result like this one on worker-1 node:
top:
Tasks: 827 total,   2 running, 825 sleeping,   0 stopped,   0 zombie
%Cpu(s): 34.9 us, 11.9 sy,  0.0 ni, 51.5 id,  0.0 wa,  0.0 hi,  1.7 si,  0.0 st
KiB Mem : 98833488 total,  2198412 free, 81151568 used, 15483504 buff/cache
KiB Swap:        0 total,        0 free,        0 used. 17101808 avail Mem

free -g:
              total        used        free      shared  buff/cache   available
Mem:             94          77           1           0          14          16
Swap:             0           0           0

So the memory available in the nodes are about 16-17 GB but still cannot schedule new pod into them. So my wonder is what causes this conflict of memory number, is it the amount between 86.2 (on Rancher GUI) and 94 (on server) is for the OS and other processes? And why Rancher shows K8s workload currently takes about 83-85 GB but in server the memory available is about 16-17GB. Is there any way to check deeper into this?
I'm still learning K8s so please explain in detail if you can or topics that talk about this.
Thanks in advance!

A: It doesn't matter what's actual resource consumption on worker nodes.
What's really important is resource requests.
Requests are what the container is guaranteed to get. If a container requests a resource, Kubernetes will only schedule it on a node that can give it that resource.
Read more about Resource Management for Pods and Containers

but my wonder is why it shows almost full of 86.2 GB when the actual
memory is 94GB

use kubectl describe node <node name> to see how much memory has been given available to kubelet on particular node
You will see something like
Capacity:
  cpu:                8
  ephemeral-storage:  457871560Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             32626320Ki
  pods:               110
Allocatable:
  cpu:                8
  ephemeral-storage:  457871560Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             32626320Ki
  pods:               110
......
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests   Limits
  --------           --------   ------
  cpu                100m (1%)  100m (1%)
  memory             50Mi (0%)  50Mi (0%)
  ephemeral-storage  0 (0%)     0 (0%)
  hugepages-1Gi      0 (0%)     0 (0%)
  hugepages-2Mi      0 (0%)     0 (0%)

K8s workload currently takes about 83-85 GB but in server the memory
available is about 16-17GB.

From output of free in question, this is not really true
KiB Mem : 98833488 total,  2198412 free, 81151568 used, 15483504 buff/cache
2198412 free which is ~2GB and you have ~1.5GB in buff/cache.
You can use cat /proc/meminfo to get more details about OS-level memory info.


text:
Q: Choosing Hadoop solution for Big Data project - Pricing Options I have to use Hadoop for my research work and I am deciding for the best option to start with. So far I have end up to go with Cloudera. I've downloaded the quick start VM
and started learning different turorials.
The issue is that my system can't afford to run it and perform very slow and I think it might just stop working after I feed it with all the data and run other services.
I was advised to go for a cloud service with 4 cluster node. Can someone please help me by providing the best option and estimated pricing to consider? 1 year plan might be enough to complete my research.
Thanks.

A: If you are a linux user, Just download the individual components(like hdfs, MR1, YARN, Hbase, Hive etc...) from this  Cloudera Archives instead of loading Cloudera Quickstart VM.
If you want to try the 4 node cluster, easiest option is to use cloud.
There are plenty of cloud providers. I have personally used AWS, Google Cloud, Microsoft Azure, IBM SmartCloud. Out of which, AWS is the best to start with.
It is like pay as you go(use).I can recommend you to use a decent EC2 Machine(4 X m3.large Machines)
Type: m3.large  CPU:2   RAM:7.5G    Storage: 1 x 32 SSD Price: $0.133 per Hour AWS Pricing
If you plan to do the research for one year, I recommend you to go for VPC.
Cons of AWS EC2:
If you launch a machine in EC2, the moment you restart your machine, Your IP and the hostname will get changed.
In AWS VPC, your IP and hostname will remain the same.
If you use 4 Machinesx24x7xone month,it costs you $389.44.
You can calculate the AWS cost by yourself

A: As best as I can see you have two paths:

*

*Setup Hadoop in a cloud service provider (i.e. Amazon's EC2 or
Redhat's Openshift.

*Use Hadoop-as-a-service (i.e. Amazon's EMR or Microsoft's HDInsight).

The first path, setting up Hadoop in a cloud service provider will require you to become a semi-competent Hadoop administrator. If that's your goal, great! However you'll spend a great deal of time learning the necessary skills and mindset to become that. I don't suspect that that is your goal.
The second path is the one I'd recommend out of these two. Using Hadoop-as-a-service you will get up and running faster, but will cost more up front and on an ongoing (per hour basis). You'll still probably save money because you'll be spending less time troubleshooting your Hadoop cluster and more time doing the work you wanted to do in the first place.
I have to wonder, if you can even fit your dataset on your laptop, why are you using big data tools in the first place? True, they'll work. However Big Data is at least partially defined as data sets and computational problems that just don't fit on a single machine.


text:
Q: Output GNU Octave (or Matlab) matrix into a file with C array syntax I have a big matrix in octave which I need it's data to be imported into my C++ code. The matrix is all numbers and I would like to save it as a C array in a header file.
example :
> # octave:
results =

  -3.3408e+01  -5.0227e+00   4.3760e+01   3.2487e+01   1.0167e+01   4.1076e+01   6.3226e+00  -3.7095e+01   1.3318e+01   3.8582e+01
  -2.1087e+01  -6.1606e+00   4.8704e+01   3.1324e+01   3.0287e+01   4.0114e+01   1.5457e+01  -3.6283e+01   2.6035e+01   4.0112e+01

Needed output:
/* In some foo.h */

static const float results = {
    3.3408e+01,-5.0227e+00,4.3760e+01,3.2487e+01,1.0167e+01,4.1076e+01,6.3226e+00,-3.7095e+01,1.3318e+01,3.8582e+01,
    2.1087e+01,-6.1606e+00,4.8704e+01,3.1324e+01,3.0287e+01,4.0114e+01,1.5457e+01,-3.6283e+01,2.6035e+01,4.0112e+01,
};

A: For vectors, try this function
function str = convertarraytoc(B, type, precision, varName)

if nargin < 2
    type = 'float';
end
if nargin < 3
    precision = 35;
end
if nargin < 4
    varName = 'B';
end

str = sprintf('%s %s[%d] = {', type, varName, length(B));
for iB=1:length(B)
    if strcmpi(type, 'float')
        str = [ str sprintf( ['%1.' int2str(precision) 'ff'], B(iB)) ];
    else
        str = [ str sprintf('%d', B(iB)) ];
    end
    if iB ~= length(B)
        str = [ str sprintf(',') ];
    end
    if mod(iB, 501) == 0, str = [ str sprintf('\n') ]; end
end
str = [ str sprintf('};\n') ];
fprintf('%s', str);

For example
convertarraytoc(rand(1,5), 'float', 8, 'test')

ans =

    'float test[5] ={0.84627244f,0.63743734f,0.19773495f,0.85582346f,0.24452902f};'

The function would need to be adapted to process Matlab arrays.


text:
Q: Returning Local Variable Pointers - C I'm trying to write a function in C to return the reverse of the a string that is passed into to the function.
Once the string is passed in I declare a local char [] to fill with the reverse of the string.
However, when I compile the program I receive a warning stating warning: function returns address of local variable      return test;
Am I allowed to return local variable pointers from functions in C?
char *reverseString(char *str)
{
    int i, j;
    char test[strlen(str)];

    if(str == 0)
        return;

    for(i = 0, j = strlen(str); i < strlen(str), j >= 0; i++, j--)
        str[j] = test[i];

    return test;
}

A: *

*You need more space for a string, strlen() gives you the number of characters, but c strings use an extra character to mark the end of the string, the '\0' ascii nul character, so 1 + strlen(otherString) is always required to copy a string.

*You check str for NULL after dereferencing it. That doesn't make sense, fist check for NULL and then call strlen().

*Using strlen() that way is not a good idea, because in c the string length is not stored anywhere, calling strlen() computes the string basically this way
size_t strlen(const char *string)
{
    size_t count = 0;
    while (*string++ != '\0')
        count++;
    return count;
}

there you can see how important the terminating '\0' is, and why you should not call strlen() in a loop for a string whose length doesn't change.

*If you return the address of a local variable, it will not work as you expect, because it wil be deallocated when the function returns, so you need to use dynamic allocation, for that there exists malloc() which makes it easy to do, so in your case it would be something like this
char *reverseString(char *str)
{
    size_t index;
    char  *test;
    size_t length;

    if (str == NULL)
        return NULL;

    length = strlen(str);
    test   = malloc(1 + length);
    if (test == NULL)
        return NULL;
    /* perform string reversal */
    for (index = 0 ; index < length ; index++)
        test[index] = str[length - index - 1];
    /* add the `nul` terminator */
    test[length] = '\0';
    /* return the newly allocated and initialized data */
    return test;
}


text:
Q: I want to change the Data source for the Elements in Information designer in Spotfire I have already created elements on a data source. But now the data source path is changed. I want to map the elements to a new data source path

A: Just edit the data source connection string to the new server.


text:
Q: How to view an openGL renders generated from PC's c++ code on an Android Device connected via WiFi? I'm working on an Augmented Reality (AR) demo in which high quality openGL renders (in C++) will be generated from a PC and then streamed to an Android display device (running minimum Android 2.2).  What is the easiest way to achieve this in real-time (30 FPS on Android Device) ?
I've looked into existing Anrdroid applications, and have not found anything to be suitable so far.  The best available were remote desktop applications (such as TeamViewer) however the frame rates were far too low and unreliable.
Possible solution A:
1) Encode openGL window as H.264 Video (natively supported by Android)
2) Stream the H.264 Video via RTSP using a server
3) View the content from an Android Browser (android and pc connected via WiFi)
Possible solution B:
1) Encode openGL window as IP Camera in c++ (is this possible?)
2) Use an IPCamViewer on Android device to view (again connected via WiFi)
I'm not entirely sure if either or both of these approaches are viable and would like some reassurance before moving forward.

A: What is the resolution of the image (is it equal to the current screen resolution, larger or smaller)? It is possible and efficient to transport a H.264 stream, but it also depends on the machine used to do the encoding. Hardware encoders or GPU-accelerated encoders are your best bet.
Remember - if you choose to go with encoding, you will have latency due to buffering (on the encode and the decode side). It will be a constant time offset so if that's not a problem you should be ok.
The total system delay as proposed by this paper is composed of

Note that none of these delays can be fully measured directly in frame-time. Some of these depend on the frame data and/or the encoder/processing performed. But as a rough estimate with fast GPU-encoding and hardware decoding I'd say a lag of around 5-20 frames. You'll have to measure the final latency per-scenario. I did this by sending frames containing text (ticks) and once the frames were steady, comparing them side-by-side. In fact, I even allowed the user to enter "test mode" at anytime to compensate for network traffic peak times or have him change the "quality" settings to tweak this delay.