text:
Q: Can Console.Clear be used to only clear a line instead of whole console? While working on a question/answer program for school, it occurred to me that I can use Console.Clear() to wipe out everything on the screen. I wonder if I can use Console.Readline(valueOne), then output only the answer without the question. If I only asked one question, the Console.Clear works.
I have several questions with values not references, to erase if possible. I want to leave out the questions and only display several answers. I think if I store the answers, I could use Console.Clear() then just Console.WriteLine() with three variables. I could do something like this:
Console.WriteLine("Value 1 is: {0:c}" + "Value 2 is: {1:c}" + "Value 3 is: {2:c}, valueOne, valueTwo, valueThree).

The problem is easier with references because the values are stored and retrieved. If I simply use methods to pass by value and output the value, main() will not have a reference to those values to clear and output again. That's why I wonder if I can just ask a question, then erase the line and output only the answer (or answers).
I am just trying to understand the possibilities and not trying to setup a program. I like to know the abilities of outputting a value from reference and by value without extra output questions.

A: My preferred method is to use PadRight. Instead of clearing the line first, this clears the remainder of the line after the new text is displayed, saving a step:
Console.CursorTop = 0;
Console.CursorLeft = 0;
Console.Write("Whatever...".PadRight(Console.BufferWidth));

A: A simpler and imho better solution is:
Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");

It uses the carriage return to go to the beginning of the line, then prints as many spaces as the console is width and returns to the beginning of the line again, so you can print your own test afterwards.

A: We could simply write the following method
public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

and then call it when needed like this
Console.WriteLine("Test");
ClearLine();

It works fine for me.

A: "ClearCurrentConsoleLine", "ClearLine" and the rest of the above functions should use Console.BufferWidth instead of Console.WindowWidth (you can see why when you try to make the window smaller). The window size of the console currently depends of its buffer and cannot be wider than it.
Example (thanks goes to Dan Cornilescu):
public static void ClearLastLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.BufferWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

A: Description
You can use the Console.SetCursorPosition function to go to a specific line number. Then you can use this function to clear the line:
public static void ClearCurrentConsoleLine()
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, currentLineCursor);
}

Sample
Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

*

*Console.SetCursorPosition Method

A: This worked for me:
static void ClearLine(){
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

A: To clear from the current position to the end of the current line, do this:
    public static void ClearToEndOfCurrentLine()
    {
        int currentLeft = Console.CursorLeft;
        int currentTop = Console.CursorTop;
        Console.Write(new String(' ', Console.WindowWidth - currentLeft));
        Console.SetCursorPosition(currentLeft, currentTop);
    }

A: public static void ClearLine(int lines = 1)
{
    for (int i = 1; i <= lines; i++)
    {
        Console.SetCursorPosition(0, Console.CursorTop - 1);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, Console.CursorTop - 1);
    }
}

A: I think I found why there are a few varying answers for this question. When the window has been resized such that it has a horizontal scroll bar (because the buffer is larger than the window) Console.CursorTop seems to return the wrong line. The following code works for me, regardless of window size or cursor position.
public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}

Without the (Console.WindowWidth >= Console.BufferWidth ? 1 : 0), the code may either move the cursor up or down, depending on which version you use from this page, and the state of the window.

A: This works perfect for me as i expected -
    public static void ClearLine()
    {
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, Console.CursorTop);
    }


text:
Q: 100V "rated" wire on 220V supply I am genuinely sorry for posting such a basic, basic, basic question.
Moving to Thailand (220V) from Japan (100V). You cannot buy an extension cord in Thailand that is flush to the wall. Here in Japan, there are lots of angled extension cords from reputable companies that are flush. Most of these Japanese cords are rated at "1500W". If the only purpose is to connect a single 45W computer power adapter and nothing else, is it safe to use a "100V" Japanese extension cord without an intermediate step down transformer?
I have a basic understanding of electrical theory, which means I am fully qualified to burn my apartment building down to the ground. But I feel my neighbours would appreciate an informed opinion.

A: TL;DR
The Japanese cable will work, but you may not want to use it.
Why?
As the 110v extension lead is designed to be plugged into 'mains', which experiences 1500v spikes whether on a 100v or 220v system, its insulation will be rated for at least those spikes. So 220v will be no problem.
However, after the fire (caused by some other random electrical thing overheating, or a cooking accident, or your 2 year old playing with matches) the insurance assessors will pick through the debris looking for reasons not to pay your claim. If they find a 100v rated extension lead plugged into a 220v system, even if it obviously didn't cause the fire, they might just make life difficult for you, just when you don't need it to be.
But check the rating. It's possible that extension leads available in Japan might be rated for 220v, even if Japan uses a 100v system, so that it's saleable in neighbouring territories. If it says 220v on it, then there's not even the insurance problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Send button error message escaped I'm integrating Send button in a site and faced with an issue that error message saying that to be able send to e-mail requires a public e-mail address is escaped. So that user can't click the link to setup @facebook address.
Here is error message screenshot

Is it possible to address it somehow or better report to developers?

A: You need to claim your facebook email account. Click the following link after you've logged into your FB account.
http://www.facebook.com/messages/?setup

A: Appears to be bug: https://developers.facebook.com/bugs/302953569717849


text:
Q: How to call a function when a property is used? When I change a property in a JavaScript "class" I want to log to the console when the old deprecated property is used.
eg.
var app = function() {
    this.oldvar = function() { console.log('oldvar is old!'); return myapp.newvar; };
    this.newvar = 'Hello world!';
}

var myapp = new app();

alert(myapp.oldvar);

My example will not work because the string representation of oldvar will be outputted and the function won't actually be called.
I want the alert() to think it's using the old property but "extra" code will be run in the function.
I do not want to call oldvar as a function. I want my code to try and alert() it as a string.
Is this possible?

A: You can define a getter for your app like this:
var app = function () {
    this.newvar = 'Hello world!';
};

app.prototype = {
    get oldvar() {
        console.log('oldvar is old!');
        return this.newvar;
    }
};

var myapp = new app();

alert(myapp.oldvar);

I've tested this in Node.js v0.10.32 and JSFiddle in the latest Chrome and it seems to work for me. However, this is a relatively recent feature in ECMA Script, so older browsers won't support it. I refer you to the Mozilla Developer Network Docs for the compatibility table.
The above method involves redefining the prototype of your app. This is probably fine if app is entirely your own function. However, if you're using an existing function and don't want to override everything there already, you can use this alternative syntax:
var app = function () {
    this.newvar = 'Hello world!';
};

Object.defineProperty(app.prototype, 'oldvar', {
    get: function () {
        console.log('oldvar is old!');
        return this.newvar;
    }
});

var myapp = new app();

alert(myapp.oldvar);

Using this syntax, you can add new getters without having to re-define all your old ones. If you then want to delete it, you can use the standard delete function in JavaScript, i.e. delete app.prototype.oldvar;.

A: The suggested solutions will not work, because oldvar needs to be treated as a property, not as a function.
Try using getters, defined in ECMAScript 5 (so only newer browsers will support it, i.e. nothing before IE9)
Example:
var app = {
    newvar: 'Hello world!'
};

Object.defineProperty(app, 'oldvar', {
    get: function() {
        console.log('oldvar is old!');
        return this.newvar;
    }
});

You can read more about them here: http://javascriptplayground.com/blog/2013/12/es5-getters-setters/

A: You just need to call the oldVar property as a function:
Use alert(myapp.oldvar());


text:
Q: What do you call a number formed by a sequence of repeating digits For example, I have a sequence
77777777777

Is there a word in the dictionary to represent

a sequence of repetitive/recurring digits

A: This type of number is commonly called a repdigit number, or sometimes a monodigit number.  This term is used most frequently in recreational mathematics and is most often seen in investigations into prime numbers.
See wikipedia article on repdigit for details.

A: It's called a periodic sequence. See wikipedia.

A: The given example is not a sequence per se, considering that the "digits" are not separated (by a comma, space).
A natural number whose digits are repeating in some  positional number system is called, in recreational mathematics, a repdigit. This comes from repeated and digit. In the case it is composed of digit 1 (1, 11, 111, 11111), it is called a repunit. The latter was  coined  by A. H. Beiler in  1966. See Repunit and Repdigit Numbers for other details.
Otherwise, this would just be a constant sequence:

Constant sequences are sequences for which all terms are the same.

A: Repeating would be the usual term, as in a repeating decimal, but that could also mean a sequence such as "123123123123."  If you don't mind a coinage, how about monodigital sequence?

A: • thefreedictionary.com defines repetend as "Mathematics The digit or group of digits that repeats infinitely in a repeating decimal".
• collinsdictionary.com defines repetend as "(mathematics) the digit or series of digits in a recurring decimal that repeats itself".
• Wiktionary defines repetend as "(mathematics) A repeating decimal", which while closer to what you've asked about – ie the sequence of repeated numbers rather than the digits that repeat – is probably an incorrect definition.

A: The closest single word would be repetend, which generally means anything that is repeated (e.g. it would also be used about music and poetry).
Unfortunately, the one thing we cannot use it for is repeating numbers, because it has a specific sense when it comes to numbers where it only refers to the repeated numbers found in representing a fraction that cannot be fully represented in the base used (e.g. ⅓ in decimal ends with a repetend of 3, 1/7 in decimal has a repetend of 142857, ⅓ in binary ends with a repetend of 01, 1/10 in binary ends with a repetend of 0011, and so on).
So, while in that one case it is the perfect word to use, in any others it is a particularly bad word to use, because it will make people think of that more specific use.
In other cases I would just use "recurring sequence" or "repeated sequence".

A: A series or set, maybe.
Finding an exact term for this kind of repeated number is quite hard, for it will depend on where you are currently using it


text:
Q: Block the navigation indicated by an onBeforeNavigate event in a Chrome extension, but not non-navigation requests I want to restrict the browser to within a set of URLs. I'm using:
chrome.webNavigation.onBeforeNavigate.addListener(functon(details){
    if (notAllowed(details.url)) {
         // Do something to stop navigation
    }
});

I know that I can cancel chrome.webRequest.onBeforeRequest.  But, I don't want to block requests, like XHR or any other. I want this filter to be applied only for navigation.
For the user, it should looks like, the link (e.g. foo) click event was stopped.

A: The following extension adds a listener to webNavigation.onCompleted which is used to remember, indexed by tabId, both the most recent URL in frameId==0 for which the event is fired, and the prior URL.
A listener is added to webNavigation.onBeforeNavigate which watches for matching URLs, in this case, stackexchange.com. If the URL matches, the tab URL is updated, via tabs.update, to navigate back to the last URL for which a webNavigation.onCompleted event was fired.
If the onBeforeNavigate event is for a frameId other than 0, then the tab is navigated to the previous URL for which a onCompleted event was fired for frameId==0. If the prior URL was not used, then we could get into a loop where the current URL is repeatedly re-loaded due to the URL in one of its frames matching the URL we are blocking. A better way to handle this would be to inject a content script to change the src attribute for the frame. We would then need to handle frames within frames.
blockNavigation.js:
//Remember tab URLs
var tabsInfo = {};
function completedLoadingUrlInTab(details) {
    //console.log('details:',details);
    //We have completed loading a URL.
    createTabRecordIfNeeded(details.tabId);
    if(details.frameId !== 0){
        //Only record inforamtion for the main frame
        return;
    }
    //Remember the newUrl so we can check against it the next time
    //  an event is fired.
    tabsInfo[details.tabId].priorCompleteUrl = tabsInfo[details.tabId].completeUrl;
    tabsInfo[details.tabId].completeUrl = details.url;
}

function InfoForTab(_url,_priorUrl) {
    this.completeUrl = (typeof _url !== 'string') ? "" : _url;
    this.priorCompleteUrl = (typeof _priorUrl !== 'string') ? "" : _priorUrl;
}

function createTabRecordIfNeeded(tabId) {
    if(!tabsInfo.hasOwnProperty(tabId) || typeof tabsInfo[tabId] !== 'object') {
        //This is the first time we have encountered this tab.
        //Create an object to hold the collected info for the tab.
        tabsInfo[tabId] = new InfoForTab();
    }
}

//Block URLs
function blockUrlIfMatch(details){
    createTabRecordIfNeeded(details.tabId);
    if(/^[^:/]+:\/\/[^/]*stackexchange\.[^/.]+\//.test(details.url)){
        //Block this URL by navigating to the already current URL
        console.log('Blocking URL:',details.url);
        console.log('Returning to URL:',tabsInfo[details.tabId].completeUrl);
        if(details.frameId !==0){
            //This navigation is in a subframe. We currently handle that  by
            //  navigating to the page prior to the current one.
            //  Probably should handle this by changing the src of the frame.
            //  This would require injecting a content script to change the src.
            //  Would also need to handle frames within frames.
            //Must navigate to priorCmpleteUrl as we can not load the current one.
            tabsInfo[details.tabId].completeUrl = tabsInfo[details.tabId].priorCompleteUrl;
        }
        var urlToUse = tabsInfo[details.tabId].completeUrl;
        urlToUse = (typeof urlToUse === 'string') ? urlToUse : '';
        chrome.tabs.update(details.tabId,{url: urlToUse},function(tab){
            if(chrome.runtime.lastError){
                if(chrome.runtime.lastError.message.indexOf('No tab with id:') > -1){
                    //Chrome is probably loading a page in a tab which it is expecting to
                    //  swap out with a current tab.  Need to decide how to handle this
                    //  case.
                    //For now just output the error message
                    console.log('Error:',chrome.runtime.lastError.message)
                } else {
                    console.log('Error:',chrome.runtime.lastError.message)
                }
            }
        });
        //Notify the user URL was blocked.
        notifyOfBlockedUrl(details.url);
    }
}

function notifyOfBlockedUrl(url){
    //This will fail if you have not provided an icon.
    chrome.notifications.create({
        type: 'basic',
        iconUrl: 'blockedUrl.png',
        title:'Blocked URL',
        message:url
    });
}

//Startup
chrome.webNavigation.onCompleted.addListener(completedLoadingUrlInTab);
chrome.webNavigation.onBeforeNavigate.addListener(blockUrlIfMatch);

//Get the URLs for all current tabs when add-on is loaded.
//Block any currently matching URLs.  Does not check for URLs in frames.
chrome.tabs.query({},tabs => {
    tabs.forEach(tab => {
        createTabRecordIfNeeded(tab.id);
        tabsInfo[tab.id].completeUrl = tab.url;
        blockUrlIfMatch({
            tabId : tab.id,
            frameId : 1, //use 1. This will result in going to '' at this time.
            url : tab.url
        });

    });
});

manifest.json:
{
    "description": "Watch webNavigation events and block matching URLs",
    "manifest_version": 2,
    "name": "webNavigation based block navigation to matched URLs",
    "version": "0.1",
    "permissions": [
        "notifications",
        "webNavigation",
        "tabs"
    ],
    "background": {
        "scripts": ["blockNavigation.js"]
    }
}

A: It is possible to prevent navigation altogether. Use redirectURL and set a link which generates 204 (no content) response.
chrome.webRequest.onBeforeRequest.addListener(

  function(details) {

    //just don't navigate at all if the requested url is example.com
    if (details.url.indexOf("://example.com/") != -1) {

      return {redirectUrl: 'http://google.com/gen_204'};

    } else {

      return { cancel: false };

    }

  },
    { urls: ["<all_urls>"] },
    ["blocking"]
  );

A: webRequest.onBeforeRequest has a field .type which can be used to determine why the request was made. For only requests which are loading a page, check details.type === "main_frame" and to include requests which are navigating inside an iframe, also check details.type === "sub_frame".
browser.webRequest.onBeforeRequest.addListener(
    (details) => {
        if (details.type !== "main_frame" || details.method !== "GET") {
            return;
        }
    },
    { urls: ["<all_urls>"] },
    ["blocking"],
);

        permissions: [
            "webRequest",
            "webRequestBlocking",
            "http://*/",
            "https://*/",
        ],


text:
Q: Android NDK & FFMPEG : findLibrary returned null I am using this  to build ffmpeg on ndk:
 roman10's android ndk r9d - ffmpeg tutorial
The link shows how to compile, but its not clear how to use it. Can anybody guide me? Thanks.
After ndk-build from my project root i was able to generate .so files inside libs/armeabi and obj/local/armeabi.. Now I am getting findLibrary returned null?? What to do now?
java.lang.UnsatisfiedLinkError: Couldn't load libavutil from loader dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.palak.androidffmpegroman-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.palak.androidffmpegroman-2, /vendor/lib, /system/lib]]]: findLibrary returned null

        at java.lang.Runtime.loadLibrary(Runtime.java:358)
        at java.lang.System.loadLibrary(System.java:526)
        at com.palak.androidffmpegroman.MainActivity.<clinit>(MainActivity.java:175)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1208)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5001)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        at dalvik.system.NativeStart.main(Native Method)

my project structure:

My build_android.sh
  #!/bin/bash
NDK=$HOME/NDK/android-ndk-r10d
SYSROOT=$NDK/platforms/android-19/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86
function build_one
{
sudo ./configure \
    --prefix=$PREFIX \
    --enable-shared \
    --disable-static \
    --disable-doc \
    --disable-ffmpeg \
    --disable-ffplay \
    --disable-ffprobe \
    --disable-ffserver \
    --disable-avdevice \
    --disable-doc \
    --disable-symver \
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
    --target-os=linux \
    --arch=arm \
    --enable-cross-compile \
    --sysroot=$SYSROOT \
    --extra-cflags="-Os -fpic $ADDI_CFLAGS" \
    --extra-ldflags="$ADDI_LDFLAGS" \
    $ADDITIONAL_CONFIGURE_FLAG
make clean
make
make install
}
CPU=arm
PREFIX=$(pwd)/android/$CPU
ADDI_CFLAGS="-marm"
build_one

I am using Ndk r10, ffmpeg 2.5.4, ubuntu x86.
Edit: Android.mk
LOCAL_PATH:= /home/palak/NDK/ffmpeg-2.5.4/android/arm

include $(CLEAR_VARS)
LOCAL_MODULE:= libavcodec
LOCAL_SRC_FILES:= lib/libavcodec-56.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavformat
LOCAL_SRC_FILES:= lib/libavformat-56.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libswscale
LOCAL_SRC_FILES:= lib/libswscale-3.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavutil
LOCAL_SRC_FILES:= lib/libavutil-54.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavfilter
LOCAL_SRC_FILES:= lib/libavfilter-5.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libswresample
LOCAL_SRC_FILES:= lib/libswresample-1.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

Android.mk under jni folder:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := tutorial01
LOCAL_SRC_FILES := tutorial01.c
LOCAL_LDLIBS := -llog -ljnigraphics -lz
LOCAL_SHARED_LIBRARIES := avformat avcodec swscale avutil

include $(BUILD_SHARED_LIBRARY)
$(call import-module,ffmpeg-2.5.4/android/arm)

A: LOCAL_MODULE:= libavutil

-->
LOCAL_MODULE:= avutil # libavutil.so

example (used to work):
https://github.com/18446744073709551615/reDroid/blob/master/jni/Android.mk
UPDATE:
Once again: you do not need the lib prefixes in library names; LOCAL_MODULE:= avutil will give you libavutil.so
At second, what parameter do you pass to loadLibrary()? Again, it should be "avutil" for  libavutil.so.
If you have problems, the best way is to start with the hello-jni example in the NDK (your-ndk-dir/samples/hello-jni/)
/* this is used to load the 'hello-jni' library on application
 * startup. The library has already been unpacked into
 * /data/data/com.example.hellojni/lib/libhello-jni.so <== !!!!!!!!!!!!!
 * at installation time by the package manager.
 */
static {
    System.loadLibrary("hello-jni");
}

Once the example compiles and runs, you may add your libraries to it and have your stuff work.

A: You use name libavutil to refer to libavutil-54.so during ndk-build. This is fine, but the runtime lib is still called libavutil-54.so. Moreover, your other modules, including tutorial01, know it by this name, so renaming it in libs/armeabi will also be wrong.
You need something like
static {
    System.loadLibrary("avutil-54");
    System.loadLibrary("avcodec-56");
    System.loadLibrary("avformat-56");
    System.loadLibrary("swscale-3");
    System.loadLibrary("tutorial01");
}

In recent version of Android, the system will automatically resolve the local external references, so it's enough to call
static {
    System.loadLibrary("tutorial01");
}

A: Replace your
LOCAL_SHARED_LIBRARIES := avformat avcodec swscale avutil

with
LOCAL_SHARED_LIBRARIES := libavformat libavcodec libswscale libavutil libavfilter libswresample

in Android.mk in your Jni folder.
And Load the libraries like below
static {

  System.loadLibrary("avutil-54");
  System.loadLibrary("avcodec-56");
  System.loadLibrary("avformat-56");
  System.loadLibrary("swscale-3");
  System.loadLibrary("avfilter-5");
  System.loadLibrary("swresample-1");
  System.loadLibrary("tutorial01");

}

A: Are you sure that you are using a phone with an armeabi processor? Add the armeabiv7 in the Application.mk file and it will compile the required files for armeabiv7 phones in the libs folder.
APP_ABI := armeabi armeabi-v7a x86

This should work.


text:
Q: Flixel error "FlxPreloader was not found." When I run my Flixel code in Flash develop it throws this error:

col: 33 Error: The definition of base class FlxPreloader was not found.

my code:
package
{
    import org.flixel.FlxPreloader;
    public class Preloader extends FlxPreloader
    {

        public function Preloader()
        {
        className = "Jumper";
        super();
        }

    }

}

A: FlxPreloader is in the package org.flixel.system.FlxPreloader.
Change your import statement to look like this:

import org.flixel.system.FlxPreloader;


text:
Q: I lost a css background image in the body tag using curl post I lost a css background image in the body tag using a curl post. It is set like this.
body {
    font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
    background-image: url(../Images/pattern4.png); // this one disappeared
    background-repeat: repeat-x;
    background-attachment: fixed;
    margin: 0;
    padding: 0;
    color: #000;
}

The Curl Post is.
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpStr);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_exec($ch);
curl_close($ch);

I was hoping that it would get solved automatically so I kept coding in another request using curl and I lost my ability to scroll the page on all pages also. The whole scroll bar on the right side of the page is gone. My code is a one class architecture and all Html is displayed using php.
Any Idea what the problem could be?
The site is www.bestspot2shop.com
I made two calls to an API that I made using curl to get info from a site and display it on my site. The first call lost me the background picture and the scrollbar on the side. Mouse over APITestPacks on the left side menu and click one the Medical, Tests link. Do you have any idea what the problem might be? I have an ssl certificate and sometimes that interferes with things.

A: The URL for the background image needs to be fully-qualified (http://) because it needs to point back to the original server.


text:
Q: Show that the set is a regular surface Consider the set $S \subset \mathbb{R}^4$, define by the equations, $x^2 + y^2 = 1$ and $ z^2 + t^2 = 1$.
a) Prove that $S$ is a regular surface.
b) Find a parameterization of $S$ around the point $p = (1, 0, 1, 0)$ and calculate the 1st
fundamental form.
(Im new with differential geometry and I do not really know how to start this exercise because is $\mathbb{R}^4$, many thanks!)

A: Consider $f:\mathbb{R}^4\rightarrow\mathbb{R}^2$ defined by $f(x,y,z,t)=(x^2+y^2,z^2+t^2)$. Show that it is a submersion in a neighborhood of $f^{-1}(1,1)$ by computing the Jacobian. This implies that $f^{-1}(1,1)$ is a submanifold.


text:
Q: write a function that generates a list of last days of each month for the past n months from current date I am trying to create a list of the last days of each month for the past n months from the current date but not including current month
I tried different approaches:
def last_n_month_end(n_months):
    """
    Returns a list of the last n month end dates
    """
    return [datetime.date.today().replace(day=1) - datetime.timedelta(days=1) - datetime.timedelta(days=30*i) for i in range(n_months)]

somehow this partly works if each every month only has 30 days and also not work in databricks pyspark. It returns AttributeError: 'method_descriptor' object has no attribute 'today'
I also tried the approach mentioned in Generate a sequence of the last days of all previous N months with a given month
def previous_month_ends(date, months):
  year, month, day = [int(x) for x in date.split('-')]
  d = datetime.date(year, month, day)
  t = datetime.timedelta(1)
  s = datetime.date(year, month, 1)
  return [(x - t).strftime('%Y-%m-%d')
          for m in range(months - 1, -1, -1)
          for x in (datetime.date(s.year, s.month - m, s.day) if s.month > m else \
                    datetime.date(s.year - 1, s.month - (m - 12), s.day),)]

but I am not getting it correctly.
I also tried:
df = spark.createDataFrame([(1,)],['id'])

days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))

I got the last three months (Sep, oct, nov), but all of them are the 30th but Oct has Oct 31st. However, it gives me the correct last days when I put more than 3.
What I am trying to get is this:
(last days of the last 4 months not including last_day of current_date)
daterange = ['2022-08-31','2022-09-30','2022-10-31','2022-11-30']

A: Not sure if this is the best or optimal way to do it, but this does it...
Requires the following package since datetime does not seem to have anyway to subtract months as far as I know without hardcoding the number of days or weeks. Not sure, so don't quote me on this....
Package Installation:
pip install python-dateutil

Edit: There was a misunderstanding from my end. I had assumed that all dates were required and not just the month ends. Anyways hope the updated code might help. Still not the most optimal, but easy to understand I guess..
# import datetime package
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta

def previous_month_ends(months_to_subtract):
    # get first day of current month
    first_day_of_current_month = date.today().replace(day=1)
    print(f"First Day of Current Month: {first_day_of_current_month}")
    # Calculate and previous month's Last date
    date_range_list = [first_day_of_current_month - relativedelta(days=1)]
    cur_iter = 1
    while cur_iter < months_to_subtract:
        # Calculate First Day of previous months relative to first day of current month
        cur_iter_fdom = first_day_of_current_month - relativedelta(months=cur_iter)
        # Subtract one day to get the last day of previous month
        cur_iter_ldom = cur_iter_fdom - relativedelta(days=1)
        # Append to the list
        date_range_list.append(cur_iter_ldom)
        # Increment Counter
        cur_iter+=1
    return date_range_list

print(previous_month_ends(3))

Function to calculate date list between 2 dates:

*

*Calculate the first of current month.

*Calculate start and end dates and then loop through them to get the list of dates.

*I have ignored the date argument, since I have assumed that it will be for current date. alternatively it can be added following your own code which should work perfectly.

# import datetime package
from datetime import date, timedelta
from dateutil.relativedelta import relativedelta

def gen_date_list(months_to_subtract):
    # get first day of current month
    first_day_of_current_month = date.today().replace(day=1)
    print(f"First Day of Current Month: {first_day_of_current_month}")
    start_date = first_day_of_current_month - relativedelta(months=months_to_subtract)
    end_date = first_day_of_current_month - relativedelta(days=1)
    print(f"Start Date: {start_date}")
    print(f"End Date: {end_date}")
    date_range_list = [start_date]
    cur_iter_date = start_date
    while cur_iter_date < end_date:
        cur_iter_date += timedelta(days=1)
        date_range_list.append(cur_iter_date)
        # print(date_range_list)
    return date_range_list

print(gen_date_list(3))

Hope it helps...Edits/Comments are welcome - I am learning myself...

A: from datetime import datetime, timedelta

def get_last_dates(n_months):
   '''
   generates a list of lastdates for each month for the past n months
   Param:
     n_months = number of months back
   '''
  last_dates = []  # initiate an empty list
  for i in range(n_months):
    last_dates.append((datetime.today() - timedelta(days=i*30)).replace(day=1) - timedelta(days=1))
  return last_dates

This should give you a more accurate last_days

A: I just thought a work around I can use since my last codes work:
df = spark.createDataFrame([(1,)],['id'])

days = df.withColumn('last_dates', explode(expr('sequence(last_day(add_months(current_date(),-3)), last_day(add_months(current_date(), -1)), interval 1 month)')))

is to enter -4 and just remove the last_date that I do not need days.pop(0) that should give me the list of needed last_dates.


text:
Q: Mybatis string value insert into oracle CLOB I'm trying to insert list of records into oracle database by using mybatis orm.
Below exception throws while insert into database.

Error updating database.  Cause: java.sql.SQLException: ORA-01461: can bind a LONG value only for insert into a LONG column

Query I have written to insert the data.
<insert id="insertCusHistoryData" parameterType="com.dpworld.tos.admin.model.CusHistory">
      INSERT INTO
         CUS_ACTION_HISTORY_T(SEQ_NO, GLOBAL_ID, REQUEST_ID, CUS_ACTION_CODE, CUS_REQUEST_TIME, ENTITY_TYPE, ENTITY_KEY, PARENT_ENTITY_KEY,
             DELTA_CHANGE, TOTAL_PROCESSING_TIME, TOTAL_SERVER_PROCESSING_TIME, USER_AN, UPDATE_MODE, TOTAL_TIME)
            select  A.*  from(
     <foreach collection="cusHistory" item="history" separator="UNION ALL" >
        SELECT
                #{history.sequenceNo} as SEQ_NO,
                #{history.globalId} as GLOBAL_ID,
                #{history.requestId} as REQUEST_ID,
                #{history.cusActionCode} as CUS_ACTION_CODE,
                #{history.cusRequestTime} as CUS_REQUEST_TIME,
                #{history.entityType} as ENTITY_TYPE,
                #{history.entityKey} as ENTITY_KEY,
                #{history.parentEntityKey} as PARENT_ENTITY_KEY,
                #{history.deltaChange, jdbcType=CLOB},
                #{history.totalProcessingTime} as TOTAL_PROCESSING_TIME,
                #{history.totalServerProcessingTime} as TOTAL_SERVER_PROCESSING_TIME,
                #{history.userAn} as USER_AN,
                #{history.updateMode} as UPDATE_MODE,
                #{history.totalTime} as TOTAL_TIME
            FROM DUAL
    </foreach>)A

But when I modify insertion code like below it inserts property, but it takes around 23 seconds tom complete the job.
BEGIN
     <foreach collection="cusHistory" item="history" separator="" >
         INSERT INTO
         CUS_ACTION_HISTORY_T(SEQ_NO, GLOBAL_ID, REQUEST_ID, CUS_ACTION_CODE, CUS_REQUEST_TIME, ENTITY_TYPE, ENTITY_KEY, PARENT_ENTITY_KEY,
            DELTA_CHANGE, TOTAL_PROCESSING_TIME, TOTAL_SERVER_PROCESSING_TIME, USER_AN, UPDATE_MODE, TOTAL_TIME)
         VALUES(
                #{history.sequenceNo},
                #{history.globalId},
                #{history.requestId},
                #{history.cusActionCode},
                #{history.cusRequestTime},
                #{history.entityType},
                #{history.entityKey},
                #{history.parentEntityKey},
                #{history.deltaChange, jdbcType=CLOB},
                #{history.totalProcessingTime},
                #{history.totalServerProcessingTime},
                #{history.userAn},
                #{history.updateMode},
                #{history.totalTime});
    </foreach>
      END;

I have tried by removing the CLOB column from the first and second query, first query took around 8 seconds and second query took around 20 seconds to complete, huge performance issue comes in this case.
Please advice.


text:
Q: Exim: convert bounced messages back to original We have exim4 set up on Debian as a smarthost to send mail via Google's mail servers. We use Google Apps for everything else, so this made sense. Problem is, the password for the smart host account was changed, causing exim to bounce the messages back and then freeze them. Now I have a large collection of unsent mail in /var/spool/exim4/[input|msglog].
I have tried running:
exim -d -M 1Mx6IS-0006bC-3h
but that causes the bounced message to be sent, not the original. I can see a copy of the original message in /var/spool/exim4/input/1Mx6IS-0006bC-3h-D under the line
------ This is a copy of the message, including all the headers. ------

...but I have not figured out a way to take this frozen bounced message, and convert it back to the original message so it can be retried.
Any ideas?

A: Is this a final bounce? Or the one that says that another attempt to deliver will happen in some number of hours, if later, could it be that both messages are sent out, the original and bounce? Since both are in the queue, as I understand it from your question.

A: UNTESTED!
This is a python script that should do what you want.  It is thoroughly untested, and is guarenteed not to work in all cases.  If you don't know Python, then nevermind, it was a nice bit of practice for me.
import os
import smtplib
import email

mydir = os.open("/mydir")
server = smtplib.SMTP()

files = [mydir + "/" + f for f in os.listdir(mydir) if os.path.isfile(mydir + "/" + f)]

while files:
    f = files.pop()
    msg = email.message_from_file(open(f))
    body = msg.get_payload().split("------ This is a copy of the message, including all the headers. ------")[1].strip()
    from_addr = msg["To"]
    to_addr = msg["X-Failed-Recipients"]
    print "Sending message to ", to_addr
    server.send(from_addr, to_addr, body)
    print "Message sent"


text:
Q: I get the following error on the "Confirm Hosts" step in Ambari (creating cluster):
The Registration log contains the following error:
==========================
Running setup agent script...
==========================
Command start time 2017-11-26 12:05:31

('  File "/usr/lib/python2.6/site-packages/ambari_agent/main.py", line 355, in main
    (retries, connected, stopped) = netutil.try_to_connect(server_url, MAX_RETRIES, logger)
UnboundLocalError: local variable \'server_url\' referenced before assignment
INFO 2017-11-26 12:00:19,304 ExitHelper.py:53 - Performing cleanup before exiting...
I tried it a few times from scratch and I get the same result. ANy ideas on how to fix this?


text:
Q: undefined local variable or method `json' in JBuilder When I try get all categories (index action) there is an error:
undefined local variable or method `json'

But in show action everything fine. All files has .jbuilder extension.
Here is controller code:
def index
  @categories = Category.all
end

# GET /categories/1
# GET /categories/1.json
def show
  @category = Category.find(params[:id])
end

Stack trace:

app/views/categories/index.json.builder:1:in_app_views_categories_index_json_builder___502133872307116590_70140532925300'
  actionpack (3.2.11) lib/action_view/template.rb:145:inblock in render'
  activesupport (3.2.11) lib/active_support/notifications.rb:125:in instrument'
  actionpack (3.2.11) lib/action_view/template.rb:143:inrender'

A: Try to rename your file index.json.builder to index.json.jbuilder

A: You could also rename it to index.json.jpbuilder and use this gem: https://github.com/bigjason/jpbuilder (if you want JSONP)


text:
Q: How to make android app in java with counter automatically increment integer by 1 every 24 hours? I want to make the app increase the integer by 1 every 24 hours, I have set a sharedpreferences to save the value in the app whenever it closes.
How can I get the app to calculate days passed whenever opened?
I also want the button to reset the counter.
I have tried searching google but I'm not finding a solution specific to my problem.
public class MainActivity extends AppCompatActivity {
    private int days;
    Button bt;
    TextView textView;
    private SharedPreferences counter;

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

        counter = getApplicationContext().getSharedPreferences("shareware", Context.MODE_PRIVATE);
        days = counter.getInt("days",0);

        bt = (Button) findViewById(R.id.bt);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText(Integer.toString(days));
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                days++;
                textView.setText(Integer.toString(days));
                counter.edit().putInt("days", days).apply();
                Log.i("Test: ", Integer.toString(counter.getInt("days", days)));
                Button bt = (Button)findViewById(R.id.bt);
                bt.setText("Reset");
            }
        });
    }
}


text:
Q: Is Boba Fett alive in the new canon? In the EU/Legends material Boba Fett fought his way out of the Sarlacc's guts- Has there been any announcements or anything to suggest he survived getting swallowed by it in the new films (from TFA and beyond)?

A: According to the Boba Fett Fan Club, the LucasFilm Story Group brought up Fett at Celebration Anaheim in 2015; according to them, he's Schrödinger's Fett:

"Boba Fett is both simultaneously alive and dead in the Sarlacc."

[...]
What Pablo [Hidalgo] meant by the quote, as explained by further context of his point during the panel, is that Lucasfilm's Story Group has not independently decided one way or the other that Boba Fett is alive nor dead after the fall in the Sarlacc Pit.

However, Fett appears as a playable "Hero" character1 in the recently-released Star Wars: Battlefront video game:

However however, since the canonical status of Battlefront is "complicated", that may not necessarily be a confirmation of his survival2:

*

*Vader and Palpatine are also playable heroes in Battlefront, despite them not appearing in some of the playable maps, and being dead for others (like the Battle of Jakku DLC map)

*Similarly, Fett is playable in some maps where he, canonically, does not appear; Hoth, for instance:

I haven't played the game, so I can't comment on the situations where Fett appears.

1 Battlefront games are typically multiplayer shooters, where you play as ground troops: Stormtroopers, CLone troopers, CIS droids, Rebel soldiers, what-have-you. If you collect enough widgets, you can temporarily play as a main character from the films, with different powers and higher stats, who is associated with your faction. The most recent Battlefront game (the one I'm talking about) has six playable Heroes
2 Hat-tip to Tom.Bowen89 for bringing up these points

A: In the (Disney Canon) series The Mandalorian, Boba Fett is indeed alive, however we do not know fully how he escaped the Sarlacc.
He makes his first appearance is S02E01, Chapter 9: The Marshal, at the end of the episode in a quick cameo.

Retroactively, we also saw his feet, cape, and arm in the closing moments of S01E05 Chapter 5: The Gunslinger.

He is then fully introduced in S02E06, Chapter 14: The Tragedy, fighting along side Din Djarin.

Boba is being played by Temura Morrsion who is the same actor that played Jango Fett in the prequel trilogies. Since Boba is an unaltered clone of Jango this makes good sense.

A: A set of Madalorian armor which is implied to have been Fett's is seen in Star Wars: Aftermath

From the box, he withdraws a helmet. Pitted and pocked, as if with some kind of acid. But still-- he raps his knuckles on it . The Mandalorians knew how to make armor, didn't they? "Look at this," he says, holding it up. "Mandalorian battle armor. Whole box. Complete set, by the looks of it. Been through hell and back. I think my boss will appreciate this."

However, this doesn't necessarily mean that Boba Fett is alive, just that his armor somehow made it out of the Sarlacc. (He could have died afterwards.)

A: In Star Wars: Aftermath -life debt- there is an interlude on Tatooine where they talk about how the Sarlacc became partially exposed after jabbas barge crashed around it. And that Jawas have been cutting into and looting the creature. It is possible that he could have been freed this way and that is likely how the Mandalorean armor was also attained. Whether he was alive when found or not though doesnt get explained. Though at the same time they reference finding skeletons. But at the same same time there is no way he could have been a skeleton if his armor was stil intact and as referenced it takes a thousand years for the sarlacc to digest.


text:
Q: messed up screen sharing I am screen sharing from an iMac 10.6.8 looking at a MacBook Pro 10.8. Quite often, but not always, the shared screen looks like this on my iMac.

(This image is anonymized.) So there is the real shared screen down below, and an inverted piece of it at top. Neither piece is active, in that I can't do anything on them remotely. What's going on? Is a display setting messed up on one machine? Help! This is really annoying. I can easily do screen sharing to other machines.


text:
Q: GameObject colliding with Sprite? So I have a sprite and it's name is "princess" and when a cube touches my sprite
I want the princess to be destroyed. I added a rigidbody, and a box collider, but for some reason the cube just goes through the princess sprite.
The cube is generated with code so it's name is "Cube" according to the hierachy so I wrote this code

private void OnCollisionEnter(Collision collision)
{
   if(collision.gameObject.name == "Cube")
    {
        Destroy(this.gameObject);
    }
}

I think Destroy(this.gameObject) would destroy the princess, but they're not even colliding.
Any ideas?
Here is what the "game" looks like.
Game

A: Check if you checked the "is trigger" inside the box colliders.
You should use tag because if you spawn multiple cubes the will have names like "Cube (1)" and so on.
You need to use collider2d
void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Cube")
    {
        Destroy(this.gameObject);
    }
}

both of your object needs to have box collider2d and rigidbody2d and not set to "is trigger". example:

A: Destroy(this.gameObject) is working for own object where
collision.gameObject.setActive("False") is working for collide object
This code is working on my game. where "Player" is my Sprite tag. And make sure 'Is Trigger' is checked for your Cube
void OnTriggerEnter2D(Collider2D other) {
    if (other.tag == "Player")
    {
        Destroy(gameObject);
    }

}

OR alternatively in your case below code you could use in Cube script then might be work
void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "princess")
    {
        collision.gameObject.setActive("False")
    }
}


text:
Q: Почему через Геокодер не получается найти организацию? Я преобразую текст в координаты при помощи geocode, после чего рисую метку.
Но пользователи "преобразуют" текст в координаты при помощи яндекс-карт. По одному и тому же запросу получаеются разные координаты (в яндекс-картах и при использовании geocode).
фиддл с использованием геокода:
...
let geocode = await ymaps.geocode('картодром фирсановка', {json: true});
let coords = geocode.GeoObjectCollection.metaDataProperty.GeocoderResponseMetaData.Point.coordinates.reverse();
point.geometry.setCoordinates(coords);
yMap.setCenter(coords);
...

http://jsfiddle.net/1v3fw53m/235/
Ссылка на карту с ТЕМ ЖЕ запросом:
https://yandex.ru/maps/216/zelenograd/?ll=37.254842%2C55.971234&z=16&mode=search&text=%D0%BA%D0%B0%D1%80%D1%82%D0%BE%D0%B4%D1%80%D0%BE%D0%BC%20%D1%84%D0%B8%D1%80%D1%81%D0%B0%D0%BD%D0%BE%D0%B2%D0%BA%D0%B0&sll=37.254842%2C55.971234&sspn=0.027637%2C0.014416&ol=biz&oid=219586516291&sctx=ZAAAAAgBEAAaKAoSCdo5lKEqlkJAEUMQIXU7X0xAEhIJAP%2F%2F%2F%2F9MzD8RAJATVMjtvD8iBAABAgQoBTABOOrFu%2BTS8JKFxQFA1wFIAVXNzMw%2BWABqAnJ1cACdAexRuD2gAQCoAQA%3D
Каким образом я могу получить из АПИ такой же результат, как и при обычном поиске?

A: Геокодер предназначен для конвертации адресов в координаты и наоборот. Найти организацию через Геокодер нельзя, т.к. он не является поиском и решает другую задачу.
Вам нужно использовать Геопоиск (API Поиска по организациям). В зависимости от Вашей задачи можно просто добавить поисковую строку с предзаполненным запросом или использовать HTTP API Геопоиска. Второй вариант необходим, если Вы хотите сами выбирать способ отображения объекта на карте (кастомная метка, своя карточка и .т.п).


text:
Q: Page loads forever when i make a request in my FastApi server I have set this FastApi server:
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from pathlib import Path
import requests
import mysql.connector as mariadb
from database import connection_properties as conn

mariadb_connection = mariadb.connect(user=conn.USER,
                                    password=conn.PASSWORD,
                                    host=conn.HOST,
                                    database=conn.DATABASE,
                                    auth_plugin='mysql_native_password')
cursor = mariadb_connection.cursor()

app = FastAPI()

templates = Jinja2Templates(directory="htmlPages")

app.mount(
    "/htmlPages/static",
    StaticFiles(directory=Path(__file__).parent.absolute() / "htmlPages" / "static"),
    name="static",
)

@app.get("/county")
async def get_regions():
    cursor.execute("SELECT name FROM county")
    regions = cursor.fetchall()
    return {"regions": regions}

@app.get("/")
async def home_page(req: Request):
    return templates.TemplateResponse("homePage.html", {"request": req})

@app.get("/predictions", response_class=HTMLResponse)
async def predictions(request: Request):
    response = requests.get("http://localhost:8000/county")
    regions = response.json()["regions"]
    return templates.TemplateResponse("predictions.html", {"request": request, "regions": regions})

The proble is that everytime I make a request at http://localhost:8000/predictions , the page seems like loading forever and I do not get anything. When I make a request at http://localhost:8000/county I receive the data that I want from the database. What is wrong?


text:
Q: Cannot put MacBook Air to sleep Problem
I have a MacBook Air (2020) running MacOS Monterey (12.2.1) which will not go to sleep. I also cannot put it to sleep manually (the option is greyed out from the Apple menu and the keyboard shortcut does not work). Closing the display does not put the laptop to sleep either. For example, if I'm playing music, it will continue to play even after closing the display.
Attempted solutions

*

*Restarting computer

*Shutting down computer

*Restarting in Safe mode

*Resetting NVRAM

*Running sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.PowerManagement SystemPowerSettings -dict SleepDisabled -bool NO from the command line and then restarting again

Any ideas?

A: Try entering sudo pmset -a disablesleep 0 into your Terminal App.
Basically I had this need of stopping my MacBook from sleeping so I can have music playing with lid closed.  Before using an app called "Amphetamine", my way of approach is to use commands in Terminal to modify some system's internal things. When sleep is disabled this way, all the above things you mentioned above happens.
Therefore the command I suggested should, theoretically (re)enable sleep.


text:
Q: Why does my application using OmniThreadLibrary Parallel.Pipeline continue remain running in the background after being closed? I'm using OmniThreadLibrary to implement a background pipleline for sending emails (refer to this SO question). I notice that after closing the application, it continues running in the background (seen in Windows Task Manager). That means that there is something wrong in my code in the way I implemented the OTL pipeline. Can you help me identify the trouble?
Code follows:
unit uEmailQueue;

interface

uses Classes, OtlCommon, OtlCollections, OtlParallel, Windows;

type
  TEmailServer = record
    SMTPHost: String;
    SMTPPort: Integer;
    SMTPUseSSL: Boolean;
    SMTPUserName: String;
    SMTPPassword: String;
    SMTPSenderName: String;
  end;

  TEmailMessage = record
    RecipientEmailAddr: String;
    EmailSubject: String;
    EmailMessage: String;
  end;

  TEmailQueue = class(TObject)
  private
    FEmailServer: TEmailServer;
    FPipeline: IOmniPipeline;
    procedure SendEmailStage(const input, output: IOmniBlockingCollection);
  public
    constructor Create;
    destructor Destroy; override;
    procedure SendEmail(AEmailMessage: TEmailMessage);
  end;

implementation

{ TEmailQueue }

procedure TEmailQueue.SendEmailStage(const input, output: IOmniBlockingCollection);
var
  mailmessage: TOmniValue;
begin
  for mailmessage in input do
  begin
    Beep(3700, 1500); // just some dummy code for now
  end;
end;

constructor TEmailQueue.Create;
begin
  FPipeline := Parallel.pipeline.Stage(SendEmailStage).Run;

end;

destructor TEmailQueue.Destroy;
begin

  inherited;
end;

procedure TEmailQueue.SendEmail(AEmailMessage: TEmailMessage);
begin
  FPipeline.input.Add(TOmniValue.FromRecord(AEmailMessage));

  // FPipeline.input.CompleteAdding;

  // FPipeline.WaitFor(INFINITE);

end;

end.

I initialize and call the above class like this:
In the application's main form's OnCreate event:
  FEmailQueue := TEmailQueue.Create;

A button on the main form has this in the OnClick event:
var
  em: TEmailMessage;
begin
  FEmailQueue.SendEmail(em);

later, I free the class like this in the main form's OnDestroy event:
  FEmailQueue.Free;

A: You should call FPipeline.input.CompleteAdding from TEmailQueue.Destroy. Otherwise, SendEmailStage will never stop.


text:
Q: Can pip/setuptools console scripts pass python options to python itself? For example, using -m for pdb and post-mortem debugging, you can do:
python -m pdb script.py arg1 --kwarg
(say for instance that arg1 and kwarg are parsed from sys.argv with the argparse module).
A CLI tool can be created with pip/setuptools' entry points:
setup(
    ...
    entry_points={
        "console_scripts": [
            "toolname = my_project.script:main"
        ]
    },
)

Now after installing pip install my_project, toolname can be used instead of python /path/to/script.py. Is it possible to pass arguments directly to python - like -m to invoke pdb?
Edit:
Unlike python setup tools console_scripts with arguments I know how to pass arguments to the script, and I'm looking for how to pass arguments to python itself.
The python -m pdb $(which myscript) method, used in How to start debugger with an entry_point script is pretty good, but it only works if the script actually calls main() when executed (script may be from a third-party library).
python -c "import pdb, pkg_resources; pdb.run('pkg_resources.load_entry_point(\'mylocalpkg\', \'console_scripts\', \'myscript\')()')" supports more scripts and platforms, but I'm not sure if it works for other python options other than -m pdb.


text:
Q: react native google places autocomplete npm package tacking full page in app I am developing a react native app. In that, I am using react-native-google-places-autocomplete NPM package. It's working fine. My problem is it is taking full page view. how to fix this. I want an Output like this
Needed Output image link
here is my code

https://snack.expo.io/@savadks1818/react-native-google-places-autocomplete-example

        import React from 'react';
    import { Constants } from 'expo';
    import { View, TextInput,Text,Alert } from 'react-native';
    import {
      GooglePlacesAutocomplete,
    } from 'react-native-google-places-autocomplete'; // 1.2.12
    let datas;
    let details;
    const homePlace = {
      description: 'Home',
      geometry: { location: { lat: 48.8152937, lng: 2.4597668 } },
    };
    const workPlace = {
      description: 'Work',
      geometry: { location: { lat: 48.8496818, lng: 2.2940881 } },
    };

    export default class OutletCreator extends React.Component {
      render() {
        return (

          <View style={{ paddingTop: Constants.statusBarHeight, flex: 1 }}>
            <GooglePlacesAutocomplete
              placeholder="Search"
              minLength={2} // minimum length of text to search
              autoFocus={false}
              returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
              listViewDisplayed="false" // true/false/undefined
              fetchDetails={true}
              renderDescription={row => row.description} // custom description render
              onPress={(data, details = null) => {
                // 'details' is provided when fetchDetails = true
                datas=data;
                alert("lat: "+JSON.stringify(details.geometry.location.lat)+" lan: " +JSON.stringify(details.geometry.location.lng) )
                console.log(data);
                console.log(details);
              }}
              getDefaultValue={() => {
                return ''; // text input default value
              }}
              query={{
                // available options: https://developers.google.com/places/web-service/autocomplete
                key: 'xxxxxxxxxx',
                language: 'en', // language of the results
                types: '(cities)', // default: 'geocode'
              }}

              styles={{
                locationAutocompleteStyle: {
        container: {
          zIndex: 10,
          overflow: 'visible',
          height: 50,
          flexGrow: 0,
          flexShrink: 0
        },
                description: {
                  fontWeight: 'bold',
                },
                predefinedPlacesDescription: {
                  color: '#1faadb',
                },
                textInput: {
                backgroundColor: 'transparent',
                fontSize: 15,
                lineHeight: 22.5,
                paddingBottom: 0,
                flex: 1
              },
        listView: {
          position: 'absolute',
          top: 60,
          left: 10,
          right: 10,
          backgroundColor: 'white',
          borderRadius: 5,
          flex: 1,
          elevation: 3,
          zIndex: 10
        },
                }

              }}
              //currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
              currentLocationLabel="Current location"
              nearbyPlacesAPI="GooglePlacesSearch" // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
              GoogleReverseGeocodingQuery={{
                // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
              }}
              GooglePlacesSearchQuery={{
                // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                rankby: 'distance',
                types: 'food',
              }}
              filterReverseGeocodingByTypes={[
                'locality',
                'administrative_area_level_3',
              ]} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
              predefinedPlaces={[homePlace, workPlace]}
              debounce={200}
            />
          <TextInput>Some Text</TextInput>

          </View>
        );
      }
    }


text:
Q: I'm trying to detect that SQL Server Compact Edition is installed in a system or not Same code is behaving differently in a console app & WPF app.
When I call the method in a WPF app, it returns true, even though SQL Server CE is not installed; however, the same code run in a console app returns false.
I found a way but it seems two behave from same code, one in console app & one in WPF app! What's making the difference?
I have logged each steps, shocked to see how it returns true in WPF
public static bool IsSQLCeV40Installed()
{
        var result = false;

        try
        {
            System.Reflection.Assembly.Load("System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
            result = true;
            _logger.Info($"IsSQLCeV40Installed: IsSqlCe {result}");
        }
        catch (System.IO.FileNotFoundException)
        {
            _logger.Info("IsSQLCeV40Installed: File Not Found Exception");
        }
        catch (Exception)
        {
            _logger.Info("IsSQLCeV40Installed: General Exception");
        }

        return result;
}

WPF prints this:
IsSQLCeV40Installed: IsSqlCe & returns true

Console app logs this:
IsSQLCeV40Installed: File Not Found Exception & returns false

However both should return as console app is doing in case that SQL Server CE is not installed on the machine!

A: One of the apps are most likely built for x86 and the other AnyCPU or x64, and therefore they look in either the 32 bit .NET Framework GAC or the 64 bit .NET Framework GAC.
More tips here: http://erikej.blogspot.com/2010/05/how-to-detect-if-x64-sql-compact-35-sp2.html

A: If your application relies on sql ce being there and a specific version then you can just copy the dll to the same location as your exe and then there's no need to install them. Thus no need to check if they're already installed.
Do that with whatever installer or disctribution method you use for an app.  This is just an filecopy/xcopy rather than an install and will of course work fine with pushing file copy installs from a windows server.
If you have many applications using sql ce this would of course be somewhat wasteful of disk space on the client computer. This is not usually a concern. I think it's under 5 meg.
Generally, I would also advise you try and avoid driving programme logic by error handling. Where you can possibly avoid a try catch driving routine logic then do so. In this case you could check whether there is one of several possible entries in the user's registry.


text:
Q: How do I get pagination to work with bootstrap using PHP? I have been attempting to get my items in the database to show on my application using pagination. However I have hit a stumbling block with some errors that I haven't come across before which are :-

*

*
Undefined index: page in C:\Users\lenny\Desktop\TheVault\vault.php on
  line 14

*
Missing argument 3 for FilmDataSet::showFilms(), called in
  C:\Users\lenny\Desktop\TheVault\vault.php on line 15 and defined in
  C:\Users\lenny\Desktop\TheVault\Model\FilmDataSet.php on line 26

*
Undefined variable: page in
  C:\Users\lenny\Desktop\TheVault\Model\FilmDataSet.php on line 32

I am using MVC on my application using Netbeans as my IDE, these errors are from these sections of my application which are :-
Model
public function showFilms($UserID, $perPage, $page) {

    //declare new film array
    $film = array();
    //SQL Query Selecting equivalent information to be displayed
    // $sqlQuery = 'SELECT FilmID, Title, Director,YearofRelease, Genre, Image, MainActor, MainActor1, MainActor2, Synopsis FROM films WHERE User ="' . $UserID . '" LIMIT '.$perPage.' OFFSET '.(($page - 1)*$perPage).' ORDER BY Title DESC';
    $sqlQuery = 'SELECT FilmID, Title, Director, YearofRelease, Genre, Image, MainActor, MainActor1, MainActor2, Synopsis FROM films WHERE User ="' . $UserID . '" ORDER BY Title DESC LIMIT ' . $perPage . ' OFFSET ' . (($page - 1) * $perPage) . '';
    // prepare a PDO statement
    $statement = $this->_dbHandle->prepare($sqlQuery);

    // Execute PDO statement
    $statement->execute();

    // While loop fetches each row matching query
    while ($row = $statement->fetch()) {
        $film[] = array('FilmID' => $row['FilmID'],
            'Title' => $row['Title'],
            'User' => $UserID,
            'Director' => $row['Director'],
            'YearofRelease' => $row['YearofRelease'],
            'Genre' => $row['Genre'],
            'Image' => $row['Image'],
            'MainActor' => $row['MainActor'],
            'MainActor1' => $row['MainActor1'],
            'MainActor2' => $row['MainActor2'],
            'Synopsis' => $row['Synopsis']
        );
    }
    //returning film array
    return $film;
}

View

        <?php
        if (count($film)) {
            ?>

            <?php foreach ($film as $list): ?>

                            <?= ( $list['Title']) ?>   Directed By : <?= ( $list['Director']) ?>

                            <?= ($list['Image'] <> "" ? "" : "") ?>

 Year Released :  <?= ( $list['YearofRelease']) ?>

 Film Genre :  <?= ($list['Genre'] ) ?>

 Starring : <?= ($list['MainActor']) ?> , <?= ($list['MainActor1']) ?> , <?= ($list['MainActor2']) ?>

 Synopsis :  <?= ($list['Synopsis'] ) ?>

            <?php endforeach; ?>

            <?php
        }else {
            ?>

No Films Added yet!

        <?php } ?>

                        «

1

2

3

4

5

                        »

Controller
<?php
session_start();

require_once('Model/UserDataSet.php');
require_once('Model/FilmDataSet.php');

$view = new stdClass();
$view->pageTitle = 'My Vault';

$aa = new FilmDataSet();

$film = array();
$page = htmlspecialchars($_GET['page']);
$film = $aa->showFilms($_SESSION['Email'], $page);

require_once('View/home.phtml');

Any Ideas of how I can rectify this as I want 1 item to show up per page. I did get them appearing from the database however they were all just showing up from the database beforehand.

A: You are missing a parameter in your showFilms() call, it should be like
$film = $aa->showFilms($_SESSION['Email'], $item_per_page, $page);

and your $page variable should be an integer.
I suggest you to check both Datatables plugin and Bootstrap table
EDIT: if you have lots of data (more than 1000 rows), consider Pipelining data, it works very good


text:
Q: Socket close timing I have what appears to be a timing problem between a client (Galaxy Nexus) and a custom server since upgrading from Ice Cream Sandwich to Jelly Bean.  Here is the general flow:

*

*Client opens socket, issues HTTP get to server

*Server accepts, starts new thread, responds with HTTP header and 200 OK.

*Server writes (binary) file to socket.

*Client reads data from socket and saves to a file.

*After server thread writes all data, it closes the socket, and terminates

This has worked well over the past several months prior to the Jelly Bean update.  Since the update the binary transfer succeeds about 70% of the time.  The remaining 30% fails
when 'serverSocket.getInputStream().read' returns a -1 indicating the end of stream has been reached.  No data has been read, no error exceptions raised, nothing in logcat.
The possibility of a timing problem arises when I change the server behavior in step #5.  The thread was closing the socket after the write with the observed problems.  If I remove the socket close, terminate the thread after the write, and let the OS eventually close the socket then it seems to work all the time.
I used tcpdump and WireShark to look at the packets in both the successful and failed cases.  In the failed case a socket is closed in a few milli-seconds while in the successful case the socket is closed is a quarter or more of a second.  The net of this is that any delay we cause in the socket closing improves our chances for success.
If anyone has any suggestions with what we may be doing to cause this problem or suggestions on how to narrow down the problem please feel free to respond.  I can add code samples if required.

A: It looks like that when the server ask for the connection close, the socket is immediatly closed. Maybe the default ocket linger's time has changed between version ???
Try setting the socket linger's time using:
socket.setSoLinger(boolean on, int timeout);

to have the server waiting some time before close channel if some data still waiting to be sent.
If this doesn't solve, you can change your flow above to:
...
4.Client reads data from socket and saves to a file.
5.Client send confirmation to server.
6.Server close connection.
--EDITED--
A gracefull way to achive the above without additional TCP data packets traveling for the closing confirmation is:
when server finish writing to the socket calls:
socket.shutdownOutput();

when client socket.read() returns -1, client calls:
socket.close();

This ensures that client is informed that all data has been sent, and sender will wait for the socket closure protocol to complete.


text:
Q: Bootstrap - should each row have container as immediate parent? I know column should have row as immediate parent (or, to be precise, rows should have only columns as ther immediate children) but does row must have container/container-fluid as immediate parent?
I couldn't find mentioning it in docs and i've seen examples of both: where rows do and don't have their respective containers.

A: It is not essential that a row has a container as immediate parent as in some cases it is not possible to have it as immediate parent. But to be consistent with your project you should always have container as some parent to the row as you may experience alignment and padding problems without it.

A: It depends on the Bootstrap version, and how you want the content aligned, but generally containers are required...
Version 3.x

"Rows must be placed within a .container (fixed-width) or
  .container-fluid (full-width) for proper alignment and padding."

Version 4.x

"Containers are the most basic layout element in Bootstrap and are
  required when using our default grid system."

The top level element of the grid system is the .row, and therefore row's should be the immediate child of a container. Bootstrap 4 is more flexible in that rows & columns can be created without gutters, and the spacing utils can be used to adjust padding and margins.


text:
Q: Trigger creation when table is altered but there will same e_id where updation or deletion will happen CREATE TABLE source_det (
det_id number(10) by default IDENTITY
    e_id       NUMBER(10),
    sys_name   VARCHAR2(20),
    ref_id     NUMBER(10),
    sys_other  VARCHAR2(30)
);

INSERT INTO source_det VALUES(1,11,'SOURCE',992,null);
INSERT INTO source_det VALUES(2,11,'SOURCE',637,null);
INSERT INTO source_det VALUES(3,11,'SOURCE',null,'Manual');
INSERT INTO source_det VALUES(4,11,'TARGET',637,null);
INSERT INTO source_det VALUES(5,12,'TARGET',637,null);

Audit table:
CREATE SEQUENCE audit_tab_sq;
CREATE TABLE audit_tab (
    a_id       NUMBER(10) default audit_tab_sq.nextval,
    l_transaction varchar2(20),--INSERT, UPDATE, DELETE
    e_id       NUMBER(10),
    sys_name   VARCHAR2(20),
    value_old  VARCHAR2(20),
    value_new  VARCHAR2(20)
);

I need to create a trigger that will get fired whenever there is new event occurred on the main table i.e source_det
Example:
Lets say for this record
INSERT INTO source_det VALUES(11,'SOURCE',null,'Manual');
For e_id 11 whose sys_name is SOURCE and ref_id is null and sys_other is Manual.
So, for this record if user has filled in the ref_id to 321 and sys_other to Document.
Then in my audit table, a new entry will get inserted only for this row even though we have multiple e_id.
Expected Output:
+------+---------------+------+----------+-----------+-----------+
| a_id | l_transaction | e_id | sys_name | value_old | value_new |
+------+---------------+------+----------+-----------+-----------+
|    1 | UPDATE        |   11 | SOURCE   | null      | Document  |
+------+---------------+------+----------+-----------+-----------+

Likewise, if there are any new records inserted or deleted same should be the case.
I am wondering if this can be handled using trigger because there can be multiple e_id
Tool used: Oracle SQL Developer(18c)

A: From the information you have given, it seems as though you are missing a unique value (key) for your tables and this may be causing your problems.
Per your given code, you have
CREATE TABLE source_det (
    e_id       NUMBER(10),
    sys_name   VARCHAR2(20),
    ref_id     NUMBER(10),
    sys_other  VARCHAR2(30)
);

INSERT INTO source_det VALUES(11,'SOURCE',992,null);
INSERT INTO source_det VALUES(11,'SOURCE',637,null);
INSERT INTO source_det VALUES(11,'SOURCE',null,'Manual');
INSERT INTO source_det VALUES(11,'TARGET',637,null);
INSERT INTO source_det VALUES(12,'TARGET',637,null);

The database currently has no way of differentiating between the row inserted with INSERT INTO source_det VALUES(11,'SOURCE',637,null); and the row inserted in the following INSERT INTO source_det VALUES(11,'SOURCE',637,null);.
I would recommend adding a unique value (key) to each of your tables so that there is a unique value to identify each tuple. You can achieve this in multiple ways (id, unique pair, etc.), but your dataset doesn't seem to contain unique pairs, so an id would probably work best:
CREATE TABLE source_det (
    id         NUMBER GENERATED BY DEFAULT AS IDENTITY
    e_id       NUMBER(10),
    sys_name   VARCHAR2(20),
    ref_id     NUMBER(10),
    sys_other  VARCHAR2(30),
    PRIMARY KEY(id)
);

Then you can create a trigger that fires on update | insert | delete and will have a unique key to reference for each row.

A: Here's how; trigger:
SQL> CREATE OR REPLACE TRIGGER trg_sdet_audit
  2     BEFORE INSERT OR UPDATE OR DELETE
  3     ON source_det
  4     FOR EACH ROW
  5  BEGIN
  6     IF INSERTING
  7     THEN
  8        INSERT INTO audit_tab (a_id,
  9                               l_transaction,
 10                               e_id,
 11                               sys_name,
 12                               value_old,
 13                               value_new)
 14             VALUES (audit_tab_sq.NEXTVAL,
 15                     'INSERT',
 16                     :new.e_id,
 17                     :new.sys_name,
 18                     NULL,
 19                     :new.sys_other);
 20     ELSIF UPDATING
 21     THEN
 22        INSERT INTO audit_tab (a_id,
 23                               l_transaction,
 24                               e_id,
 25                               sys_name,
 26                               value_old,
 27                               value_new)
 28             VALUES (audit_tab_sq.NEXTVAL,
 29                     'UPDATE',
 30                     :new.e_id,
 31                     :new.sys_name,
 32                     :old.sys_other,
 33                     :new.sys_other);
 34     ELSIF DELETING
 35     THEN
 36        INSERT INTO audit_tab (a_id,
 37                               l_transaction,
 38                               e_id,
 39                               sys_name,
 40                               value_old,
 41                               value_new)
 42             VALUES (audit_tab_sq.NEXTVAL,
 43                     'DELETE',
 44                     :new.e_id,
 45                     :new.sys_name,
 46                     :old.sys_other,
 47                     NULL);
 48     END IF;
 49  END;
 50  /

Trigger created.

Testing:
SQL> UPDATE source_det
  2     SET sys_other = 'Other'
  3   WHERE e_id = 11;

4 rows updated.

SQL> DELETE FROM source_det
  2        WHERE det_id = 2;

1 row deleted.

Result:
SQL> SELECT * FROM audit_tab;

      A_ID L_TRANSACTION              E_ID SYS_NAME             VALUE_OLD            VALUE_NEW
---------- -------------------- ---------- -------------------- -------------------- --------------------
        16 UPDATE                       11 SOURCE                                    Other
        17 UPDATE                       11 SOURCE                                    Other
        18 UPDATE                       11 SOURCE               Manual               Other
        19 UPDATE                       11 TARGET                                    Other
        20 DELETE                                               Other

SQL>

Note that it would probably be a good idea to include timestamp into the log table.


text:
Q: Belisha Beacon Java Program button query the task is to write code for a Belisha Beacon which starts off as flashing and the colours alternate between light grey and Orange and has two buttons which are Flash and Steady. So when I click the Steady button, the Beacon has to stay as Orange but for my program, the Beacon stays steady on whichever colour it was when I click on the Steady button and when I click on the Flash button after I have clicked on the Steady button, the Beacon doesn't flash again. Here is my code so far, someone please help me where I have gone wrong, thank you :).
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class BelishaBeacon {
    private static Timer timer;
    public class Drawing extends JPanel {

        private int x = 125;
        private int y = 80;
        private boolean changeColors = false;

        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            //creating the shapes
            Rectangle box1 = new Rectangle(165, 180, 20, 45);
            Rectangle box2 = new Rectangle(165, 225, 20, 45);
            Rectangle box3 = new Rectangle(165, 270, 20, 45);
            Rectangle box4 = new Rectangle(165, 315, 20, 45);
            Rectangle box5 = new Rectangle(165, 360, 20, 45);
            Rectangle box6 = new Rectangle(165, 405, 20, 45);

            //drawing the shapes
            Ellipse2D.Double ball = new Ellipse2D.Double(x, y, 100, 100);
            g2.draw(ball);
            g2.draw(box1);
            g2.draw(box2);
            g2.draw(box3);
            g2.draw(box4);
            g2.draw(box5);
            g2.draw(box6);
            //coloring the shapes
            g2.setColor(Color.BLACK);
            g2.fill(box1);
            g2.fill(box3);
            g2.fill(box5);
            g2.setColor(Color.ORANGE);
            g2.fill(ball);
            changeColors = !changeColors;
            if (changeColors) {
                g2.setColor(Color.darkGray);
                g2.fill(new Ellipse2D.Double(x, y, 100, 100));
            }
        }

        public void changeColors() {
            changeColors = true;
            repaint();
        }
    }

    public BelishaBeacon() {
        //Creation of frame
        JFrame frame = new JFrame();
        frame.setSize(350, 570);
        frame.setTitle("Belisha Beacon");
        frame.setLayout(new BorderLayout(0, 0));
        final Drawing shapes = new Drawing();

        timer = new Timer(500, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shapes.repaint();
            }
        });

        JButton jbtFlash = new JButton("Flash");
        jbtFlash.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });

        final JButton jbtSteady = new JButton("Steady");
        jbtSteady.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        timer.stop();
                    }
                });

        //Positioning
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new GridLayout(1, 2, 0, 0));
        controlPanel.add(jbtFlash);
        controlPanel.add(jbtSteady);

        frame.add(controlPanel, BorderLayout.SOUTH);
        frame.add(shapes);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new BelishaBeacon();
        timer.start();
    }
}

A: So for your Flash button, the listener is currently empty. What you want to do is to check that when the flash button is pressed then start the timer again.
Try this
JButton jbtFlash = new JButton("Flash");
    jbtFlash.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Flashing");
            if (!timer.isRunning()) {
                timer.start();
            }

        }
    });

And for your Steady button problem. There is no logic there at the moment to check what is the current colour i.e. if it is Grey or Yellow. So you will need somehow modify the code to check the current colour state and stop it when it is Yellow. Have some thoughts :)


text:
Q: Can I return two values from recursive search function? Got stuck in a weird JavaScript functional programming hole.
Here it is:
// Given an integer n, can n be reached by some combination of plus five and times three?

function recursiveSearch (n) {
  // if attempt matches return success
  // if attempt produces neutral keep trying
  // if attempt matches less than 1 return failure
  if (n === 1) return true
  if (n > 1) {
    return recursiveSearch( n-5 ), recursiveSearch( n/3 )
  }
  else return false
}

console.log(1, recursiveSearch(1) )
console.log(3, recursiveSearch(3) )
console.log(6, recursiveSearch(6) )
console.log(7, recursiveSearch(7) )
console.log(9, recursiveSearch(9) )
console.log(13, recursiveSearch(13) )
console.log(51, recursiveSearch(51) )
console.log(247, recursiveSearch(247) )

I obviously can't return two different things from a function, but if I don't return, I can't branch out in my search:
  if (n > 1) {
    recursiveSearch( n-5 )
    recursiveSearch( n/3 )
  }

That just produces undefineds.

A: Okay, apparently the answer is quite obvious : )
Use an or statement.
if (n > 1) {
  return recursiveSearch( n-5 ) || recursiveSearch( n/3 )
}


text:
Q: On the length of a zero dimensional locally complete intersection scheme. Let, $X$ be a nonsingular closed subscheme in $\mathbb{P}^{n}$(Over an algebraically closed field $\mathbb K$ of characteristic $0$) and $Y$ be a locally complete intersection of $X$.
We know that the length of a closed subscheme $Y$ is defined as dimension of the $\mathbb K$ vector space $\mathcal O_Y(Y)$.
At this point my question is :Is it true that if in the above situation $Y$ is a zero dimensional scheme,then length($Y$) = $|Y|$?
(Here, $|Y|: =$cardinality of $Y$).
I know that if a subscheme is  a finite collection of $d$ distinct point in projective space  then it has degree $d$,but I don't see how to extend it in case of length.
Any help from anyone is welcome.


text:
Q: HTML5, CSS background-image display problem in IE I have scoured the stack-overflow quite a bit, and all solutions relevant to this aren't fixing my problem.
So I've been trying to load a background-image onto the figure element.  This works in firefox, chrome, opera, and safari...but of course IE9/8/7 is messing with my head.

with the styles of
figure#mainlogo {
  background: url(../images/logocrop.png) no-repeat center;
}

I have tried using a div instead of a figure, setting it as display block, getting rid of the id, and almost everything I can find on the net.  Additionally, I've tried separating it out into the separated css styles of background-color, background-image, etc.
I didn't post the rest of the code because this doesn't work even when I separate it out into a separate html file with an inline style it still doesn't show up
<!DOCTYPE html>

I've also tried the other doctypes just to make sure it wasn't that either.  When I set a background color ahead of it, it the color will show.  Anyhow, i have a feeling that this is going to wind up being something fairly obvious and/or easy...Thanks in advance and sorry for the pestering if it's been figured out.

A: You could use HTML5 Shiv in order to make IE<9 recognize new elements.
Just add this to your HEAD.

A: I wrote like that and it worked on IE 9 without any problems (I changed image name for me):
<!DOCTYPE html>

A: Internet Explorer can't style a figure element (it's not supported in most versions).  I'm not sure about the newest version of IE though, it may work on there.

A: I've gotten it to work but it seems the only way IE will recognize the figure is to first create the element using document.createElement("figure") and also REMOVE the id. It will style with css just targeting the figure but it freaks out if there is an id present. An example of what I did is here:http://jsfiddle.net/pdq7u/5/ and documentation is here:http://ejohn.org/blog/html5-shiv/.

Note you also need to have it display block so IE doesn't treat it as an inline element.


text:
Q: p:selectCheckboxMenu filterMatchMode not showing I have this code:
<div class="p-col-12">
    <p:outputLabel for="tripType" value="Testing new title"/>
        <p:selectCheckboxMenu id="tripType"
                              value="#{analyticsController.selectedNewTripType}"
                              label="Cities"
                              filter="true"
                              filterMatchMode="in"
                              panelStyle="width:250px">
                                   <f:selectItems value="#{analyticsController.newTripType}" />
        </p:selectCheckboxMenu> </div>

And the controller is:
private String[] selectedNewTripType;
    private List<String> newTripType;

    @PostConstruct
    public void init() {
        newTripType = new ArrayList<String>();
        newTripType.add("Miami");
        newTripType.add("London");
        newTripType.add("Paris");
        newTripType.add("Istanbul");
        newTripType.add("Berlin");
        newTripType.add("Barcelona");
        newTripType.add("Rome");
        newTripType.add("Brasilia");
        newTripType.add("Amsterdam");
    }

    public String[] getSelectedNewTripType() {
        return selectedNewTripType;
    }

    public void setSelectedNewTripType(String[] selectedNewTripType) {
        this.selectedNewTripType = selectedNewTripType;
    }

    public List<String> getNewTripType() {
        return newTripType;
    }

I used like describe in the documentation https://www.primefaces.org/showcase-v8/ui/input/checkboxMenu.xhtml but this is the result:
This is the result
Now I need somithing like this:
This is I need
And I don't know what happened, why doesn't it show even an error?
Could you help me please?
I am using PrimeFaces v8


text:
Q: SlidingDrawer rotation using onConfigurationChanged I found an Android bug that is giving me a lot of headaches.
Activity on Manifest:
<activity
        android:name=".ActivityTest"
        android:configChanges="orientation"
        android:label="@string/app_name" />

Layout:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="TEST" />

<SlidingDrawer
    android:id="@+id/drawer"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:content="@+id/content"
    android:handle="@+id/handle"
    android:orientation="vertical" >

    <ImageView
        android:id="@id/handle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:id="@id/content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <Button
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Big Big Button" />
    </LinearLayout>
</SlidingDrawer>

Now.. grab the handle of the drawer, and move it to middle and maintain the finger while rotating the device...
The drawer dimentions get all screwed... until it gets completely opened.

Someone has any ideia of how to fix it? I'm trying to look at the SlidingDrawer opening code to check why it gets ok when opened..but no luck yet.
Not handling rotation on my own is not an option that I'm willing to opt-in right now...

A: I've never worked with sliding drawers, so I'm just going to throw an idea out here and maybe it sticks to the wall.
What if whenever onConfiguration is called, you get the width of the scren and set the layout_width of the sliding drawer to that value? It looks like when you stop half way and rotate the screen, that the width (after the rotation), is the same as the width before the rotation. Maybe if you explicitly set the width, it will expand properly.

A: Ok, managed to fix it with some tricks... the touch events sometimes don't get to the views after rotating with the Drawer half opened...
First I extended the Drawer and then: added some code to some methods:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
    if (mTracking && !rotationStopTracking)
    {
        return;
    }
    else if (rotationStopTracking)
    {
        rotationStopTracking = false;
         if (isMoving())
        {
            animateOpen();
            close();
        }else{
            animateOpen();
        }
    }

    ...

   }

//Called from Activity onConfigurationChanged
public void enableRotationResize()
{
    if (mTracking)
    {
        mTracking = false;
        rotationStopTracking = true;
    }
}


text:
Q: 2D array will compile without printing results For some reason my 2D array will compile and take inputs, but will not actually print the array. It is supposed to be able to print the Array forward and backward, but nothing shows up. Please help!
import java.util.Scanner;
public class Assignment7 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("input row and column dimensions with a space separating them:");
        int[][] array = new int[scan.nextInt()][scan.nextInt()];  // scans input for array dimensions

        for(int row = 0; row < array.length; row++) //row
        {
            for(int col = 0; col < array[row].length; col++) //column
            {
                array[row][col] = scan.nextInt();
            }
        }
        System.out.println("Array forward");

        for(int row = 0; row < array.length; row++){
            for(int col = 0; col < array[row].length; col++){
                // print number followed by a space
                System.out.print(array[row][col] + " ");
            }
            System.out.println();
        }
        System.out.println("Array backwards");
        for(int row = array.length-1; row >= 0; row--){
            for(int col = array[row].length-1; col >= 0; col--)
            {
                System.out.print(array[row][col] + " ");
            }
            System.out.println();
        }

    }

}

A: After entering the dimensions you also have to enter values for the array. After that I get this output:
input row and column dimensions with a space separating them:
3 2
1 2 3 4 5 6
Array forward
1 2
3 4
5 6
Array backwards
6 5
4 3
2 1

So it seems to work fine. :)


text:
Q: Send audio over input stream like if I'm speaking with microphone I would like to send a sound over my input device: I don't want to play it, I just want that it "looks like" I'm talking with my microphone but instead I'm playing something like a wav file on that stream.
This because I would like to send audio indepentently from what application I'm using to talk with my friends (so it doesn't matter if I'm using skype/teamspeak/ventrilo and so on).
Is it possible? How to do something like this?

A: There is already a question like this with an answer that fits mine too:
How to Play a sound file on line-in (Microphone)?
Hopefully this will help others too, if a mod wants can close the question, sorry and thanks.


text:
Q: High Availability for OTRS I need to setup high availability for OTRS or say, i want a backup server which comes up when the main server goes down or a a different server that perform few tasks and the main server performs all other tasks. Please suggest how can i do it?

A: You can achieve this by Master-Slave configurations in MySQL...so with this when the Master server goes down, the Slave will serve your request.
Let me know if you have any more questions.


text:
Q: How to cover the catch block for after insert Trigger? When you create a Barrel, a Filling is also created. Is there any chance to make a fake error in unit test between Barrel and Filling to crush the upsert process and cover the catch block?
Helper:
public void insertFilling(List<Barrel__c> createdBarrels){
List<Filling__c> fillingsToInsert = new List<Filling__c>();
for(Barrel__c barrel : createdBarrels){
    if(barrel.FinishDateTime__c >= Date.TODAY()){
        fillingsToInsert.add(
            new Filling__c(Barrel__c = barrel.Id, Barrel_ExternalID__c = barrel.Id)
        );
    }
}
if(!fillingsToInsert.isEmpty()){
    try{
        upsert fillingsToInsert Barrel_ExternalID__c;
    //I want to cover this part:
    } catch(Exception e){
        //email error notification
    }
}
}

Trigger:
trigger BarrelTrigger on Barrel__c (after insert) {
  TriggerHelper helper = new TriggerHelper();
  helper.insertFilling(Trigger.new);
}

Test:
    @isTest static void testBarrelInsertException(){
    Barrel__c barrel = new Barrel__c(
        Name = 'TestBarrel',
        Opportunity__c = null, //required field
        FinishDateTime__c = DateTime.NOW().AddDays(1)
    );
    //But I even can't insert it. I'm getting the 'REQUIRED_FIELD_MISSING' error:
    insert barrel;
    //And still no coverage.
}

A: The only way to cover a catch is if you cause your code inside the try to fail.
In your case you should get rid of the try/catch because it will never fail (or, let's say you introduce a new validation rule on the Filling it will always fail and you will need to change the trigger).
There another good answer that discuss the benefits of catching: When do we really need try/catch?


text:
Q: Disable directon aware hover on mobile I am trying to disable the direction aware hover effect when browsing my website on mobile devices and just display an overlay div with like 30% of the image height. Here is the effect that I am using http://tympanus.net/codrops/2012/04/09/direction-aware-hover-effect-with-css3-and-jquery/
Thanks in Advance

A: If anyone needs this, I fixed it by adding a window width check when the page is loaded. It doesn't work on page resize though. Hover Effect works only if the window width is above 768px.
$(document).ready(function() {
            if($(window).width() > 768){
                $(function() {

                $(' #da-thumbs > div > div > li ').each( function() { $(this).hoverdir(); } );

        });
        }
    });


text:
Q: Allowing user to input into a text file How can I create a program that allows a user to input some numbers into a text file, then from the text file randomly selects the numbers in Python 3.0
So far I've tried this:
input1 = input("Input: ")
input2 = input("Input: ")
file = open("text file", "w")
file.write("\n".join((input1,input2,)))
file.close()

That is what I have so far but I am looking for a possible way for the user to be able to input an unlimited amount of inputs.

A: import random
# Writing part:
user_input = []
while True:
    i = input('Enter your number. For end press enter:')
    if not i:
        break
    else:
        user_input.append(i)

f = open('user.txt', 'w')

for number in user_input:
    f.write(number+'\n')

f.close()

# Reading part:
numbers = []
f = open('user.txt', 'r')

for line in f:
    numbers.append(line)

f.close()

print(random.choice(numbers))


text:
Q: In Quickblox, how can we rotate a video (90 degrees, for example) in Android app (QBRTCSurfaceView)? We are streaming a video chat using Quickblox and we'd like to be able to rotate it (90, 180, 270 degrees).
In the iOS SDK this seems possible, but with Android there doesn't seem to be a setting. How can we get around this and display the video rotated? Thanks!

A: You can use a View method : void setRotation (float rotation) like below :
your_vide_view.setRotation(90f);
or
your_vide_view.setRotation(180f);
or
your_vide_view.setRotation(270f);

this method work for sdk >15
you should also add this condition :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            your_vide_view.setRotation(180f);
        }

A: This may be too late, but for anyone wondering how to rotate the video view, you can get the video track and call addSink() function to retrieve each frame. You can then rotate the frames and call onFrame() function on the videoview. Please find the sample code below.
Remove any renderers before adding the below code and also do not add any renderers because the below code will do that.
 localVideoTrack?.track?.addSink { videoFrame->
            localVideoView.onFrame(VideoFrame(videoFrame.buffer, 90, -1))
        }