text:
Q: pandas date time disaster, cannot convert rows of dates to anything uniformly usable Given this sample data from an excel file to csv (using Pandas) I have tried every form of pd.datetime to convert these seemingly uniform string dates to datetime format.  Use the flags errors='coerce' I lose a bunch of dates.  No good.  Use errors='ignore' I get some columns with dtype datetime and others remain object.  No good.  The goal is to grab the years for all these dates and then bin them in five year bins from 1980-2000.  At this point I am thinking pandas datetime parser is like the Kardashian of parsers, famous for nothing.
Date_1  Date_2    Date_3      Date_4      Date_5    Date_6
1000    9/1/2019    NaN      NaN          NaN       NaN
1001    NaN         NaN      NaN          NaN       NaN
1002    NaN         1/1/2000 NaN          NaN       NaN
1003    NaN         NaN      NaN          NaN       NaN
1004    NaN         4/1/2016 NaN          NaN       NaN
1005    NaN         NaN      NaN          NaN       1/1/2013

What have I tried.  pd.todatetime with various flags and without flags.
This is the most common error:
    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\arrays\datetimes.py in objects_to_datetime64ns(data, dayfirst, yearfirst, utc, errors, require_iso8601, allow_object)
   2053         try:
-> 2054             values, tz_parsed = conversion.datetime_to_datetime64(data)
   2055             # If tzaware, these values represent unix timestamps, so we

pandas\_libs\tslibs\conversion.pyx in pandas._libs.tslibs.conversion.datetime_to_datetime64()

TypeError: Unrecognized value type: <class 'str'>

Tried even converting all date strings to just strings and using regex to grab just the year.  I only need the year for each of these dates to then use pd.cut or groupby and get the following result in bins.
1980 - 1985     347
1986 - 1990     450
1995 - 2000     47

and so on.
However, having done what I thought was a good set of operations, I keep ending up with dramatically less in date figures than are in the actual data set, like 50% of the dates just disappear from the dataset no matter what datetime conversion is attempted.  So much frustration that I have actually linked half the dataset in csv format here so you can actually check out what I am dealing with in reality

A: I've got a solution which is a bit convoluted but should work.
Read the values, convert to string, remove nan's, gather the dates into a list per row, filter the lists for where there are actual values, explode the lists and you have a series with the dates. You can do it in one go but I'll break down the steps.
import pandas as pd
df = pd.read_csv("tst_file.csv")
df = df.drop("Unnamed: 0", axis=1)
df_str = df.astype(str).replace("nan", "")
df_lists = df_str.apply(list, axis=1)
df_filtered = df_lists.apply(lambda x: list(filter(lambda y : len(y) >= 1, x)))
clean = df_filtered.explode()

dates = pd.to_datetime(clean, format="%m/%d/%Y")
ts = pd.DataFrame(dates, columns=["time"])
ts["year"] = ts["time"].dt.year

Now you can bin the years as you wish
It looks like this :
          time    year
0   2019-09-01  2019.0
1   2011-01-01  2011.0
2   2000-01-01  2000.0
3          NaT     NaN
4   2016-04-01  2016.0
..         ...     ...
995 2020-01-01  2020.0
996 2015-02-01  2015.0
997 2016-04-01  2016.0
998 2001-12-01  2001.0
999 2016-01-01  2016.0

[1162 rows x 2 columns]

You can keep the original index and create a new one, a good way is also to set the dates as index and use loc to grab the relevant slices.
ts = ts.reset_index()
ts = ts.set_index("time").sort_index()

For example, there are 285 rows in this interval
ts.loc["2010":"2015"]

            index    year
time
2010-01-01    418  2010.0
2010-01-01    318  2010.0
2010-01-01    416  2010.0
2010-01-01    676  2010.0
2010-01-01    729  2010.0
...           ...     ...
2015-12-01    827  2015.0
2015-12-01    409  2015.0
2015-12-01    194  2015.0
2015-12-02    804  2015.0
2015-12-15    513  2015.0

[285 rows x 2 columns]


text:
Q: How to switch left and right in a css file? I have an HTML django template page that is both RTL and LTR (depends on user's locale).
The CSS of this page is stored in another file, and that file is currently static.
What is the best way to switch the attribute left and right according to the locale? Is there a built in attribute in CSS for this problem? (I don't want to use JS, it feels too messy)
I have:
.elem{
    left: 10px;
    bottom: 10px;
    position: absolute;
}

I want something like this:
.elem{
    right-or-left-according-to-html-dir: 10px;
    bottom: 10px;
    position: absolute;
}

Currently the only option I can think of is turning the file into a template also:
.elem{
    {{dir}}: 10px;
    bottom: 10px;
    position: absolute;
}

Is there a better way that will let me keep my CSS file static?

A: How about adding the direction to your body element via a special class, then you can write according selectors:
<body class="rtl">

and in the CSS:
.rtl .myclass {
   text-align: right;
}

A: You say you're making the document rtl or ltr depending on locale. In that case you can use the :lang() selector to make certain parts of your document have styling depending on the locale.

*

*http://www.w3.org/wiki/CSS/Selectors/pseudo-classes/:lang

*http://www.w3.org/TR/css3-selectors/#lang-pseudo
If you want a little more support (IE7+) you could use the attribute selector selector[lang='en'] though that will only test the attribute on the specified selector.

*

*http://www.w3.org/TR/css3-selectors/#attribute-selectors
If you specify the language in the html element (which you should, with lang="en" for example) you can just put the html selector in front of the class you want to apply in certain locales:
.elem {
    margin: 0 10px 0 0;
    color: blue;
}

html[lang='en'] .elem {
    margin: 0 0 0 10px;
}

Even better, if you specified the dir attribute you can directly use that in css like so:
.elem[dir='rtl'] {
    margin: 0 10px 0 0;
}

Please note that with a class on the body element you will always depend on that class always being there. But the dir and lang attribute can be specified on a more specific scope, like a single div, and still be used in the css along with styles for the 'other' reading directions.
Edit
Lastly, to gaze into the future, the CSS Selectors 'Level 4' will include a psuedo tag which will be able to filter on text directionality. Of course the specs are in development and adoption by browsers may take years before it is possible to reliably use it:
http://dev.w3.org/csswg/selectors4/#dir-pseudo

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set all pages of a Fireworks CS4 document to PNG? I've a Fireworks CS4 document containing multiple pages. The File > Export > Pages to Files feature generates GIFs but I want PNGs instead. How can I change this setting for all pages avoiding to go through each page and manually change this setting?

A: To Export All pages in preferred image format (in our case as PNG):
Set all pages to export as PNG:

*

*select all pages in Window > Pages (shortcut F5)

*in Window > Optimize (F6) setup your preferred image format (in our case PNG).

*all pages are now set to export as PNG files.

Now export (save) all pages:
Note: page names/titles, see/edit them in Window > Pages (F5), are used as names for exported files
Solution FIREWORKS CS4

*

*File > Export.. (Ctrl+Shift+R)

*IMPORTANT: uncheck "Current page only" on bottom of Export window.

Solution FIREWORKS CS5

*

*select pages > rightclick > Export all

A: I had a similar problem, where Fireworks kept exporting .gifs even when I specified PNG (use the "Export Wizard" in File > Export Wizard.
What was odd is that my index page (page 1) was a PNG, and the other pages were GIF. I have no idea why they defaulted as GIF, but that was the culprit. See attached image, the document type is specified there and it has to be PNG.
Image: http://davormiksic.com/iphone_test/png_check.png
I believe you can make your file type PNG by "Save As" and choosing PNG. Otherwise, when I do "Create New" and start working, it is PNG by default for me. Hope that helps.

A: I know this is not the answer you want, but, having those gif files, you could do a batch process, like:
Fireworks CS5:

*

*File > Batch Process...

*Select all files you want

*Select "Export" as batch option, and choose "custom" from setting tab

*Select the PNG format you want, or any other in the format tab

*Set the location for the files

*and then batch =)


text:
Q: Error: Element type is invalid with React-app I can see that there is a lot of questions oriented around this particular error, but most seem unanswered, and those that have been answered do not apply (or I don't understand how they apply.).
This is the Error I'm getting:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of `Posts`.

And this is my code in the related file:
import React from 'react';
import './Posts.css'

class Posts extends React.Component {
    constructor() {
        super()
        this.state = {
            posts: []
        }
        console.log("from constructor");
    }

    componentDidMount() {
        fetch('http://jsonplaceholder.typicode.com/posts/')
            .then(response => response.json())
            .then(data => {
                this.setState({
                    posts: data
                })
            })
    }

    render() {
        return(

                {
                    this.state.posts.map(Post => {
                        return(
                            <Post title={Post.title} desc={Post.body}/>
                        )
                    })
                }

        )
    }
}

export default Posts

Im currently working through an online course and this has stopped me in my tracks, any help would be greatly appreciated.

A: You use the same variable for the map iterator value and the component name. Change it to this:
render() {
        return(

                {
                    this.state.posts.map(p => {
                        return(
                            <Post title={p.title} desc={p.body}/>
                        )
                    })
                }

        )
    }


text:
Q: Apex Mocks github deployment to Production stuck in Status: Queued I'm attracted to the FinancialForce apexmocks and related libraries, and have successfully deployed to Trailhead playgrounds, Dev sandboxes and our full sandboxes.  The deployments ran quite smoothly and quickly.  When I went to deploy apexmocks to our Production instance, the status doesn't move past Status: Queued.  Are there settings that I should check in Production to see why there's such a difference?
I will try again in the wee hours, but I tried yesterday afternoon, (relatively) early this morning and ~2:00 p.m. EST, and I see neither progress nor errors.

A: NOTE: The tool does not run tests during the deployment, so will not deploy into production orgs, I may add a checkbox with a big disclaimer around it if there is demand. Bottom line this is a developer tool.
via the man himself: https://andyinthecloud.com/2013/09/24/deploy-direct-from-github-to-salesforce/


text:
Q: Would an executable need an OS kernel to run? I know that when the source code, in say C++, is compiled, the output from the compiler is the machine code (executable) which I thought were instructions to the CPU directly. Recently I was reading up on kernels and I found out that programs cannot access the hardware directly but have to go through the kernel.
So when we compile some simple source code, say with just a printf() function, and the compilation produces the executable machine code, will each instruction in this machine code be directly executed from memory (once the code is loaded into memory by the OS) or will each command in the machine code still need to go through the OS (kernel) to be executed?
I have read a similar question. It did not explain if the machine code that is generated after compilation is an instruction to the CPU directly or if it will need to again go through the kernel to create the correct instruction for the CPU. I.e., what happens after the machine code is loaded into memory? Will it go through the kernel or directly talk to the processor?

A: As someone who has written programs that execute without an OS, I offer a definitive answer.

Would an executable need an OS kernel to run?

That depends on how that program was written and built.
You could write a program (assuming you have the knowledge) that does not require an OS at all.
Such a program is described as standalone.
Boot loaders and diagnostic programs are typical uses for standalone programs.
However the typical program written and built in some host OS environment would default to executing in that same host OS environment.
Very explicit decisions and actions are required to write and build a standalone program.

... the output from the compiler is the machine code (executable) which I thought were instructions to the CPU directly.

Correct.

Recently I was reading up on kernels and I found out that programs cannot access the hardware directly but have to go through the kernel.

That's a restriction imposed by a CPU mode that the OS uses to execute programs, and facilitated by certain build tools such as compilers and libraries.
It is not an intrinsic limitation on every program ever written.

So when we compile some simple source code, say with just a printf() function, and the compilation produces the executable machine code, will each instruction in this machine code be directly executed from memory (once the code is loaded into memory by the OS) or will each command in the machine code still need to go through the OS (kernel) to be executed?

Every instruction is executed by the CPU.
An instruction that is unsupported or illegal (e.g. process has insufficient privilege) will cause an immediate exception, and the CPU will instead execute a routine to handle this unusual condition.
A printf() function should not be used as an example of "simple source code".
The translation from an object-oriented high-level programming language to machine code may not be as trivial as you imply.
And then you choose one of the most complex functions from a runtime library that performs data conversions and I/O.
Note that your question stipulates an environment with an OS (and a runtime library).
Once the system is booted, and the OS is given control of the computer, restrictions are imposed on what a program can do (e.g. I/O must be performed by the OS).
If you expect to execute a standalone program (i.e. without an OS), then you must not boot the computer to run the OS.

... what happens after the machine code is loaded into memory?

That depends on the environment.
For a standalone program, it can be executed, i.e. control is handed over by jumping to the program's start address.
For a program loaded by the OS, the program has to be dynamically linked with shared libraries it is dependent on.  The OS has to create an execution space for the process that will execute the program.

Will it go through the kernel or directly talk to the processor?

Machine code is executed by the CPU.
They do not "go through the kernel", but nor do they "talk to the processor".
The machine code (consisting of op code and operands) is an instruction to the CPU that is decoded and the operation is performed.
Perhaps the next topic you should investigate is CPU modes.

A: When you compile your code, you create so-called "object" code that (in most cases) depends on system libraries (printf for example), then your code is wrapped by linker that will add kind of program loader that your particular operating system can recognize (that is why you can't run program compiled for Windows on Linux for example) and know how to unwrap your code and execute. So your program is as a meat inside of a sandwich and can be eaten only as a bundle, in whole.

Recently I was reading up on Kernels and I found out that programs cannot access the hardware directly but have to go through the kernel.

Well it is halfway true; if your program is a kernel mode driver then actually you can access directly hardware if you know how to "talk" to hardware, but usually (especially for undocumented or complicated hardware) people use drivers that are kernel libraries. This way you can find API functions that know how to talk to hardware in almost human readable way without the need to know addresses, registers, timing and bunch of other things.

will each instruction in this machine code be directly be executed from the memory (once the code is loaded into the memory by OS) or will each each command in the machine code still need to go through the OS(kernel) to be executed

Well, the kernel is as a waitress, whose responsibility is to walk you to a table and serve you. The only thing it can't do - it is eat for you, you should do that yourself. The same with your code, kernel will unpack your program to a memory and will start your code which is machine code executed directly by CPU. A kernel just need to supervise you - what you are allowed and what you're not allowed to do.

it not explain if the machine code that is generated after compilation is an instruction to the CPU directly or will it need to again go through the kernel to create the correct instruction for the CPU?

Machine code that is generated after compilation is an instruction to the CPU directly. No doubt on that. The only thing you need to keep in mind, not all code in compiled file are actual machine's/CPU code. Linker wrapped your program with some meta data that only kernel can interpret, as a clue - what to do with your program.

What happens after the machine code loaded on to the memory? Will it go through the kernel or directly talk to the processor.

If your code is just simple opcodes like addition of two registers then it will be executed directly by CPU without kernel assistance, but if your code using functions from libraries then such calls will be assisted by kernel, as in example with waitress, if you want to eat in a restaurant they would give you a tools - fork, spoon (and it still their assets) but what you will do with it, - it up to your "code".
Well, just to prevent flame in comments - it is really oversimplified model that I hope would help OP understand base things, but good suggestions to improve this answer are welcome.

A: The kernel is "just" more code. It's just that that code is a layer that lives between the lowest parts of your system and the actual hardware.
All of it runs directly on the CPU, you just transition up through layers of it to do anything.
Your program "needs" the kernel in just the same way it needs the standard C libraries in order to use the printf command in the first place.
The actual code of your program runs on the CPU, but the branches that code makes to print something on screen go through the code for the C printf function, through various other systems and interpreters, each of which do their own processing to work out just how hello world! actually gets printed on your screen.
Say you have a terminal program running on a desktop window manager, running on your kernel which in turn is running on your hardware.
There's a lot more that goes on but lets keep it simple...

*

*In your terminal program you run your program to print hello world!

*The terminal sees that the program has written (via the C output routines) hello world! to the console

*The terminal program goes up to the desktop window manager saying "I got hello world! written at me, can you put it at position x, y please?"

*The desktop window manager goes up to the kernel with "one of my programs wants your graphics device to put some text at this position, get to it dude!"

*The kernel passes the request out to the graphics device driver, which formats it in a way that the graphics card can understand

*Depending on how the graphics card is connected other kernel device drivers need to be called to push the data out on physical device buses such as PCIe, handling things like making sure the correct device is selected, and that the data can pass through relevant bridge or converters

*The hardware displays stuff.

This is a massive oversimplification for description only. Here be dragons.
Effectively everything you do that needs hardware access, be it display, blocks of memory, bits of files or anything like that has to go through some device driver in the kernel to work out exactly how to talk to the relevant device. Be it a filesystem driver on top of a SATA hard disk controller driver which itself is sitting on top of a PCIe bridge device.
The kernel knows how to tie all these devices together and presents a relatively simple interface for programs to do things without having to know about how to do all of these things themselves.
Desktop window managers provide a layer that means that programs don't have to know how to draw windows and play well with other programs trying to display things at the same time.
Finally the terminal program means that your program doesn't need to know how to draw a window, nor how to talk to the kernel graphics card driver, nor all of the complexity to do with dealing with screen buffers and display timing and actually wiggling the data lines to the display.
It's all handled by layers upon layers of code.

A:
So when we compile a simple source code, say with just a printf() function, and the compilation produces the executable machine code, will each instruction in this machine code be directly be executed from the memory (once the code is loaded into the memory by OS) or will each each command in the machine code still need to go through the OS(kernel) to be executed?

Essentially, only system calls go to the kernel.  Anything to do with I/O or memory allocation/deallocation typically eventually results in a system call.  Some instructiosn can only be executed in kernel mode and will cause the CPU to trigger an exception.  Exceptions cause a switch to kernel mode and a jump to kernel code.
The kernel does not process every instruction in a program.  It just does the system calls and switches between running programs to share the CPU.
Doing memory allocation in user-mode (without the kernel) is not possible, if you access memory you don't have permission to access, the MMU, previously programmed by the kernel, notices and causes a CPU-level "segmentation fault" exception, which triggers the kernel, and the kernel kills the program.
Doing I/O in user-mode (without the kernel) is not possible, if you access I/O ports or registers for devices, or addresses connected to devices (one or both needed to perform any I/O), these trigger an exception in the same way.

Would a executable need a OS kernel to run?

Depends on the type of executable.
Kernels, in addition to mediating shared access to RAM and hardware, also perform a loader function.
Many "executable formats", like ELF or PE, have metadata in the executable file in addition to the code, and its the loader's job to process that.  Read the gory details about Microsoft's PE format for more information.
These executables also reference libraries (Windows .dll or Linux shared object .so files) - their code has to be included.
If your compiler produces a file that's meant to be processed by an operating system loader, and that loader is not there, it won't work.

*

*Can you include code that does the job of the loader?

Sure.  You need to convince the OS to somehow run your raw code without processing any metadata.  If your code calls kernel APIs, it still won't work.

*

*What if it doesn't call kernel APIs?

If you load this executable somehow from an operating system somehow (i.e. if it allows raw code to be loaded and executed), it will still be in user mode.  If your code accesses things that are prohibited in user mode, as opposed to kernel mode, such as unallocated memory or I/O device addresses/registers, it will crash with privilege or segment violations (again, exceptions go to kernel mode and are handled there) and still won't work.

*

*What if you run it from kernel mode.

Then it will work.

A: TL;DR No.
Arduino development comes to mind as a current environment where there's no OS.  Trust me, on one of these babies you don't have the space for an operating system.
Likewise, games for the Sega Genesis didn't have an OS provided by Sega to call on.  You just crafted your game in 68K assembler, writing directly to the bare metal.
Or where I cut my teeth, doing embedded work on the Intel 8051.  Again when all you have is a 2716 eprom with a 2k * 8 footprint, you don't have the room for an operating system.
Of course, this assumes a very broad usage of the word application.  As a rhetorical question, it's worth asking yourself if an Arduino sketch actually is an application.

A: While I don't want to imply that the other answers are not right on their own, they provide far too many details that, I'm afraid, are still very obscure to you.
The basic answer is that the code will be executed directly on the processor. And no, the machine code will not "talk" to anybody, it's the other way around. The processor is the active component and everything you do in your computer will be done by that processor (I'm simplifying things a bit here but that's OK for now). The processor will read the code and execute it and spit out the results, the machine code is just food for the processor.
Your confusion stems from the use of the word hardware. Although the division isn't as clear cut as it used to be, it's better if you think in terms of peripherals rather than simply calling everything hardware. So, if there is an operating system or similar on your machine, your program has to use its services for accessing the peripherals but the processor itself is not a peripheral, it's the main processing unit that your program runs on directly.
Kernels, operating systems and similar intervening layers are typically used only in larger systems where there is an expectation that several programs will run and there is a need for the system to manage how these programs can use the peripherals of the computer (quite often at the same time). In these cases, running programs can only access these peripherals using the system that will decide how to share them and will make sure there are no conflicts. Small systems where there is no need for any management among competing programs because there are none, often have no underlying system at all and the single program normally running on these systems is more or less free to do whatever it wants with the peripherals.

A: It depends on the environment. In many older (and simpler!) computers, such as the IBM 1401, the answer would be "no". Your compiler and linker emitted a standalone "binary" that ran without any operating system at all. When your program stopped running, you loaded a different one, which also ran with no OS.
An operating system is needed in modern environments because you aren't running just one program at a time. Sharing the CPU core(s), the RAM, the mass storage device, the keyboard, mouse, and display, among multiple programs at once requires coordination. The OS provides that. So in a modern environment your program can't just read and write the disk or SSD, it has to ask the OS to do that on its behalf. The OS gets such requests from all the programs that want to access the storage device, implements about things like access controls (can't allow ordinary users to write to the OS's files), queues them to the device, and sorts out the returned information to the correct programs (processes).
In addition, modern computers (unlike, say, the 1401) support the connection of a very wide variety of I/O devices, not just the ones IBM would sell you in the old days. Your compiler and linker can't possibly know about all of the possibilities. For example, your keyboard might be interfaced via PS/2, or USB. The OS allows you to install device-specific "device drivers" that know how to talk to those devices, but present a common interface for the device class to the OS. So your program, and even the OS, doesn't have to do anything different for getting keystrokes from a USB vs a PS/2 keyboard, or for accessing, say, a local SATA disk vs a USB storage device vs storage that's somewhere off on a NAS or SAN. Those details are handled by device drivers for the various device controllers.
For mass storage devices, the OS provides atop all of those a file system driver that presents the same interface to directories and files regardless of where and how the storage is implemented. And again, the OS worries about access controls and serialization. In general, for example, the same file shouldn't be opened for writing by more than one program at a time without jumping through some hoops (but simultaneous reads are generally ok).
So in a modern general-purpose environment, yes - you really need an OS. But even today there are computers such as real-time controllers that aren't complicated enough to need one.
In the Arduino environment, for example, there isn't really an OS. Sure, there's a bunch of library code that the build environment incorporates into every "binary" it builds. But since there is no persistence of that code from one program to the next, it's not an OS.

A: The BIOS that runs in your computer on power up is executable code stored in ROM.  It consists of machine instructions plus data.  There is a compiler (or assembler) that assembles this BIOS from source code.  This is a special case.
Other special cases include the bootstrap program that loads the kernel and the kernel itself.  These special cases are generally coded in a language other than C++.
In the general case, it is much more practical to have the compiler produce some instructions that invoke system services provided by a kernel or by library routines.  It makes the compiler much more lightweight.  It also makes the compiled code more lightweight.
At the other end of the spectrum is Java.  In Java, the compiler does not translate the source code into machine instructions, as this term is usually understood.  Instead, the source code is translated into "machine instructions" for an imaginary machine, called the Java Virtual Machine.  Before a Java program can run,  it must be combined with the Java runtime, which includes an interpreter for the Java Virtual Machine.

A: In the good old days your program was responsible for doing everything that needed to be done during the execution of your program, either by you doing it yourself or by adding library code others wrote to your program.   The only thing running beside that in the computer was the code to read in your compiled program - if you were lucky.   Some computers had to had code entered through switches before being able to do more (the original "bootstrap" process), or even your whole program entered this way.
It was quickly found that it was nice to have code running capable of loading and executing program.   Later it was found that computers were powerful enough to support running several programs at the same time by having the CPU switch between them, especially if the hardware could help, but with the added complexity of the programs not steppings on each others toes (for instance, how to handle multiple programs trying to send data to the printer at once?).
All this resulted in a large amount of helper code being moved out of the individual programs and into the "operating system", with a standardized way of invoking the helper code from user programs.
And that is where we are today.  Your programs run full speed but whenever they need something managed by the operating system they call helper routines provided by the operating system, and that code is not needed and not present in the user programs themselves.  This included writing to the display, saving files, accessing the network, etc.
Microkernels have been written that provide just what is needed for a given program to run without a full operating system.  This has some advantages for the experienced users while giving away most others.   You may want to read the Wikipedia page about it - https://en.wikipedia.org/wiki/Microkernel - if you want to know more.
I experimented with a Microkernel capable of running a Java Virtual Machine, but found later that the sweet spot for that is Docker.

A: I think many answers misunderstand the question, which boils down to this:

A compiler outputs machine code. Is this machine code executed directly by a CPU, or is it "interpreted" by the kernel?

Basically, the CPU directly executes the machine code. It would be significantly slower to have the kernel execute all applications. However, there are a few caveats.

*

*When an OS is present, application programs typically are restricted from executing certain instructions or accessing certain resources. For example, if an application executes an instruction which modifies the system interrupt table, the CPU will instead jump to an OS exception handler so that the offending application is terminated. Also, applications are usually not allowed to read/write to device memory. (I.e. "talking to the hardware".) Accessing these special memory regions is how the OS communicates with devices like the graphics card, network interface, system clock, etc.

*The restrictions an OS places on applications are achieved by special features of the CPU, such as privilege modes, memory protection, and interrupts. Although any CPU you would find in a smartphone or PC has these features, certain CPUs do not. These CPUs do indeed need special kernels which "interpret" application code in order to achieve the features that are desired. A very interesting example is the Gigatron, which is an 8-instruction computer you can build out of chips which emulates a 34-instruction computer.

*Some languages like Java "compile" to something called Bytecode, which is not really machine code. Although in the past they were interpreted to run the programs, these days something called Just-in-Time compilation is usually used so they do end up running directly on the CPU as machine code.

*Running software in a Virtual Machine used to require its machine code to be "interpreted" by a program called a Hypervisor. Due to enormous industry demand for VMs, CPU manufacturers have added features like VTx to their CPUs to allow most instructions of a guest system to be executed directly by the CPU. However, when running software designed for an incompatible CPU in a Virtual Machine (for example, emulating a NES), the machine code will need to be interpreted.

A: In typical desktop OSes, the kernel itself is an executable. (Windows has ntoskrnl.exe; Linux has vmlinux, etc.)  If you needed a kernel in order for an executable to run, then those OSes could not exist.
What you need a kernel for is to do the things a kernel does. Allow multiple executables to run at once, referee between them, abstract the hardware, etc. Most programs aren't capable of doing that stuff themselves competently, and you wouldn't want them to even if they could. In the days of DOS -- which could barely be called an operating system itself -- games often used the OS as little more than a loader, and directly accessed the hardware much like a kernel would.  But you often had to know what brands and models of hardware were in your machine before you bought a game. Many games only supported certain families of video and sound cards, and ran very poorly on competing brands if they worked at all.  That's the kind of thing you get when the program controls the hardware directly rather than through the abstraction typically provided via the kernel.)


text:
Q: make infinite loop pyrogram I need this part of script work infinitely(send messages), but it works only one time and then stops
f = open('text.txt')
t = 1
with app:
    while True:
        for line in f.readlines():
            try:
                app.send_message(chat_id=line[13:].rstrip(), text=txt)
                print(f"Успешно написал в чат по ссылке {line}")
                time.sleep(0.5)
            except:
                print(f"Что-то пошло не так... Возможно в чате {line} включен медленный режим")```

A: The for loop stops when it gets to the end of the file. When the while loop repeats, there's nothing for the for loop to read because you're already at the end of the file.
You can seek to the beginning each time.
f = open('text.txt')
t = 1
with app:
    while True:
        f.seek(0)
        for line in f.readlines():
            try:
                app.send_message(chat_id=line[13:].rstrip(), text=txt)
                print(f"Успешно написал в чат по ссылке {line}")
                time.sleep(0.5)
            except:
                print(f"Что-то пошло не так... Возможно в чате {line} включен медленный режим")

Or you could save the contents to a list and loop through that.
with open('text.txt') as f:
    lines = f.readlines()
t = 1
with app:
    while True:
        for line in lines:
            try:
                app.send_message(chat_id=line[13:].rstrip(), text=txt)
                print(f"Успешно написал в чат по ссылке {line}")
                time.sleep(0.5)
            except:
                print(f"Что-то пошло не так... Возможно в чате {line} включен медленный режим")


text:
Q: Sitecore GraphQL from the frontend I am looking for an article/example taht can help me do the following:
Run a graphql query (which runs perfectly in the Playground) through my react code
This is the code I am referring to:
export const getStaticProps : GetStaticProps = async(context)=> {
  const endPoint = process.env.PREVIEW_URL as string;
  const graphQLClient = new GraphQLClient(endPoint);
  graphQLClient.setHeader('X-GQL-Token', process.env.PREVIEW_API as string);
  const query = gql`{

      item(path: "/sitecore/content/sug-containers/home/Item" language: "en"){
          field(name: "imageSrc") {
          ... on ImageField {
            id(format: "B")
              name
              src
          }
        }
      }
    }
  }`

  const data = await graphQLClient.request(query);
  console.log(JSON.stringify(data, undefined, 2))
  return{
    props:{data}
  };
}

However, no data is every returned. Props is always null.
I think my query definition is incorrect. I copied the query that runs successfully in the playground. Does anyone know what the problem could be or point me to a working example somewhere please? I have referred to this article:
https://thetombomb.com/posts/do-you-need-graphql-client
In the GraphQL playground, this is the query I use:
query {
    item(path: "/sitecore/content/sug-containers/home/AvistaLogo" language: "en"){
        field(name: "imageSrc") {
      ... on ImageField {
        id(format: "B")
          name
          src
      }
    }
  }
}

And here is the output:
{
  "data": {
    "item": {
      "field": {
        "id": "{94B0DA6A-D944-489B-B6B0-39094114F244}",
        "name": "imageSrc",
        "src": "/sitecore/shell/-/media/Images/Logos/logo.svg"
      }
    }
  }
}


text:
Q: using DataURL in VB.NET happy new year!
I just want to generate DataURL type data in VB.Net and also want to load string type DataURL to an image.
In other words, I want to convert an image in PictureBox(or Image) into string type DataURL vice versa.
The purpose of this kind of doubtful procedure is to save string data and image data into one single file.
Thank you!

A: Something like this:
Use this function to get a Base64 string representation of the Image
Public Function ToBase64String(ByVal aImage As Image) As String
    Using stream = New System.IO.MemoryStream
        aImage.Save(stream, System.Drawing.Imaging.ImageFormat.Png)
        Return Convert.ToBase64String(stream.ToArray)
    End Using
End Function

Then use this to display it:
<img src="data:image/png;base64, Base64StringHere" />


text:
Q: Ksh - Script: List Files and store as variable I'm using kshon an HP-UX box.
In a portion of my script, I want to list certain files (*.xml), have them numbered and have the user choose a file by typing the number and hitting enter. That filename will then be stored as a variable.
Example of output:
Please choose a file:
1) bar27.xml
2) foo1.xml
3) foobar4.xml

Then the user types in 1, 2, or 3 and hit enter.  The file name chosen needs to be stored as a variable. So if the user chooses 2 the variable should contain foo1.xml.

A: I've come up with the following which works:
files=$(ls *.xml)
i=1

for j in $files
do
echo "$i) $j"
file[i]=$j
i=$(( i + 1 ))
done

echo "Choose an XML file from above to use:"
read v_CHOOSELIST
echo "File chosen: ${file[$v_CHOOSELIST]}"


text:
Q: Redirecting to a page after submission Hi i have a HTML form like this:
 <form id="msform" action="https://forms.hubspot.com/uploads/form/v2/5435007/bb741987-d401-482b-86b3-13ebf0405ec4" method="post">

  <input type="email" id="mail" name="email" value="{{request.query_dict.email}}">
   <input type="hidden" id="something" name="hs_context" value="">
 <fieldset>
    <legend>4Section 4 (4/5)</legend>

Do you have a COS Account Manager? (Your account manager is your primary sales contact at COS)

     1. My account manager is exceptional at providing solutions to my business problems:
      <input type="radio" id="radio_s4_01" value="Strongly Disagree" name="my_account_manager_is_exceptional">Strongly Disagree
      <input type="radio" id="radio_s4_02" value="Slightly Disagree" name="my_account_manager_is_exceptional">Slightly Disagree
          <input type="radio" id="radio_s4_03" value="Disagree" name="my_account_manager_is_exceptional">Disagree
          <input type="radio" id="radio_s4_04" value="Neutral" name="my_account_manager_is_exceptional">Neutral
          <input type="radio" id="radio_s4_05" value="Slightly Agree" name="my_account_manager_is_exceptional">Slightly Agree
          <input type="radio" id="radio_s4_06" value="Strongly Agree" name="my_account_manager_is_exceptional">Strongly Agree

         7. Other:
       <textarea id="bio" name="other_section_5"></textarea>

       <input type="button" name="previous" class="previous action-button" value="Previous" />
       <input type="button" name="next" class="next action-button" value="Next" />
     </fieldset>

  <fieldset>
     <legend>6Section 6 (6/6)</legend>
    1. How likely are you to recommend COS to a colleague or friend?
     <textarea id="bio" name="how_likely_are_you_to_recommend"></textarea>

        2. What are your reasons for giving that score?
     <textarea id="bio" name="what_are_your_reasons_for_giving_that_score"></textarea>

        3. What ONE THING (if any) should COS START doing right now?
     <textarea id="bio" name="what_one_thing_if_any_should"></textarea>

        4. What ONE thing (if any) should COS STOP doing right now?
     <textarea id="bio" name="one_thing_if_any_should_cos_stop"></textarea>

        5. What is COS' single greatest STRENGTH?
     <textarea id="bio" name="cos_single_greatest_strength"></textarea>

        6. What is COS' single greatest WEAKNESS?
     <textarea id="bio" name="cos_single_greatest_weakness"></textarea>

        7. Lastly, do you have any advice or feedback to give to the COS General Manager?
     <textarea id="bio" name="lastly_do_you_have_any_advice"></textarea>
    <input type="button" name="previous" class=" previous action-button" value="Previous" />
    <input type="submit" value="Submit" class="action-button" />
  </fieldset>

</form>

and i have a piece of javascript that create multi-step form, however i was trying to make it redirecting to another page after the subsmission but im stuck, i tried to use window.location but didnt work, here is the entire js:
$(function() {

//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    next_fs = $(this).parent().next();

    //activate next step on progressbar using the index of next_fs
    $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

    //show the next fieldset
    next_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale current_fs down to 80%
            scale = 1 - (1 - now) * 0.2;
            //2. bring next_fs from the right(50%)
            left = (now * 50)+"%";
            //3. increase opacity of next_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({'transform': 'scale('+scale+')'});
            next_fs.css({'left': left, 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".previous").click(function(){
    if(animating) return false;
    animating = true;

    current_fs = $(this).parent();
    previous_fs = $(this).parent().prev();

    //de-activate current step on progressbar
    $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

    //show the previous fieldset
    previous_fs.show();
    //hide the current fieldset with style
    current_fs.animate({opacity: 0}, {
        step: function(now, mx) {
            //as the opacity of current_fs reduces to 0 - stored in "now"
            //1. scale previous_fs from 80% to 100%
            scale = 0.8 + (1 - now) * 0.2;
            //2. take current_fs to the right(50%) - from 0%
            left = ((1-now) * 50)+"%";
            //3. increase opacity of previous_fs to 1 as it moves in
            opacity = 1 - now;
            current_fs.css({'left': left});
            previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
        },
        duration: 800,
        complete: function(){
            current_fs.hide();
            animating = false;
        },
        //this comes from the custom easing plugin
        easing: 'easeInOutBack'
    });
});

$(".submit").click(function(){
  return false;
})
//end of line
});

can someone suggest a good solution for this? im not using any serverside code to execute anything, just simply use frontend script to handle the task

A: Change the action URL of a form :
$("#msform").attr("action", "<<<<new action>>>>>");
$("#msform").submit();


text:
Q: Set two strings in logging so my script goes like this:
import logging
LOG_FORMAT = "%(levelname)s %(message)s - %(asctime)s"
logging.basicConfig(filename="newfile.log",
                level=logging.DEBUG,
                format= LOG_FORMAT,
                filemode= 'w')
logger = logging.getLogger()
s1 = "14-03-2019"
s2 = "13    185 Log 357 - sr 6 at realtime"

logger.info(s1+s2)

print:
INFO 14-03-201913   185 Log 357 - sr 6 at realtime - 2022-01-05 19:14:58,670

and what i actually want, is that the s1 will appear first in the line, before the INFO like this:
14-03-2019 INFO 13   185 Log 357 - sr 6 at realtime - 2022-01-05 19:14:58,670


text:
Q: Assign 'active' class only to deepest child I have a bootstrap-based
 navigation tree where every
 in the path to the current page is given the class "active". So if I was on a page two levels below the homepage, the code would be roughly like this:

Link1

Link2

Link3

sublink1

sublink2

subsublink1

subsublink2 THIS IS MY PAGE

The problem is that bootstrap adds a border to all li.active elements. And I only want the border to apply to the deepest one, i.e., the page I'm actually on.
I'm not going to mess with the bootstrap underpinnings, so I'm not going to remove the active class from the whole path.
My goal is to have jQuery remove the unwanted borders. I want to find any li.active with no children that are li.active, which indicates it's the deepest li.active in the path. Then find all its parents with li.active and remove the border from them.
HOW WOULD I CONSTRUCT THAT JQUERY?
I'm thinking something like this (knowing that notHasClass doesn't exist):
$('li.active').children().notHasClass('active').parents.hasClass('active').css('border','none');

A: Find all li.active elements which contain another .active element and remove the border:
$('li.active:has(.active)').css({ border : 'none' });

http://jsfiddle.net/X8K4E/

A: This:
$("li.active").each(function(){
    if($(this).find("li.active").length>0){
        $(this).css("border","none");
    }
})

JSFiddle: http://jsfiddle.net/DDUNE/
Or i didn't understand you right?

A: With :last u get the last element in the DOM. So you can get the parents with li.active and remove the border.
$('li.active:last').parents('li.active').css('border', 'none');

Check out the example:
http://jsfiddle.net/kmgUh/
Alternatively u can replace .css('border', 'none') with removeClass('active').
Best regards

A: I am assuming that li can only have ul as its children and that only li will have .active class, and for these assumptions, this works:
$('li.active').filter( function () {
    if ( $(this).children('ul').length === 0 )
        return true;
    return false;
}).parents('li').removeClass('active');

DEMO

A: found a slightly different way to achieve it:
$('li.active').has('ul').addClass('hasSubmenu');

Obviously if my li contains a ul it can't be the deepest li.active.
So now I can use pure css to get rid of the border:
li.active.hasSubmenu {border:none}


text:
Q: Prove when Instaneous Velocity is equal to Average Velocity with Constant Acceleration Assume constant acceleration. It seems that average velocity over some time interval [t1, t2], will be equal to the instantaneous velocity at the midpoint t = 1/2[t1 + t2]. I'm wondering how you might prove this mathematically (assuming what I've said is even true). If it's not always true, I would be curious to see a counterexample. Thank you kindly, in advance!
I suppose it's really a question about secant lines, tangent lines, and derivatives, but this is the context in which I had the thought. Thanks again for taking the time.

A: This follows immediately from the definition of constant acceleration. We can define constant acceleration to mean that there is some acceleration $a$ such that for all times $w, x$, we have $v(w) - v(x) = a(w - x)$.
Suppose the constant acceleration is $a$. Let $m = \frac{t_1 + t_2}{2}$.
Then $v(m) - v(t_1) = a (m - t_1)$. Similarly, $v(t_2) - v(m) = a (t_2 - m)$.
Note that $m - t_1 = t_2 - m$. Therefore, $v(t_2) - v(m) = v(m) - v(t_1)$. Therefore, $v(m) = \frac{v(t_1) + v(t_2)}{2}$.

A: Alternative approach:
$$\frac{\int_{t_1}^{t_2} \left[V_0 + at\right]dt}{t_2 - t_1}$$
$$= \frac{\left[V_0t + \frac{1}{2}at^2\right] ~|_{t=t_1}^{t=t_2}}{t_2 - t_1}$$
$$= \frac{\left[V_0(t_2 - t_1)\right] + \left[\frac{1}{2}a(t_2 - t_1)(t_2 + t_1)\right]}{t_2 - t_1}$$
$$= V_0 + \left[\frac{1}{2}a(t_2 + t_1)\right].$$


text:
Q: Remove Dynamically created UIButton Subview I have applied a custombadge as a subview of a UIButton with the help of @Midhun MP in this question - Adding a subview to UIButton.
All works great - but I'm now trying to remove the subview when the button is clicked.
I've setup a method thats triggered via a click on one of the buttons
- (void)hide
{
    //Hide Buttons
    _importantMsg.hidden = YES;

    [CustomBadge removeFromSuperview];

}

But I'm struggling to hide the subview - I've tried -
[CustomBadge removeFromSuperview];

and
_MsgHeadBtn.subviews.hidden = YES;;

but i get unknown receiver errors - can anyone point me in thh right direction pls?
errors for each try show in screenshot below -

A: You need either a reference to the custom view so you can remove it, iVar or alternatively give the view a tag then use button viewForTag method and remove that way.
i.e.
@implementation ViewController {
   UIView *_customView;
}

-(void)addCustomsubView
{
   _customView = [UIView alloc] init …./ your initialize

   [button addSubView:_customView];
}

- (void)hide
{
   [_customView removeFromSuperView];
   _customView = nil;
}

A: try with this
the method which can have the button reference if you created button dynamically.
 -(void)hide:(UIButton *)sender
 {
   for(UIView *viewRef in sender.subviews)
    {
     if(viewRef isKindofClass:[CustomBadge class])
     {
      [viewRef removeFromSuperview];
     }
    }

 }

A: The first problem is  _MsgHeadBtn.subviews.hidden = YES;  .subviews is an array, that you cannot perform the setHidden selector on. The second issue-ish is that there's no point in hiding a view if you are removing it right after. Third problem is that
 [CustomBadge removeFromSuperview];

CustomBadge is not a instance of a class, an object, it is just a class. The theoratical approach would be smth like
-(void)addSomeView {
    //customBadge MUST be an instance variable or a property, otherwise you are not holding a reference to it so you can access it later
    customBadge = [[CustomBagde alloc] initWith...];
    [yourButton addSubView:customBadge];
}

-(void)hide {
    //This is where the app will crash if customBadge is not a property or an instance variable
    [customBadge removeFromSuperView];
}

A: You can use a tag on your custom subview to remove it later. Use this to add your custom view:
customBadge1.tag=1;
[_MsgHeadBtn addSubview:customBadge1];

and this to remove it
customBadge=[_MsgHeadBtn viewWithTag:1];
[customBadge removeFromSuperview]


text:
Q: spark-scala: groupBy throws java.lang.ArrayIndexOutOfBoundsException (null) I started with following a RDD that has string
((26468EDE20E38,239394055),(7665710590658745,-414963169),0,f1,1420276980302)
((26468EDE20E38,239394055),(8016905020647641,183812619),1,f4,1420347885727)
((26468EDE20E38,239394055),(6633110906332136,294201185),1,f2,1420398323110)
((26468EDE20E38,239394055),(6633110906332136,294201185),0,f1,1420451687525)
((26468EDE20E38,239394055),(7722056727387069,1396896294),0,f1,1420537469065)
((26468EDE20E38,239394055),(7722056727387069,1396896294),1,f1,1420623297340)
((26468EDE20E38,239394055),(8045651092287275,-4814845),0,f1,1420720722185)
((26468EDE20E38,239394055),(5170029699836178,-1332814297),0,f2,1420750531018)
((26468EDE20E38,239394055),(7722056727387069,1396896294),0,f1,1420807545137)
((26468EDE20E38,239394055),(4784119468604853,1287554938),0,f1,1421050087824)

Just to give an high level view on description of the data. You can think first element in the main tuple (first tuple) as a user identification, second tuple as a product identification, and third element is user's preference on the product. (for future reference I am going to mark above data set as val userData)
Here is how I construct userData:
val userData = data.map(x => {
  val userId = x._1.replace("_","")
  val programId = x._2
  val feature = someMethod(x._5, x._4)
  val userHashTuple = (userId, userId.hashCode)
  val programHashTuple = (programId, programId.hashCode)
  (userHashTuple, programHashTuple, x._3, timeFeature, x._4)
})

My goal is that if user has casted both positive (1) and negative (0) preference for a product only take the record with positive. For example:
((26468EDE20E38,239394055),(7722056727387069,1396896294),0,f1,1420537469065)
((26468EDE20E38,239394055),(7722056727387069,1396896294),1,f1,1420623297340)

I only want to keep
((26468EDE20E38,239394055),(7722056727387069,1396896294),1,f1,1420623297340)

Based on previously provided answer I followed following:
val grpData = userData.groupBy(x => (x._1, x._2)).mapValues(_.maxBy(_._3)).values

But I am getting an error at the stage of groupBy. java.lang.ArrayIndexOutOfBoundsException (null) [duplicate 1]
and its keep repeating the same error while increasing the duplicate number. Also exception doesn't point to my code so I am having tough time figuring out what exactly going on.
At the end I get following:
 java.lang.ArrayIndexOutOfBoundsException

Driver stacktrace:
        at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1203)
        at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1192)
        at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1191)
        at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
        at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
        at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1191)
        at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693)
        at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693)
        at scala.Option.foreach(Option.scala:236)
        at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:693)
        at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1393)
        at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1354)
        at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)

Does this mean that key is empty? but if key is empty it would still carry out the groupBy for a "". So I am bit confuse.
After digging around I found following: https://issues.apache.org/jira/browse/SPARK-6772
But I don't think the issue is same but thats all I got.


text:
Q: How to populdate the dijit.form.ComboBox by calling the URL which will returns JSON data? I have a combox box component in the dojo datagrid like
var tacStore = {items:[]};
       Tac
And i have button when i clicked the button am trying to populate the Combo box using below code.
        function loadTimeZones() {

        dojo.xhrGet({
                //url: "/AAORPCAdapterServicesWeb/RPCAdapter/httprpc/TimeZoneService/getTimeZones",
                url: "/AAORPCAdapterServicesWeb/RPCAdapter/httprpc/DeliverableService/getAllTacs",
                handleAs:"json",
                load: createTimeZoneStore,
                error: function(error,ioargs){
                  console.log(error);
                }
            });
        return false;
    }

         function  createTimeZoneStore(response) {
        console.log("createTimeZoneStore::response:: "+response);
        if ( response.result != null) {
            var timezone = [];
            for(var resultCounter=0; resultCounter<response.result.length;resultCounter++)
            {
                timezone[resultCounter] = {};
                timezone[resultCounter]['name']=response.result[resultCounter];
                console.log("createTimeZoneStore::response.result[resultCounter]:: "+response.result[resultCounter]);
            }
            console.log("createTimeZoneStore::tacStore::tacs: "+tacStore);
            tacstore= new dojo.data.ItemFileWriteStore({data:{items:timezone}});
        }
        return false;
    }

Am getting response. But the values are not showing in the combobox. And when i click on combo box am getting error like this.fetch is not a function

A: First, you are using ItemFileWriteStore, which is the old dojo/data/api API. Combo box uses the newer dojo/store/api API (specifically, you can use the dojo/store/Memory implementation).
var myStore = new Memory({data: timezone});

Also, you are creating the store, but not connecting it to the ComboBox. If you are programatically creating the ComboBox, use
var myComboBox = new ComboBox({store: myStore});
myComboBox.placeAt(/* wherever you like */);
myComboBox.startup();

If the ComboBox is already created (either programatically, or using markup with data-dojo-id), use
myComboBox.set('store', myStore);
/* you may need to startup the ComboBox after this - but I am not sure */
myComboBox.startup();


text:
Q: Possible causes of garbage collection thread constantly using 100% cpu In our production tomcat deployment (Tomcat 8 + JVM 8) we have recently started observing that occasionally the garbage collection threads start using 100% cpu.
It is not a spike in usage. When it happens, the behavior persists and the only remedy is a system restart.
We took a heap dump during this time but unfortunately the dump file does not open using any tool - jhat or jvisualvm. Hence, we are unable to pin point the code where the allocation took place.
Why does this scenario happen ? Is it because the application has created a lot of objects and processing is taking a long time ?
(Note: We do have memory intensive functionality; hence an OutofMemoryError would have made sense than 100% cpu usage)


text:
Q: ClassCastException retriving element on a generic list I have the following clases:
public class PagedResult<T>
{
    private Integer count;
    private Integer pageSize;
    private Integer pageNumber;
    private Integer numPages;

    private List<T> result;
    ...
}

public class AbstractDAO <T>
{

    protected PagedResult<T> getPagedResult( String jpqlBusqueda, String jpqlCuenta, List<Object> parameters, Integer page, Integer pageSize, boolean isNative )
    {
     ...
    }
}

public class RecipeDAO extends AbstractDAO<Recipe>
{

    PagedResult<Recipe> search()
    {
       return getPagedResult( "aaaa", "aaaaa", ...);
    }
...
}

When I retrive a list of Recipe objects from BBDD using this, all works well up to the point when I try to access a single object in the result list like this:
PagedResult<Recipe> result = RecipeDAO.search(...);
Recipe theRecipe = result.getResult().get(0);

In this point I get a ClassCastException claiming that Object cannot be converted to Recipe. I try debugging and stopping the program before getting the object and netbeans debugger shows that the PagedResult object contains a list of Recipe objects. It's some kind of problem with the generics declaration, but i can not pinpoint it. Any ideas?

A: I found the problem. In the end it wasn't in the generics construcction but in the jpa part. Aparently when you call em.createNativeQuery(nativeQuery) the result it's a list of a generic type that cannot be casted to the Recipe. In order to do that you need to call em.createNativeQuery(nativeQuery, resultClass ) where resultClass it's Recipe in my case.
In order to get the resultClass dinamically so all stays generic and reusable we can do:
Class<T> resultClass = ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);

As I found in this excelent post.


text:
Q: How to get Specific Cell Value from CSV With Respect To Row And Column Value using python sample data:
user,hotel_name,city,review

adam,hotel1,chennai,"Wow, what charm! As a Travel Agent.

john,hotel2,pune,Great location for sporting events.

mike,hotel3,mumbai,Its the best of the best.

george,hotel4,delhi,Ok hotel in a bad location.

Hello all,
I would like to print the review given by mike from csv file. I am new to python can some one help me?

A: Let's assume your csv is in a file a called data.csv and you're running the script in the same directory.
Then you would do something like:
import pandas as pd              # bring in pandas

df = pd.read_csv('data.csv')     # load data
print(df[df['user'] == 'mike'])  # add a mask for mike and print row

A: Two ways, first with Python:
import csv

with open('file.csv', 'r') as fin:
    reader = csv.reader(fin)
    for line in reader:
        if line[0] == 'mike':
            print line[3]
            break

Now with Bash:
grep "mike" file.csv | cut -d, -f4

Its the best of the best.


text:
Q: Converting binary data/numbers into a memorable format What are my options for converting arbitrary binary data into a memorable format?
Are there any widely used standards? What is the most efficient way to do this? I.e. to encode the most data in the easiest-to-remember way?

A: You can use Bitcoin's BIP-39 standard, whereby numbers are split into 11 bits and each is mapped to a word from a list of 2048 words. These words are chosen whereby similar words are avoided and a word can be unambiguously determined based on the first 4 letters.


text:
Q: Changing form name causes error message "Error accessing the system registry" I am programming the On_Click method for the button labeled "View" in the first printscreen below.  The method will load a form with data corresponding with the specific address id in the row containing the "View" button.  This code worked perfectly when pointing to a target form called "Addresses".  However, when I decided to rename the form "Address", I started receiving the following error message when clicking on the view button:

I did some research on the web about this error message, which lead me to try to delete any outdated references in the VBA editor.  But when I clicked on Tools-->References in the VBA editor, I got the following error message:

It seems that MS Access' entries in the system registry might have been corrupted.  But I am not certain of this because the documentation of this on the web is sparse and inconsistent.
Here is a link to the database on a file sharing site:  http://jmp.sh/b/9Uyx6J2YzWbs8zPq2h6g
If the problem is in the database, you can recreate the problem by opening the form "Main" and clicking on the button "View" for the record shown in the printscreen above, or for other records.
Can anyone show me how to get past this error message?

A: my advices?

*

*You could rename your Forms!....SourceObject to "Address" instead of "Addresses"

*You could copy/paste the form, delete the original, and retry

*You could install a decent debugging tool like MZ-Tools for VBA, that will help you manage your errors. Check the details here
EDIT: I used to get similar bugs years ago, when I was writing specific form event procedures. As we decided to switch to a model where forms did not need to be debbuged anymore (check this here), we stopped getting this kind of message. And I think I forgot the trick we used to solve this kind of error. If I were you:

*

*I'd try to open another access database and import all objects ...

*I'd put aside/cancel the faulty onClick procedure

*And I'd install MZ Tools because otherwise VBA debugging is a nightmare ...

A: Since access was not liking the command button in each record of the continuous form, I choose to put the view button's logic in the on click event of a text box in each row, which I configured as enabled but locked.  This produces a separate link from each record of the continuous form to a unique detail page with more of the chosen record's data.
This solution works perfectly, and is enabling me to move on with my other coding.
However, it would be nice if someone else were able to show how to get the command button solution to work.


text:
Q: Is it possible to calculate the standard error of beta0 and beta1 with only their Estimates and Confidence Intervals in R? How do you calculate the standard error of beta0 and beta1 using only their Estimates and Confidence Intervals and the qt function in R?
Example:
         Est      L      U
beta0 -5.430 -5.710 -5.160
beta1  0.132  0.127  0.136

summary:
         Est  t value   Pr(>|t|)
beta0 -5.432  -29.94   <2e-16 ***
beta1  0.131   44.66   <2e-16 ***

I've calculated my quantile q-value using the qt function as follows:
conf <- .87 # size of confidence interval
qval <- -qt(p = (1-conf)/2, df = n-2) # inverse-cdf of a t(n-2)
qval <- qt(p = (1-conf)/2, df = n-2, lower.tail = FALSE)


text:
Q: Socket server with epoll gives unknown bytes at disconnect I have a socket server in C++ and I am using epoll. I am sending to the server a char that contains a HeaderPacket and the NormalPacket.
First I am reading the HeaderPacket and after that I am reading the NormalPacket.
And now the problem, when I close the client ( I was trying to use close and shutdown - same output ) I get some weird bytes on the first recv ( the one that reads the header packet ) and after that segmentation fault.
Also, when I change the size of my content char from HeaderPacket to another value for example 120 I don't get segmentation fault but when I set it to 40 or other value I get the segmentation fault.
#define BUFFERSIZE 256
#define CHARSIZE 40

Here is the function that I use it for reading:
void PacketHandler::ReadBytes(int fd, struct HeaderPacket &hp, char buffer[])

{

    int reading = 0;

    ssize_t hpCount, cpCount;

    char hpBuffer[6];

    hpCount = recv(fd, hpBuffer, 6, 0);

    if(hpCount <= 0)

    {

       reading = 1;

    } else {

        this->UnserializeHeaderPacket(hpBuffer, hp);

        print(DEBUG, Helpers::IntegerToString(hp.length));

        cpCount = hp.length;

        char cpBuffer[cpCount];

        memset(cpBuffer, 0, sizeof(cpBuffer));

        char* iterator = cpBuffer;

        int bytesLeft = sizeof(cpBuffer) - sizeof(char);

        print(DEBUG, Helpers::IntegerToString(bytesLeft));

        if(bytesLeft < 0)

        {

            reading = 1;

        }

        while(bytesLeft > 0)

        {

            ssize_t curr;

            curr = recv(fd, iterator, bytesLeft, 0);

            if(curr == -1)

            {

                if(errno != EAGAIN)

                {

                    reading = 1;

                    print(WARNING, "reading error at content packet");

                }

                break;

            } else if(curr == 0) {

                reading = 1;

                break;

            }

            iterator += curr;

            bytesLeft -= curr;

        }

            memcpy(buffer, cpBuffer, sizeof cpBuffer);

    }

    if(reading)

    {

        print(NOTICE, "Closed connection with the descriptor " + Helpers::IntegerToString(fd));

        close(fd);

    }

}

Here is the function for epoll
void EventHandler::RunningLoop(int fd)

{

    while(1)

    {

        int availableEvents, i;

        availableEvents = epoll_wait(this->efd, this->events, MAXEVENTS, -1);

        for(i = 0; i < availableEvents; i++)

        {

            if(this->events[i].data.fd == fd)

            {

                // Accepting new connection

                this->AcceptClient(fd);

                continue;

            }

            else if((this->events[i].events & EPOLLERR) || (this->events[i].events & EPOLLHUP) || (!(this->events[i].events & EPOLLIN)))

            {

                print(WARNING, "epoll error on reading from fd");

                close (this->events[i].data.fd);

                continue;

            }

            else if(this->events[i].events & EPOLLRDHUP)

            {

                print(WARNING, "intern close socket");

                close (this->events[i].data.fd);

            } else {

                // Reading packets

                this->run->InitializePacket(this->events[i].data.fd); // cals the read function

            }

        }

    }

    free(this->events);

    close(fd);

}

My packets:
struct HeaderPacket

{

    uint16_t opcode;

    uint32_t length;

};

struct HelloWorldPacket

{

    uint16_t byteOrder;

    char content[CHARSIZE];

};

Function for serialization:
void PacketHandler::SerializeHeaderPacket(HeaderPacket packet, char buffer[])

{

    uint16_t u16;

    uint32_t u32;

    u16 = htons(packet.opcode);

    memcpy(buffer+0, &u16, 2);

    u32 = htonl(packet.length);

    memcpy(buffer+2, &u32, 4);

}

void PacketHandler::UnserializeHeaderPacket(char buffer[], HeaderPacket &packet)

{

    uint16_t u16;

    uint32_t u32;

    memcpy(&u16, buffer+0, 2);

    packet.opcode = ntohs(u16);

    memcpy(&u32, buffer+2, 4);

    packet.length = ntohl(u32);

}

void PacketHandler::SerializeHelloWorldPacket(HelloWorldPacket packet, char buffer[])

{

    uint16_t u16;

    u16 = htons(packet.byteOrder);

    memcpy(buffer+0, &u16, 2);

    memcpy(buffer+2, &packet.content, sizeof packet.content);

}

void PacketHandler::UnserializeHelloWorldPacket(char buffer[], HelloWorldPacket &packet)

{

    uint16_t u16;

    memcpy(&u16, buffer+0, 2);

    packet.byteOrder = ntohs(u16);

    strcpy(packet.content, buffer+2);

}

And this is how I send data to server:
int EventHandler::SendHelloWorld(int fd)

{

    HeaderPacket hp;

    HelloWorldPacket hc;

    char buffer[256];

    int sendResult;

    char message[] = "hello_first_message\r\n";

    hp.opcode = HELLOWORLD;

    hp.length = sizeof message;

    memcpy(hc.content, message, sizeof message);

    packets->SerializeHeaderPacket(hp, buffer);

    packets->SerializeHelloWorldPacket(hc, buffer+6);

    sendResult = write(fd, buffer, sizeof buffer);

    return sendResult;

}

Thanks for your help.

A: I have found the problem.
When I write to the server I was using sizeof buffer and buffer is 256 length and I don't read 256 bytes.
Thanks for your help.


text:
Q: IIS FTP: Should i create sites or folders? I need to create a service to host several ip cameras, in the beginning 500+.
The ip cameras send the files over ftp, so, to identify each camera, the files must go to separated folders.
Now the question, does IIS have any issue creating several FTP Sites or should i create just one and put all the users inside and separate files by folders?
I think that isolated FTP Sites are better, my worry is about performance, the server isnt so fast.
Thanks!

A: Physically, you have 1 site.
You have 500 IP cameras, so let's say you have 500 accounts.
If you need to reconfigure the site for every camera, you can easily do so.
If you need to change the DNS for your FTP site, you can easily do so.
With 500 sites, you will need either 500 unique binding IP addresses, or 500 unique domain names... otherwise your server will not know where to direct the traffic.
If you need to change the FTP settings for every camera, you will need to change it... 500 times.
If your IP address changes and you need to change your DNS, you will need to do it... 500 times.
For your own sanity, don't make 500 FTP sites.
If anything, you could make 1-10 FTP sites.
Let's say...
ftp.indoor.ipcamera.com  - 100 camera accounts
ftp.outdoor.ipcamera.com  - 200 camera accounts
ftp.corridoor.ipcamera.com  - 50 camera accounts
ftp.vantage.ipcamera.com  - 15 camera accounts
ftp.bottleneck.ipcamera.com - 25 camera accounts
and you could group your cameras in different categories to make management easier.
It's all about making it easier for YOU.


text:
Q: With https how can I conditionalize against the status code of undefined? Trying to test a HTTP status code in a module but my first response is always undefined:
foo.js
const pass = require('./bar')
const test = pass('https://www.google.com/') // URL for testing will be API URL

console.log(`The return is: ${test}`)

bar.js
attempt 1:
module.exports = (url) => {
  https
    .get(url, (res) => {
      console.log(res.statusCode)
      if (typeof res.statusCode !== 'undefined' && res.statusCode.toString()[0] === '2') {
       console.log(`Results: ${res.statusCode}`)
       return true
      }
      function waiting(status) {
        if (typeof status !== 'undefined') {
          console.log('run timeout')
          setTimeout(waiting, 250)
        } else {
          console.log(`Results: ${status}`)
          return true
        }
      }
    })
    .on('error', (e) => {
      console.error(`Error ${e}`)
      return false
    })
}

attempt 2:
module.exports = (url) => {
  https
    .get(url, (res) => {
      console.log(res.statusCode)
      function waiting(status) {
        if (typeof status !== 'undefined') {
          console.log('run timeout')
          setTimeout(waiting, 250)
        } else {
          console.log(`Results: ${status}`)
          return true
        }
      }
    })
    .on('error', (e) => {
      console.error(`Error ${e}`)
      return false
    })
}

other attempts to detect undefined:
if (typeof res.statusCode === 'number' && res.statusCode !== undefined && res.statusCode !== null) {

if (!res.statusCode) {

if (typeof res.statusCode !== 'undefined') {
  console.log(`Results: ${res.statusCode}`)
  if (res.statusCode.toString()[0] === '2') return true
  return false
}

Research:

*

*http get NodeJS how to get error status code?

*JavaScript checking for null vs. undefined and difference between == and ===

*http statusCode sometimes undefined
What am I doing wrong? In my module how can I check the status code after the undefined so I can return a true or false from the actual numerical value?

A: In both your attempts, your exported function in bar.js is not returning anything. Since you are calling an async function (https.get), you will need your exported function to be async as well. You can convert your function use promises and use async/await on the calling side. E.g.
foo.js
const pass = require('./bar');

(async function() {
    const test = await pass('https://www.google.com/'); // URL for testing will be API URL

    console.log(`The return is: ${test}`);
})();

Note the IFEE to get an async scope, as per: using await on global scope without async keyword
bar.js
const https = require('https');

module.exports = (url) => {
    return new Promise((resolve, reject) => {
        https
        .get(url, (res) => {
            console.log(res.statusCode)
            if (typeof res.statusCode !== 'undefined' && res.statusCode.toString()[0] === '2') {
                console.log(`Results: ${res.statusCode}`)
                resolve(true)
            } else {
                resolve(false)
            }
        })
        .on('error', (e) => {
            console.error(`Error ${e}`)
            resolve(false)
        })
    });
}

Alternatively, you can use a callback as follows:
foo.js
const pass = require('./bar');

pass('https://www.google.com/', test => {
    console.log(`The return is: ${test}`);
});

bar.js
const https = require('https');

module.exports = (url, callback) => {
    https
    .get(url, (res) => {
        console.log(res.statusCode)
        if (typeof res.statusCode !== 'undefined' && res.statusCode.toString()[0] === '2') {
            console.log(`Results: ${res.statusCode}`)
            callback(true)
        } else {
            callback(false)
        }
    })
    .on('error', (e) => {
        console.error(`Error ${e}`)
        callback(false)
    })
}


text:
Q: Casting exceptions when rethrowing in Java Compare these two methods:
void foo() throws SomeSuperException {
    try {
        //...
    } catch (SomeSuperException e) {
        if (e instanceof SomeSubException) {
            throw e;
        }
    }
}

void bar() throws SomeSubException {
    try {
        //...
    } catch (SomeSuperException e) {
        if (e instanceof SomeSubException) {
            throw (SomeSubException) e;
        }
    }
}

Aside from the method signatures (bar can declare throws SomeSubException instead of throws SomeSuperException), is there any practical difference between the two methods?
To be clear: I'm aware that this is a horrible approach to exception handling, and should not be done!

A: The difference is that in the first case, externally the caller doesn't know about your specific SomeSubException, so some detail is lost in translation.

A: No there's no (big) difference.
From the ordinary it's the best choice to throw the most specific exception,
no the super or broader one. This allows you to handle more cases in the overlaying catchBlock.


text:
Q: Using iText, how to give Path to store PDF file from Device or Emulator? I am developing Invoice App, so i am using iText to create PDF file, like invoice. I want to store PDF file in sd card OR in the Computer itself. But it is not working because, Path is not get accesseble by the App.
But when i tried the same code in Java Application , then file is created sucessfully.Path is given in the computer LocalDisk.
I want to give the Path of file to be stored,

*

*In the SD Card of real Device.

*In the Computer LocalDisk (in case App works on Emulater).

How to do ? any help is appreciated.

A:
In the SD Card of real Device.

If by "the SD Card", you mean what the Android SDK refers to as external storage, you have a number of options for getting a path to a spot to write your file. Off the cuff, I would recommend getExternalStoragePublicDirectory() on the Environment class.
If by "the SD Card", you mean removable storage, that is not supported by the Android SDK before Android 4.4.

In the Computer LocalDisk (in case App works on Emulater).

That is not supported. The emulator has no ability to write into the filesystem of the development PC. The emalator can have its own emulated external storage, though.


text:
Q: How to cancel a pending publication on Google Play Developer Console? Is there a way to cancel a pending publication on Google Play Developer Console? I have accidentally sent a wrong apk file and couldn't find a way to cancel it.

A: Here is a solution but it could't be posssible for me because I couldn't change my app's bundle ID.
It says that:

in Advanced Mode, you can cancel and upload again a new APK.

A: I'm too late, but it helps someone.
If the app is under review, upload the original or new APK. Google will automatically publish the latest version. Make sure that the new APK has higher Version Code.
If you don't want to upload a new APK file, you can control when updates are published.
Log in to your Play Console account and click on the "Publishing overview" item on the left pane. Next, click on the manage button.

Select the first option.

Google doesn't publish your app immediately.


text:
Q: how to find untranslated Strings in Android Studio 2 How to find untranslated i18n strings (string.xml) in a new Android Studio 2.0?
I'm looking for something like Refactor > Remove Unused Resources...

A: There sure is.
You can access the Translations Editor by opening a strings.xml file for editing and clicking the Open editor link, or clicking the globe icon    in the Design layout view and choosing Edit Translations.

If you open the editor, you will have highlighted in red all the keys for the strings that are not translated to all the languages present in your project.

In all honesty, I had no idea this even existed, so I'm happy I had better luck finding it than you did, hope it's what you're after.


text:
Q: How can I make ES6 imports work in node 12?
Edit: This is not a duplicate of NodeJS plans to support import/export es6 (es2015) modules. That question is asking about node's plans. This is a specific technical error now those plans have been implemented. Please read questions before you mark them as duplicate.

Node 12 supports ES modules using the --experimental-modules flag. However when I try to use the import * syntax it fails:
> import * as record from 'src/frontend/rrweb.js'                                                               Thrown:
import * as record from 'src/frontend/rrweb.js'
       ^

SyntaxError: Unexpected token *

Likewise:
import {record} from 'src/frontend/rrweb.js'

Fails with the error SyntaxError: Unexpected token {
Is this a bug or am I doing something wrong? How can I import an ES6 module?
Updates
Loading an .mjs does not work:
$ node --experimental-modules .\deleteme.js                                                  (node:18292) ExperimentalWarning: The ESM module loader is experimental.                                    C:\Users\mikem\Code\appless\deleteme.js:1
import {record} from 'src/frontend/rrweb.mjs'
       ^

SyntaxError: Unexpected token {


text:
Q: Odd object behaviour I'm writing a small website for a newspaper and I'm trying to make the home page to show the latest news and a photo for each. I use Firebase Realtime Database and Firestorage to store the news and the photos. When getting the data and showing it I save all the data first in an object array and then displaying it (so it remains in order).
The problem is that when I'm calling the function to display it the links to the photos don't appear.
I tried outputting the array with console.log(arrayName) and everything looks like it should. But when I try console.log(arrayName[1].sos) it shows nothing.
db.collection("articole").orderBy("data", "asc").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        articolTmp = {
          titlu: doc.data().titlu,
          subtitlu: doc.data().subtitlu,
          id: doc.id,
          poza: doc.data().poza,
          data: doc.data().data,
          sos: ""
        };
        articole.push(articolTmp);
    });
    show();
});

function show(){
  for(let i = 1; i < articole.length; ++i){
    var pathReference = storage.ref('pozeArticole/' + articole[i].poza);
    pathReference.getDownloadURL().then(function(url){
       articole[i].sos = url;
    });
}
  showw();
}

function showw(){
  // this is the console.log I was talking about
  console.log(articole);
  for(let i = 1; i < articole.length; ++i){
    console.log(articole[i].sos);
    var div = document.createElement("div");
    var titlu = document.createElement("h3");
    var subtitlu = document.createElement("p");
    var link = document.createElement("a");
    var poza = document.createElement("img");
    poza.src = articole[i].sos;
    poza.alt = "alt";
    link.href = "viz.html?id=" + articole[i].id;
    titlu.innerHTML = articole[i].titlu;
    subtitlu.innerHTML = articole[i].subtitlu;
    document.getElementById("main").appendChild(div);
    link.appendChild(titlu);
    div.appendChild(link);
    div.appendChild(subtitlu);
    div.appendChild(poza);
  }

A: Your problem is in the show function. The last line of code which calls showw is executed before the line "above it" which is articole[i].sos = url;. Why is that? Because you are using an asynchronous operation. The code that gets the download url is executed in a different thread. Whenever that code finished, the block you provided (articole[i].sos = url;) will get executed. I recommend reading about asynchronous operations and promises.
So, to solve your problem, you have ti move the showw call inside the block above it. The block should be:
pathReference.getDownloadURL().then(function(url){
   articole[i].sos = url;
   showw();
});`


text:
Q: Preload image from URL for KenBurnsView Xamarin.Android I am using https://components.xamarin.com/view/KenBurnsView
I have several image URL-s by which I want to show them via KenBurnsView
after setting src of KenBurnsView to the first imageURL, at the TransitionEnd I want to replace src with new image URL and restart animation, but I want the image to be preloaded to make everything smooth.
I would preload next image at the TransitionStart event so at the end image could be loaded, but I dont know how to do it.
Image caching is what I mean maybe but I dont know how to cache it very first time

A: For image caching you can do it yourself, saving the image in the FileSystem when downloaded from internet and next time you need to load the image you check if it's already local and if it's not you just hit the web and save it. There's of course a little more to do like deleting the images in file system after certain period but just wanted to give you the main idea.
For my projects I use this library FFImageLoading. It's well maintained and its use is so simple.
ImageService.Instance.LoadUrl(urlToImage).Into(_imageView);

When the image is loaded from internet the image is cached on disk (by default 30 days but there is an optional TimeSpan so you can choose yours).

Android documentation.


text:
Q: Ruby mixins -- getting & setting base class' class variables What's the best way of setting class variables in a base class? Consider the following code snippet, which is defining a CacheMixin to be used with ActiveRecord models. For each model, I want to be able to define the table which is storing the cached data. Is there a better way to do this without using class_variable_set and class_variable_get ?
require 'rubygems'
require 'active_support/concern'

module CacheMixin
    extend ActiveSupport::Concern

    module ClassMethods
        def with_cache_table(table)
            self.class_variable_set('@@cache_table', table)
        end
    end

    def fetch_data
        puts self.class.class_variable_get('@@cache_table')
    end

end

class TestClass
    include CacheMixin
    with_cache_table("my_cache_table")
end

A: Since you are using Rails, I'd recommend checking out the class_attribute method.
If you want to do it without Rails, I'd suggest setting an instance variable directly on the class object rather than using class variables (which are generally considered to be bad news).
class Foo
  class << self
    attr_accessor :bar
  end
end

Foo.bar = 'hi'
p Foo.bar
#=> 'hi'


text:
Q: test re compile compiled "on the fly" gives an empty match, not None I'm trying to test a bunch of regex cases (specifically if something is a unit of measurement: 5px, 300mm etc).
All the questions i can find about re.match tell me that i test this as follows:
import re

test_phrase_good = "5kw"
test_phrase_bad = "5XXX"
registered_units_regex = re.compile('[0-9]+kw|[0-9]+mm', re.IGNORECASE)

# test in the following way:
registered_units_regex.match(token) is not None

# so:
print(registered_units_regex.match(test_phrase_good)) # <re.Match object; span=(0, 3), match='5kw'>
print(registered_units_regex.match(test_phrase_bad)) #  None

As expected.
However, if i want to compile a regex in a loop, i get the following:
regex_units = [r"mm", r"kw"]
regex_string = r""
for unit in regex_units:
    regex_string += r'[0-9]+{}|'.format(unit)

regex_string = regex_string.rstrip('|')

registered_units_regex = re.compile(regex_string, re.IGNORECASE)
registered_units_regex.match(test_phrase_good) is not None

# so:
print(registered_units_regex.match(test_phrase_good)) # <re.Match object; span=(0, 3), match='5kw'>
print(registered_units_regex.match(test_phrase_bad)) #  <re.Match object; span=(0, 0), match=''>

which means i can no longer use is None as a test.
Why is this?  and how should I properly test for no match?

A: The | at the end of the regexp means that it matches an empty string. You should only put | between the alternatives, not before or after them. You can use join to do that.
You also have [0-9]+ in both regex_units and the format string, you don't need it in both places.
regex_units = ["mm","kw"]
regex_string = "|".join(r'[0-9]+{}|'.format(unit) for unit in regex_units)


text:
Q: UITableView with floating cells I am working on a specific type of list for an iOS app, where cells would simply have a specific width and height and then float left (think of something like CSS float:left), creating then a list that would scroll if more than 12 items (like the picture bellow).

I was thinking that perhaps this could be done by customizing UITableViewCell and setting the frame's width and height, so I could re-use the various benefits UITableViewController, delegate and dataSource offer. but unfortunately it seems that's not possible.
So, I'm now simply creating many UIViews and positioning them across its parent programatically.
I just would like to make sure this would be the right approach to achieve such kind of lists and if someone could let me know if it's indeed not possible to have this kind of functionality on UITableView and inherit all the goodness it offers.
Thanks guys

A: I know this question is already answered, but still...
I believe you can simply use UICollectionView since iOS 6.0.
Documentation
And this is how it looks like (image)
Maybe this will help somebody.

A: UITableView can only have cells that go in one direction. It's perfectly okay to create many UIViews (table view cells are also UIViews), if the number of them is reasonable. You can usually have a few hundred UIViews in a scrollview without seeing any performance issues, but that also depends on the complexity of what's inside the uiviews. Try it for yourself and if you find out, that you need too many uiviews, or that their complexity it too high, you can optimize further. You can set the .layer.shouldRasterize property to "cache" the content of the views. Or you can use CATiledLayer, which is something like a UITableView, but it supports tiles in all direction (and scrolling, zooming, ...).

A: Take a look at this project, I think may be helpful to for your problem
link


text:
Q: I want to create array of objects MyClass ob[20]; Error: statically allocated instance of Objective-C class I want to create array of objects MyClass ob[20]; Error: statically allocated instance of Objective-C class 'MyClass'
@interface MyClass : NSObject

A: You need to create an array of object pointers.
MyClass *ob[20];

Alternatively, use a high-level collection like NSArray.


text:
Q: Error when I try to compile the kernel 2.6.37 I have downloaded the kernel 2.6.37 from kernel.org.
I have tried to compile it but I get an error:
$ make menuconfig
scripts/kconfig/conf --silentoldconfig Kconfig
***
*** Configuration file ".config" not found!
***
*** Please run some configurator (e.g. "make oldconfig" or
*** "make menuconfig" or "make xconfig").
***
make[2]: *** [silentoldconfig] Error 1
make[1]: *** [silentoldconfig] Error 2
make: *** No rule to make target `include/config/auto.conf', needed by `include/config/kernel.release'. Stop.

I have copied the actual kernel configuration to .config:
cp /boot/config-2.6.37-20110117 .config

I have executed make menuconfig another time but it compiles the full kernel without showing a menu. o_O
I have compiled this kernel a few days without problems.
Any help?
Thanks.

A: I do this on a fairly regular basis. It's quite simple. I follow the "Old fashioned way" instructions. If you're not, read that from the beginning and make sure you have the right things installed. My steps are as follows:

*

*Download kernel, extract it, and cd into the resultant directory.

*Copy in the config from the running kernel:
cp -vi /boot/config-`uname -r` .config

*Show the new config keys and set values (optional):
make oldconfig

*Main config (if I need to change things, optional again):
make menuconfig

*Compile and package:
env CONCURRENCY_LEVEL=8 fakeroot make-kpkg --initrd kernel-image kernel-headers

A: The error was an alias of make that I have defined in my .bashrc.