text:
Q: COM Runtime Breakdown in Multithreaded Server Application We are experiencing intermittent catastrophic failures of the COM runtime in a large server application.
Here's what we have:
A server process running as a Windows service hosts numerous free-threaded COM components written in C++/ATL. Multiple client processes written in C++/MFC and .NET use these components via cross-procces COM calls (incl .NET interop) on the same machine. The OS is Windows Server 2008 Terminal Server (32-bit).
The entire software suite was developed in-house, we have the source code for all components. A tracing toolkit writes out errors and exceptions generated during operation.
What is happening:
After some random period of smooth sailing (5 days to 3 weeks) the server's COM runtime appears to fall apart with any combination of these symptoms:

*

*RPC_E_INVALID_HEADER (0x80010111) - "OLE received a packet with an invalid header" returned to the caller on cross-process calls to server component methods

*Calls to CoCreateInstance (CCI) fail for the CLSCTX_LOCAL_SERVER context

*CoInitializeEx(COINIT_MULTITHREADED) calls fail with CO_E_INIT_TLS (0x80004006)

*All in-process COM activity continues to run, CCI works for CLSCTX_INPROC_SERVER.

*The overall system remains responsive, SQL Server works, no signs of problems outside of our service process.

*System resources are OK, no memory leaks, no abnormal CPU usage, no thrashing

The only remedy is to restart the broken service.
Other (related) observations:

*

*The number of cores on the CPU has an adverse effect - a six core Xeon box fails after roughly 5 days, smaller boxes take 3 weeks or longer.

*.NET Interop might be involved, as running a lot of calls accross interop from .NET clients to unmanaged COM server components also adversely affects the system.

*Switching on the tracing code inside the server process prolongs the working time to the next failure.

Tracing does introduce some partial synchronization and thus can hide multithreaded race condition effects. On the other hand, running on more cores with hyperthreading runs more threads in parallel and increases the failure rate.
Has anybody experienced similar behaviour or even actually come accross the RPC_E_INVALID_HEADER HRESULT? There is virtually no useful information to be found on that specific error and its potential causes.
Are there ways to peek inside the COM Runtime to obtain more useful information about COM's private resource pool usage like memory, handles, synchronization primitives? Can a process' TLS slot status be monitored (CO_E_INIT_TLS)?

A: We are confident to have pinned down the cause of this defect to a resource leak in the .NET framework 4.0.
Installations of our server application running on .NET 4.0 (clr.dll: 4.0.30319.1) show the intermittent COM runtime breakdown and are easily fixed by updating the .NET framework to version 4.5.1 (clr.dll: 4.0.30319.18444)
Here's how we identified the cause:
Searches on the web turned up an entry in an MSDN forum: http://social.msdn.microsoft.com/Forums/pt-BR/f928f3cc-8a06-48be-9ed6-e3772bcc32e8/windows-7-x64-com-server-ole32dll-threads-are-not-cleaned-up-after-they-end-causing-com-client?forum=vcmfcatl
The OP there described receiving the HRESULT RPC_X_BAD_STUB_DATA (0x800706f7) from CoCreateInstanceEx(CLSCTX_LOCAL_SERVER) after running a COM server with an interop app for some length of time (a month or so). He tracked the issue down to a thread resource leak that was observable indirectly via an incrementing variable inside ole32.dll : EventPoolEntry::s_initState that causes CCI to fail once its value becomes 0xbfff...
An inspection of EventPoolEntry::s_initState in our faulty installations revealed that its value started out at approx. 0x8000 after a restart and then constantly gained between 100 and 200+ per hour with the app running under normal load. As soon as s_initState hit 0xbfff, the app failed with all the symptoms described in our original question. The OP in the MSDN forum suspected a COM thread-local resource leak as he observed asymmetrical calls to thread initialization and thread cleanup - 5 x init vs. 3 x cleanup.
By automatically tracing the value of s_initState over the course of several days we were able to demonstrate that updating the .NET framework to 4.5.1 from the original 4.0 completely eliminates the leak.


text:
Q: I want to set time to visible message with AWS SQS I have a use case where I am reading the time from DB in every 30mins and if found time to be executed in next 30mins I put in a AWS SQS.
Example- I am running cron every 30 mins with lambda that reads schedule_at from DB. And find tasks which needs to be execute in next 30mins I put it in a AWS SQS queue;
Like the cron run time is 11:30 and the tasks is scheduled at 11:16. I want to add them to queue and only execute it when 11:16 time(which is schedule_at it would be different for every tasks).
Here I want to set the time to execute the message, or visible only when time schedule_at time and at that time it will trigger another lambda to deal with business logic.
I am not sure how to solve this using what attribs of AWS SQS, Can any one help me with this?

A: You can delay message visibility for up to 15 minutes.
Since you don't specify what SDK you're using, here's the API doc; look at DelaySeconds. And note that it only works for a "standard" SQS queue, not a FIFO queue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regression loop: several dep variables & several indep variables, one of these indep variables takes different values according to the dep variable I have several dependent variables (let's call them dep1, dep2 and dep3) and I want to regress several independent variables on them. I have the independent variables a,b and c which I always want to include in the regression. However the independent variables d1, d2, d3 should only be used when the number matches the number of the dependent variable. This is:
lm(dep1 ~ a + b + c + d1)
lm(dep2 ~ a + b + c + d2)
lm(dep3 ~ a + b + c + d3)

To be more exact, both my dependent and independent variables are a monthly time series (xts object). I merged the dependent variables to get the matrix "dep". a,b,c,d1,d2 and d3 are stored in the matrix "indep".
Is it possible to create a loop which does this automatically?

A: We can use paste
v1 <- paste0("dep", 1:3)
v2 <- paste0("d", 1:3)
v3 <- paste(v1, paste(paste(letters[1:3], collapse=" + "), v2, sep=" + "), sep="~")
lapply(v3, function(x) lm(x))


text:
Q: How do i execute these javascript module patterns? I had learnt to structure modules using IIFEs. Simple example:
export test_module = (function{
    var name = "henry";
    var age = 26;
    var height ="6 monthe";

    var getHeight = function()
    {
        return height;
    }

    return{
        getHeight : getHeight
    }
}());

In another file I have
import {test_module} from './test_module'

I would like to learn to import and export IIFE modules using ECMAScript 6 module exports and imports. I installed Babel the transpiler. But when I export my module and try to import it in another file I get an error saying:
 (function (exports, require, module, __filename, __dirname) { import {text_module} from './test_module'
                                                                 ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)

What is my problem ? Do I have a wrong syntax?

A: You have a syntax error, as Babel reports. Instead of
export test_module =

you must say
export const test_module =

Anyway, ES6 modules make the old IIFE-style "modules" obsolete (pretty much). Just write
// my-module.js

export function getHeight() {
    var name = "henry";
    var age = 26;
    var height = "6 monthe";

    return height;
}

Or, if you prefer
function getHeight() {
    var name = "henry";
    var age = 26;
    var height = "6 monthe";

    return height;
}

export { getHeight };

Then, when you want to use it:
import { getHeight } from './my-module';

getHeight();

or
import * as myModule from './my-module';

myModule.getHeight();

As for your rant about classes, I don't understand what it has to do with your question. If you don't like classes in ES6, then don't use them. Classes have nothing to do with ES6 modules, other than the obvious fact that like any other values classes can be exported and imported.


text:
Q: Issues using jQuery UI and html2canvas plugins I have few issues in using jQuery UI and html2canvas plugins.
Please look into the jsfiddle and the jQuery code below.
http://jsfiddle.net/fX262/7/
$(function () {
    $(".borrd-create-prod li a img").draggable({
        revert: "invalid",
        helper: "clone",
        cursor: "move"
    });

    $(".borrd-item").droppable();

    $("#borrd-droppable").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: ".borrd-create-prod li a img",
        drop: function (event, ui) {
            $(this).append(ui.helper.clone());
            $("#borrd-droppable img").addClass("borrd-item");
            $(".borrd-item").draggable({
                stack: ".borrd-item"
            });
            $(".borrd-item").droppable({
                containment: "#borrd-droppable"
            });
            /*ui.helper.clone().resizable({
          animate: "true"
       });*/
            $(".borrd-item").each(function (i) {
                $(this).attr("id", "prod_img_" + i);
            });

            $(".borrd-item").droppable({
                containment: "#borrd-droppable"
            });

            $(this).find(".placeholder-txt").remove();
        },
    });

    $(".borrd-drop img").resizable({
        handles: "n, e, s, w, sw, ne, nw, sw",
        animate: "true"
    });

    $(".borrd-right").tabs({
        hide: {
            effect: "fade",
            duration: "fast"
        }
    });
});

$(function() {
    $( "#submitBorrdImg" ).click(function() {
        html2canvas($("#borrd-droppable"), {
            onrendered: function (canvas) {
                var canvasImg = canvas.toDataURL("image/jpg");
                $("#canvasImg").html('<img src="'+canvasImg+'" alt="">');
                /*window.open(canvasImg);*/
            }
        });
    });
});

*

*Why when I drop the images from the right side to the left side container, the images position weirdly below than desired position?

*Why I couldn't resize the dropped images?

*If I click "Post" button, a screenshot of contents in "#borrd-droppable" div should be generated and displayed in "#canvasImg" div. But why nothing happens?

I need this to be compatible to Firefox 28, Google chrome 32, and if possible IE 8.
Any kind of help would be greatly appreciated.
EDIT :
Resizable now works by adding $(".borrd-item").resizable(); inside drop: function (event, ui) {} and adding corresponding jQuery UI CSS. But after you drag and drop in the left side, it doesn't drag anymore. Can anyone throw some light on this problem?
http://jsfiddle.net/fX262/9/

A: Finally, drag, drop and resize works even with forward, backward and remove buttons!
http://jsfiddle.net/fX262/11/
http://jsfiddle.net/fX262/11/embedded/result/
Applying resize on img tag didn't work. Only on block elements it works. So I wrapped img tag in a block element and applied jQuery UI on it.
Also adding IDs to clones and verifying them did the trick like this:
if ($(ui.draggable)[0].id !== "") {
    x = ui.helper.clone();
    ui.helper.remove();
    x.addClass("borrd-item");
    x.draggable({
        helper: 'original',
        containment: '#borrd-droppable',
        tolerance: 'fit',
        start: function (event, ui) {
            $(this).css("z-index", a++);
        }
    });
}

Is this a bug in jQuery UI itself?
Right now the other issues are:

*

*Why when we drag and drop images to the left side, images position far below than the actual position? I removed all paddings and margins on the elements like inputs and div containers above "borrd-droppable" div. The images now position less below than before. So I think this is some kind of CSS issue.

*When overlapping images, if we click forward few times on one image, it's z-index is increased to far more than other images. Now if that image has to go backward, we have to click few more times. Instead of that can it be made to move backward to the next image in just one click?

*canvas2html also works but only in Firefox. Not it Google Chrome. I even tried $(window).load function. Doesn't work. Know why?
Btw, even though I post the code and description this question didn't get a single reply. It is demotivating for a newbie like me in Stack Overflow.


text:
Q: Is it possible to convert this map/filter code into list comprehension? I have a list of regular expressions I want to run over a single string. I don't care which expressions matched, I just want their results (re.Match objects).
Of course it's easy with the for loop, but I wanted something more pythonic. This is what I've got now:
all_matches = map(lambda x: x.match(domain),
                  (first_re, second_re, third_re))
matches = [m for m in all_matches if m]

I feel under my skin, though, that it should be doable as a single comprehension. How should it look like, if it's possible at all?
Also, more generally - are list comprehensions equivalent to map/filter or do they just have a subset of m/f capabilities?

A: It is possible to write this as a simple list comprehension. However, the r.match(domain) will have to be evaluated twice:
matches = [r.match(domain) for r in (first_re, second_re, third_re) if r.match(domain)]

Or you will have to write a double list comprehension:
matches = [a for a in (r.match(domain) for r in (first_re, second_re, third_re)) if a]

A: In general, filter/map can be written as a list comprehension (see the documentation on this point). In this case, you can write matches = [x.match(domain) for x in (first_re, second_re, third_re) if x.match(domain)].


text:
Q: Allow one gocron at a time I have the following code snipped which schedules the job to be run after the specified seconds:
import (
    "github.com/jasonlvhit/gocron"
)

// ScheduleCron schedules job running at specified JobInterval
func (cron CronJob) ScheduleCron() {
    gocron.Every(uint64(120)).Second().Do(cron.run)
    <-gocron.Start()
}

func (cron CronJob) run() {
    fmt.Println("Cron Scheduled")
    cron.job.Run()
}

This runs the job every 2 minutes. However, I want the job to only run if the previous job has finished. In other words, only 1 job should be running at a time and preferably the next scheduled job should run 2 minutes after the previous job was completed. Is there any way to do that?
The library defines MAXJOBNUM const with value 10000, would it be right to set it to 1?

A: This is a bit old question.Still thought of answering since I came across.
The SingletonMode() can be set for the purpose. As the comment says, the SingletonMode prevents a new job from starting if the prior job has not yet
completed it's run


text:
Q: Beautiful soup, only part of the data is scraped I am trying to scrape data from the shareholding disclosures page from the Hong Kong Exchange yet when I find all ('TR'), my code only grabs the previous balance no of shares rather than the whole tr line including the name and ticker.
url = "https://di.hkex.com.hk/di/summary/DSM20220218C1.htm"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
result =soup.find('table', id="Table3")

for stock in result:
    rows = stock.find('tr')
    print(rows)


text:
Q: Парсинг json данных с конфигурации, php json Входные данные:
config = 3
config_b.items = item1
config_b.items = item2
config_b.items.named_item = 123
config_c.root.a.b.c = 13

Как в итоге должно быть:
{"config":3,
 "config_b": {
   "items":{
     "0":"item1",
     "1":"item2",
     "named_item":123
   }
 }, "config_c": {
   "root": {
     "a": {
        "c":13
       }
     }
   }
 }

Это то, что получилось у меня:
$input = '
config = 3
config_b.items = item1
config_b.items = item2
config_b.items.named_item = 123
config_c.root.a.b.c = 13';

$output = [];
$back_slash_exploded = explode("\n", $input);
foreach ($back_slash_exploded as $item) {
    if ($item) {
        $exploded = explode(' = ', $item);
        $dot_exploded = explode('.', $exploded[0]);

        $output[$dot_exploded[0]] = [];
        foreach ($dot_exploded as $new_key) {
            create_array($output, $new_key, $dot_exploded[0]);
        }
    }
}

function create_array(&$output, $new_key, $prev_key) {
    if (!isset($output[$new_key])) {
        foreach ($output as $key => $value) {
            if ($key == $prev_key) {
                $output[$prev_key][$new_key] = [];
            } else {
                create_array($output[$key], $new_key, $prev_key);
            }
        }
    }
}

var_dump($output);
  array(3) {
  ["config"]=>
  array(0) {
  }
  ["config_b"]=>
  array(2) {
    ["items"]=>
    array(0) {
    }
    ["named_item"]=>
    array(0) {
    }
  }
  ["config_c"]=>
  array(4) {
    ["root"]=>
    array(0) {
    }
    ["a"]=>
     array(0) {
    }
    ["b"]=>
    array(0) {
    }
    ["c"]=>
    array(0) {
    }
  }
}


text:
Q: TS2307: Cannot find module 'express' I am just getting started with TypeScript and I am not sure why I am seeing this error in my IDE(Webstorm).
"TS2307:Cannot find module 'express'"
import express = require("express");

I have uninstalled/installed back the typescript globally and still see the error. I used the following tutorial as a starting point
http://www.vandiest.biz/?p=3931
Currently, I am blocked and not sure how to proceed forward with this solution. Also I have tried recommendations on some other posts regarding the same error, but with no luck.

A: The comments to your question by @Saravana and @domdambrogia are both correct.
Firstly the syntax is incorrect. It should be:
import express from 'express';

Secondly you need to install the typing:
npm install @types/express --save-dev

A:
You need to install express.js

npm i @types/express

A: if this is failing for a nested node_module, update tsconfig.json with -

"skipLibCheck": true


text:
Q: Will wait and waitpid block SIGCHLD and unblock it when they return in Linux? Here is my code to examine this:
void handler(int n) {
    printf("handler %d\n", n);
    int status;
    if (wait(&status) < 0)
        printf("%s\n", strerror(errno));
}

int main() {
    struct sigaction sig;
    sigemptyset(&sig.sa_mask);
    sig.sa_handler = handler;
    sig.sa_flags = 0;
    sig.sa_restorer = NULL;
    struct sigaction sigold;
    sigaction(SIGCHLD, &sig, &sigold);
    pid_t pid;
    int status;
    printf("before fork\n");
    if ((pid = fork()) == 0) {
        _exit(127);
    } else if (pid > 0) {
        printf("before waitpid\n");
        if (waitpid(pid, &status, 0) < 0)
            printf("%s\n", strerror(errno));
        printf("after waitpid\n");
    }
    printf("after fork\n");
    return 0;
}

The output is:

before fork
before waitpid
handler 17
No child processes
after waitpid
after fork

So, I think waitpid will block SIGCHLD and wait for child to terminate, once the child terminates, it will do something and the unblock the SIGCHLD before it returns, that's why we see "No child processes" error and "after waitpid" is after "handler 17", am I right? if not, what is the truth? How to explain the output sequence? Is there a specification for Linux or something like that to check?

A: The exit information for a process can only be collected once.  Your output shows the signal handler being called while your code is in waitpid(), but the handler calls wait() and that collects the information of the child (which you throw away without reporting).  Then when you get back to waitpid(), the child exit status has been collected, so there's nothing left for waitpid() to report on, hence the `no child processes' error.
Here's an adaptation of your program.  It abuses things by using printf() inside the signal handler function, but it seems to work despite that, testing on a Mac running macOS Sierra 10.12.4 (compiling with GCC 7.1.0).
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

static void handler(int n)
{
    printf("handler %d\n", n);
    int status;
    int corpse;
    if ((corpse = wait(&status)) < 0)
        printf("%s: %s\n", __func__, strerror(errno));
    else
        printf("%s: child %d exited with status 0x%.4X\n", __func__, corpse, status);
}

int main(void)
{
    struct sigaction sig = { 0 };
    sigemptyset(&sig.sa_mask);
    sig.sa_handler = handler;
    sig.sa_flags = 0;
    sigaction(SIGCHLD, &sig, NULL);
    pid_t pid;
    printf("before fork\n");
    if ((pid = fork()) == 0)
    {
        _exit(127);
    }
    else if (pid > 0)
    {
        printf("before waitpid\n");
        int status;
        int corpse;
        while ((corpse = waitpid(pid, &status, 0)) > 0 || errno == EINTR)
        {
            if (corpse < 0)
                printf("loop: %s\n", strerror(errno));
            else
                printf("%s: child %d exited with status 0x%.4X\n", __func__, corpse, status);
        }
        if (corpse < 0)
            printf("%s: %s\n", __func__, strerror(errno));
        printf("after waitpid loop\n");
    }
    printf("after fork\n");
    return 0;
}

Sample output:
before fork
before waitpid
handler 20
handler: child 29481 exited with status 0x7F00
loop: Interrupted system call
main: No child processes
after waitpid loop
after fork

The status value 0x7F00 is the normal encoding for _exit(127).  The signal number is different for macOS from Linux; that's perfectly permissible.

To get the code to compile on Linux (Centos 7 and Ubuntu 16.04 LTS used for the test), using GCC 4.8.5 (almost antediluvian — the current version is GCC 7.1.0) and 5.4.0 respectively, using the command line:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes \
>     -Wstrict-prototypes -Wold-style-definition sg59.c -o sg59
$

I added #define _XOPEN_SOURCE 800 before the first header, and used:
struct sigaction sig;
memset(&sig, '\0', sizeof(sig));

to initialize the structure with GCC 4.8.5.  That sort of shenanigan is occasionally a painful necessity to avoid compiler warnings.  I note that although the #define was necessary to expose POSIX symbols, the initializer (struct sigaction sig = { 0 };) was accepted by GCC 5.4.0 without problems.
When I then run the program, I get very similar output to what cong reports getting in a comment:
before fork
before waitpid
handler 17
handler: No child processes
main: child 101681 exited with status 0x7F00
main: No child processes
after waitpid loop
after fork

It is curious indeed that on Linux, the process is sent a SIGCHLD signal and yet wait() cannot wait for it in the signal handler.  That is at least counter-intuitive.
We can debate how much it matters that the first argument to waitpid() is pid rather than 0; the error is inevitable on the second iteration of the loop since the first collected the information from the child.  In practice, it doesn't matter here.  In general, it would be better to be using waitpid(0, &status, WNOHANG) or thereabouts — depending on context, 0 instead of WNOHANG might be better.


text:
Q: How to find a relation when given the distinct equivalence classes? For example

I am not sure how to approach this type of problem. I know that the equivalence classes partition $A$.
Suppose $[a]= \{1,4,5\}$, $[b]=\{2,6\}$ and $[c]= \{3\}$. $[a]\bigcap[b]= \emptyset$ and $[b]\bigcap [c]=\emptyset$, but I have no idea how to find the relation as a subset of $A \times A$.

A: $A \times A$ is the Cartesian product of $A$ with itself.  On a smaller set, it might be easier to see what this means. So, let $B = \{1,2,3\}$
$B \times B = \{ (1,1), (1,2), (1,3),(2,1), (2,2), (2,3),(3,1),(3,2),(3,3)\}$
So, a subset of this would be $ \{(1,1),(2,2),(3,3)\}$ for instance.
For your question, we know the equivalence classes, which means that if two elements $a,b$ are in the same equivalence class, then $aRb$ and $bRa$.  Note: $a$ can equal $b$, so you always have $aRa$ in an equivalence relation.
So, for the equivalence class $\{2,6\}$, you will have $\{(2,2),(2,6),(6,2),(6,6)\}$ as part of the relation.
You simply need to do the same operation for the rest of the equivalence to define your relation $R = \{(1,1),(1,4),(1,5),...\}$.  They are simply asking for you to write your answer as a set of points as opposed to listing a function or using $aRb$ notation.


text:
Q: why not display error message in php? This is my php code for connecting database:
config.php:
<?php
ob_start();
error_reporting( E_ALL & ~E_NOTICE);
require_once("constants.php");
if (version_compare(PHP_VERSION, 5.3, '<') && function_exists('set_magic_quotes_runtime')) set_magic_quotes_runtime(0);
$currentPage = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
$conn=mysql_connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD) or die("sorry! could not connect
".mysql_error()."");
if($connn) {
mysql_select_db(DB_DATABASE) or die("sorry! could not connect with database
".mysql_error()."");
}
?>

constants.php:
<?php
define('HTTP_SERVER', 'http://localhost');
define('SITE_DIR', '/selva/');
define('DB_PREFIX', 'mypage1_');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'vkls8');
define('SITE_NAME', 'selva');
define('TABLE_PAGES', DB_PREFIX.'pages');
define('TABLE_TAGLINE', DB_PREFIX.'tagline');
?>

index.php:
<?php
require("libs/config.php");
?>

Now i have entered incorrect database name. but when run this code, it shows nothing. May i know why?. It needs to display 'could not connect with database' right?.. May i know is there any missing in my code.
Can anybody fix this? Thanks in advance.

A: try using this..
index.php:
<?php
require("libs/config.php");
$output = ob_get_contents();
ob_end_clean();
echo $otuput;
?>

OR comment out ob_start();


text:
Q: Cypher path needs to exclude a certain relation I have this graph:
A-[:X]->B-> a whole tree of badness
A-[:Y]->C-> a whole tree of goodness

I would like to know how to specify a path starting with A that excludes the :X relationship.
In this case "Y" could be any one of a number of different edge types. I do not want to specify them explicitly.
How do I write a path statement that includes A-[*]-B where * is not :X but can be anything else?

A: Solution for a fixed number of relationships between A and B
You can exclude a relationship type by matching all relationships from A to B and then filter out a specific type with WHERE NOT
MATCH p = (a:Label1)-[]-(b:Label2)
WHERE NOT (a)-[:X]-(b)
RETURN p

Solution for a variable length path between A and B
If you have a variable length path between A and B you cannot put the exact pattern in the WHERE NOT. Instead, you can use a NONE predicate on the path:
MATCH p = (a:Label1)-[*]-(b:Label2)
// this WHERE makes sure that none of the relationships in the
// returned path fulfill the criterion type(relationship) = 'X'
WHERE NONE (r in relationships(p) WHERE type(r) = 'X')
RETURN p

A: This Cypher query is simpler than the variable-length path query from @MartinPreusse, as it avoids using the RELATIONSHIPS function. Profiling shows that its execution plan is also a bit simpler, so it might be faster.
MATCH p=(a:Label1)-[rels*]-(b:Label2)
WHERE NONE (r IN rels WHERE type(r)= 'X')
RETURN p


text:
Q: Condition on Two columns and create third column failed Pandas Python I have the following data and I want to create a new column with certain conditions. See the following:
DataSets:
real,rel
1,0
0,1
1,1
0,1
0,0
0,0
1,1
1,1
0,0
0,1
1,0
1,1
0,1
1,0

The code I tried and the error I received:
>>> import pandas as pd
>>> df = pd.read_csv("test.csv")
>>> df.loc[df["real"]==0 and df["rel"]==0,"out"] = 9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\site-packages\pandas\core\generic.py", line 1576, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I have the condition for the out column as:
when real is 0 and rel is 0, out should be 0
when real is 1 and rel is 1, out should be 1
when real is 1 and rel is 0, out should be 2
when real is 0 and rel is 1, out should be 3
Please let me know what I can do to fulfill the missing part.
I have checked this: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

A: On way is using np.select. You can start by defining the set of conditions:
c1 = (df.real == 0) & (df.rel == 0)
c2 = (df.real == 1) & (df.rel == 1)
c3 = (df.real == 1) & (df.rel == 0)
c4 = (df.real == 0) & (df.rel == 1)

And then you can select among range(4) according to the result of the conditions:
import numpy as np
df['out'] = np.select([c1,c2,c3,c4], range(4))

     real  rel  out
0      1    0    2
1      0    1    3
2      1    1    1
3      0    1    3
4      0    0    0
5      0    0    0
6      1    1    1
7      1    1    1
8      0    0    0
9      0    1    3
10     1    0    2
11     1    1    1
12     0    1    3
13     1    0    2

A: when real is 0 and rel is 0, out should be 0
when real is 1 and rel is 1, out should be 1
when real is 1 and rel is 0, out should be 2
when real is 0 and rel is 1, out should be 3

These cases can be combined into one statement:
df['out'] = df['rel'] + 2*(df['real'] != df['rel'])
print(df)

Output:
    real  rel  out
0      1    0    2
1      0    1    3
2      1    1    1
3      0    1    3
4      0    0    0
5      0    0    0
6      1    1    1
7      1    1    1
8      0    0    0
9      0    1    3
10     1    0    2
11     1    1    1
12     0    1    3
13     1    0    2

A: Hi Below is the answer for you query:
df.loc[(df["real"]==0) & (df["rel"]==0),"out"] = 0
df.loc[(df["real"]==1) & (df["rel"]==1),"out"] = 1
df.loc[(df["real"]==1) & (df["rel"]==0),"out"] = 2
df.loc[(df["real"]==0) & (df["rel"]==1),"out"] = 3

A: One possible solution is create helper DataFrame and merge:
df1 = pd.DataFrame({'real': [0, 0, 1, 1], 'rel': [0, 1, 0, 1], 'new': [0, 1, 2, 3]})
print (df1)
   real  rel  new
0     0    0    0
1     0    1    1
2     1    0    2
3     1    1    3

df = df.merge(df1, how='left')
print (df)
    real  rel  new
0      1    0    2
1      0    1    1
2      1    1    3
3      0    1    1
4      0    0    0
5      0    0    0
6      1    1    3
7      1    1    3
8      0    0    0
9      0    1    1
10     1    0    2
11     1    1    3
12     0    1    1
13     1    0    2

A: You can use numpy.where to conditionally fill columns:
df["new_column"] = np.nan
df["new_column"] = np.where((df["real"]==0) & (df["rel"]==0), 0, df["new_column"])
df["new_column"] = np.where((df["real"]==1) & (df["rel"]==1), 1, df["new_column"])
# ... etc. through the rest of your conditions.


text:
Q: Importing large text file into sql database I read txt files and saving rows from this file to local database.The Problem is that program reads 700 000 rows and it takes long time to read whole file. I use linq to sql, firs I read the row, then i split it in to the Table object and then I submit into DB.
For example The row has format
2014-03-01 00:08:02.380 00000000000001100111

this row is splited into DateTime and 20 columns (each column represents 1 channel (CH1 - CH20))
Is there a better (faster) way?

A: That would be slow with linq to sql submitting that many items.
Bulk insert or Bulk update would be preferable for this task which you can't with linq to sql. See also this post. bulk insert with linq-to-sql
I suggest something else than linq to sql for this task.

A: You can use the FileHelpers http://filehelpers.sourceforge.net/ to feed directly into SqlBulkCopy. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
That is by far the easiest and fastest approach.
You can still use Linq-2-sql for read/non-batch writes but for bulkinsert is is simply too slow.


text:
Q: Would I be able to prove different theorems under different propositional logic systems? I can find many different formulations of propositional logic systems (i.e. the axioms and transformation rules) all that are sound and complete.  Am I correct in understanding that some theorems might be provable (and hence semantically valid) in one system but not in another?
In that case, what is semantically valid really depends on the set of axioms I start with?  I just want to confirm this.  This seems like the case because for example in some formulations of number theory, I cannot prove as many theorems if I don't include axiom of choice.
Thanks!

A: There are two different concept of "logic" in place here.
We have the so-called Classical Logic, with its semantics, and we have many proof systems (Hilbert-style, Natural Deduction, Truth Tree, Sequent Calculs) that are all sound and complete for it.
All proof systems for Classical Logic proves all and only the same valid formulas.
We have Intuitionistic Logic and we have again many proof systems (Hilbert-style, Natural Deduction, Truth Tree, Sequent Calculs) that are all sound and complete for it.
All proof systems for IL proves all and only the intuitionistically valid formulas.


text:
Q: Select based on value of another select I have two tables that like this:
'BUDGET TABLE'
idBudget BudgetDescription  CreateDate  idProject
   1       NameBudget1      09/09/2015     2
   2       NameBudget2      08/07/2015     1
   3       NameBudget3      08/09/2015     1

'ITEMS' the items in every budget
idItem  ItemDescription  Price IdBudget
  1      Item1             10     1
  2      Item2             30     1
  3      Item3             5      2
  4      Item4             130    3
  5      Item5             27     3

And I'm trying to get these kind of results if the USER wants to see the budgets that belong to Project = '1'
-----------------------------------------------
BudgetDescription    CreateDate    Sum(Price) as Total
----------------------------------------------
  NameBudget2        08/07/2015      5
  NameBudget3        08/09/2015     157
-----------------------------------------------

I tried to join these querys:
Select idBudget, BudgetDescripcion, CreateDate
from budget
where idProject='1';

Select sum(price) as total
from Items i
where i.idBudget=idBudget;

like
Select sum(price) from item where idBudget=(select idBudget, BudgetDescription, createdate from Budget where idProject='1');

but thats gives me an error: "Operand shoul contain 1 column"
so I tried and erase the other columns:
Select sum(price) from item where idBudget=(select idBudget from Budget where idProject='1');

and error: Subquery returns more than 1 row
Thank you very much for your help.

A: select
  b.idBudget,
  b.BudgetDescripcion,
  b.CreateDate BudgetCreateDate,
  COUNT(i.idItem) CountItems,
  SUM(i.price) SumItemPrice
from
  budget b
  inner join Items i on i.IdBudget = b.idBudget
where
  b.idProject = 1
group by
  b.idBudget, b.BudgetDescripcion, b.CreateDate;

A: LEFT JOIN is what you seek.
Select b.idBudget, b.BudgetDescripcion, b.CreateDate, sum(i.price) as total
from budget b
LEFT JOIN Items i ON i.idBudget=b.idBudget
where b.idProject='1';


text:
Q: Can I detach a rust thread? The spawn below
fn something() {
    std::thread::spawn(||{
        println!("hello");
    });
}

creates a JoinHandle which is waited until it finishes. This blocks the return of something.
Is there a way to detach this thread in Rust? In this case my JoinHandle isn't Send so I can't keep it around. This is mostly for testing, I'd not leave a thread hanging alone somewhere in my program

A: something is only blocked if you join the thread. Dropping a JoinHandle doesn't join a thread; it detaches it.
spawn's documentation says (emphasis added):

Spawns a new thread, returning a JoinHandle for it.
The join handle provides a join method that can be used to join the spawned thread. If the spawned thread panics, join will return an Err containing the argument given to panic!.
If the join handle is dropped, the spawned thread will implicitly be detached. In this case, the spawned thread may no longer be joined.


text:
Q: Typescript + React: Typing a functional wrapper component that extends a given class component I have a functional component that wraps a class component and passes all but one prop to it:
import React, { Component, ComponentType } from 'react'
import Layout from './components/LayoutComponent'
import { Route } from 'react-router'

type LayoutRouteProps = {
    component: ComponentType,
}

const DashboardLayoutRoute = ({
    component: Component,
    ...rest
}: LayoutRouteProps) => {
    const render = (matchProps: any) => (
        <Layout>
            <Component {...matchProps} />
        </Layout>
    )

    return (
        <Route {...rest} render={render} />
    )
}

How do I import props definition for Route and add them to type LayoutRouteProps?


text:
Q: Altering a continuuous stream of ascii data (amending it with time, for example) I have a sound level meter, which, with the help of the great sigrok-cli, spits out it's reading via the commandline:
# sigrok-cli --driver cem-dt-885x:conn=/dev/ttyUSB1\
--output-format analog --continuous |cut -c 6-12
42.7000
42.5999
42.7000
42.5999
42.5000
(...)

I would like to "amend" this continuous stream of data with a few extra things, most importantly the time of the reading to something like this:
20140111-190800 42.7000
20140111-190800 42.5999
20140111-190801 42.7000
20140111-190801 42.5999
20140111-190802 42.5000
(...)

So far I have tried
# sigrok-cli --driver cem-dt-885x:conn=/dev/ttyUSB1\
 --output-format analog --continuous |cut -c 6-12|\
 (while read r ; do echo "$(date +%Y%M%d-%H%M%S) $r"; done)

but this a) only outputs the data after pressing Ctrl-c and b) does not change the time (ie. it always shows the time from when I started the command).
In a second step I'd like to round the values to only one digit after the decimal, but that's mostly for beautifying the output (but could possibly be done "while we are at it", ie. while the output is handled in some sort anyway:
20140111-190800 42.7
20140111-190800 42.6
20140111-190801 42.7
20140111-190801 42.6
20140111-190802 42.5
(...)

Any help, pointer etc. are, as always, highly appreciated.
Edit 1
The output I get from @AmokHuginnsson 's code:
(...)
43.70 19:58:33
43.50 19:58:33
43.30 19:58:33
43.10 19:58:33
43.00 19:58:33
42.80 19:58:33
42.70 19:58:33
42.50 19:58:34
42.30 19:58:34
42.20 19:58:34
42.10 19:58:34
41.90 19:58:34
41.80 19:58:34
(...)

A: There are two parts to your problem, first you have to disable buffering on program that  outputs data, second you could use something more sophisticated to transform your data, i.e.
stdbuf -o 0 ./a.out | perl -nl -e 'use POSIX; printf ( "%s %.2f\n", strftime( "%Y%m%d-%H%M%S", localtime ), $_ )'

Where ./a.out is some program that outputs one float per line.
I don't have your program so I wrote something to test it with:
[amok@vegeta](2/1)~/$ cat tick.cxx
#include <iostream>
#include <cstdlib>
#include <unistd.h>

using namespace std;

int main( int, char** ) {
        srand( time( NULL ) );
        while ( true ) {
                int d( rand() );
                d || ( d = 1 );
                cout << static_cast<double>( rand() ) / d << "\n";
                sleep( 1 );
        }
        return ( 0 );
}

BTW, stdbuf is part of the GNU Coreutils, it also available on FreeBSD.
You could also use unbuffer program which is part of expect package, i.e.
unbuffer ./a.out | perl -nl -e 'use POSIX; printf ( "%s %.2f\n", strftime( "%Y%m%d-%H%M%S",` localtime ), $_ )

Explaining perl part as per request.
There are two parts that maybe of interest of OP.
First is the line format "%.2f %s\n" which is standard C printf() style format string,
second is time format, again time format is the same format as in C strftime() call.
Just remember to order printf arguments to reflect the order of particular format items.
man 3 printf and man 3 strftime are good references about both functions.


text:
Q: Demo DocuSign Click API - javax.net.ssl.SSLException: Connection reset We're currently integrating with the DocuSign click API and when we call clickapi/v1/accounts/<accountId>/clickwraps?status=active we are seeing intermittent connection issues. We're getting a Connection reset; nested exception is javax.net.ssl.SSLException: Connection reset error. For some background, we also call the /oauth/token API and that call usually succeeds, just not the following call to the click API.

*

*Enabled protocols: [TLSv1.3, TLSv1.2, TLSv1.1, TLSv1]

*Not a rate limiting issue

*This error only occurs when using the demo account, this is not something we've seen using the prod account.

*Running automated tests is usually when we see this issue, when we call the click API a few times in a row

Could someone provide any insight into what the cause might be?
Thanks

A: The only requirements that I'm aware of for our REST Apis are that traffic be sent on a secure channel using a TLS version higher than 1.1. If you're presently using a higher TLS version and are connecting to Demo using https, there's likely something else going on.
You should be able to use a utility like WireShark or Fiddler to capture the network traffic and see what's happening in the background. If you can, try to reproduce this and then send the resulting network log to matt.king@docusign.com and we'll have a closer look.
For Fiddler with Java: https://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigureJavaApp


text:
Q: Black screen on boot after upgrade ubuntu server from 22.04 to 22.04.01 As title says i got a black screen after upgrade my ubuntu server from 22.04 to 22.04.1 upgrade went well without errors, services work as intended i can ssh to server and manage it from there but i got a black screen on my monitor.
Any suggestion on how should I proceed?

A: The solution that work for me was:

Temporary Fix To get the system to boot:

*

*After turning on your PC, hold the right SHIFT key to get to the GRUB
bootloader if your computer uses a BIOS. If your computer uses EFI or
UEFI, continuously tap the "ESC" (escape) key after turning on your
PC.

*Once GRUB is open, press the "e" key to edit the first highlighted
entry "Ubuntu". Move your cursor down to the line that starts with
"linux", and use the right arrow key to find the section with the
words "ro quiet splash".

*Add "nomodeset" after these words.

*Feel free to remove "quiet" and "splash" for more verbosity to
troubleshoot the boot process. Press "CTRL + X" or "F10" to boot.

The system should now boot.
Permanent Fix To permanently resolve the issue:

*

*Once the system has booted using the temporary fix, log in.

*Open a terminal window (Applications -> Terminal, or press the "Start" button and type terminal).

*Either "su" in to root, or use "sudo" to open your favorite text editor and edit the file "/etc/default/grub" (I use nano which can be install by running "apt install nano"):

nano /etc/default/grub

*Locate the line with the variable "GRUB_CMDLINE_LINUX_DEFAULT", and add "nomodeset" to the variables. Feel free to remove "splash" and "quiet" if you'd like text boot. Here's an example of my line after editing (yours will look
different):

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nomodeset"

*Save
the file and exit the text editor (CTRL+X to quit, the press "y" and
enter to save).

*At the bash prompt, execute the following command to
regenerate the grub.conf file on the /boot partition from your new
default file:

update-grub

*Restart your system, it should now boot!

Solution foun on:
https://www.stephenwagner.com/2019/05/05/ubuntu-linux-black-screen-frozen-system-after-upgrade-install/


text:
Q: Meaning of "Redirects are always followed" I was reading a article and got a question.
What does "Redirects are always followed" mean in Comply with Background Transfer Limitations  section?
I'm still learning english, so I have no idea about what the sentence literally means exactly in that context(I do know Redirect, by the way).
And that seems not to be relevant to "background transfer limitation" so far.
Can you explain the sentence with simple scenario or any materials?

A: When a URL is accessed, the server can send a redirect response that indicates that the resource has moved.  For example, if you access http://www.example.com the server may send a redirect response indicating that the url http://example.com should be used.
For non-background URL sessions, the URLSessionDelegate method urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) is called when a redirect response is received.  In this delegate method you can decide whether to follow the redirection, redirect to some other URL or reject the redirection and fail with an error.
For background URL sessions this method is not called and the redirection is always followed.
In this case "Comply with Background Transfer Limitations" means that you cannot rely on any logic in that delegate method; the limitation is that the transfer must work with redirections being followed.


text:
Q: \usemodule and ConTeXt I can't seem to use modules in ConTeXt:
\usemodule[lettri]

\starttext
\lettrine{T}{his is a test}
\stoptext

When I run texexec on this, I get:
! Undefined control sequence.
l.4 \lettrine
             {T}{his is a test}
? X

I have a TeX source for lettrine in /usr/share/texmf/tex/context/third/lettrine/t-lettrine.tex. What I am doing wrong?

A:
\usemodule[lettri]

Try:
\usemodule[lettrine]
Works here with current minimals (mkii, mkiv)

A: \usemodule[lettrine] works fine for me with the context-minimals after I installed the module. (with context not texexec).


text:
Q: How to run heat.exe and register a dll in wix I need to register a dll in regAsm and now i was using
 <CustomAction Id='comReg' Directory='INSTALLLOCATION'
                ExeCommand='"[WindowsFolder]Microsoft.NET\Framework\v4.0.30319\regasm.exe" "[INSTALLLOCATION]myProduct.dll"  /codebase' Return='check' />

to register and to unregister
<CustomAction Id='comUnreg' Directory='INSTALLLOCATION' ExeCommand='"[WindowsFolder]Microsoft.NET\Framework\v4.0.30319\regasm.exe" /u "[INSTALLLOCATION]myProduct.dll"  /codebase' Return='check' />

Am using it and sometimes its installing and somnetimes it gives error.
But all are recommending to use something Heat.exe,
http://wixtoolset.org/documentation/manual/v3/overview/heat.html even i went through this link,but i need how to use it in wix and what to do with this stuff.I need some tuitorial

A: Heat is used to scrape directories or files and generate .wxs files to include in your installer.  If you wish to generate registry information from a .net dll with a COM interface you can use a command like the following:
Heat.exe file C:\<path_to_com_dll>\com.dll -dr INSTALLFOLDER -srd -gg -sfrag -suid -out C:\<path+wxs_file_name_to_output>

Here is some sample output from a command like the above:
<Component Id="ExactaDatabaseAccess.dll" Guid="{96F922A0-38C8-4B58-9E3B-E6B0C24EE09D}">
    <Class Id="{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}" Context="InprocServer32" Description="ExactaDatabaseAccess.DatabaseAccessObj" ThreadingModel="both" ForeignServer="mscoree.dll">
        <ProgId Id="ExactaDatabaseAccess.DatabaseAccessObj" Description="ExactaDatabaseAccess.DatabaseAccessObj" />
    </Class>
    <File Id="ExactaDatabaseAccess.dll" KeyPath="yes" Source="$(var.BasePath)\ExactaDatabaseAccess.dll" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\Implemented Categories\{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}" Value="" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32\5.5.6.8" Name="Class" Value="ExactaDatabaseAccess.DatabaseAccessObj" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32\5.5.6.8" Name="Assembly" Value="ExactaDatabaseAccess, Version=5.5.6.8, Culture=neutral, PublicKeyToken=null" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32\5.5.6.8" Name="RuntimeVersion" Value="v2.0.50727" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32\5.5.6.8" Name="CodeBase" Value="file:///[#ExactaDatabaseAccess.dll]" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32" Name="Class" Value="ExactaDatabaseAccess.DatabaseAccessObj" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32" Name="Assembly" Value="ExactaDatabaseAccess, Version=5.5.6.8, Culture=neutral, PublicKeyToken=null" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32" Name="RuntimeVersion" Value="v2.0.50727" Type="string" Action="write" />
    <RegistryValue Root="HKCR" Key="CLSID\{E5CF8A66-AA42-432F-A036-97A3FC7E6EBC}\InprocServer32" Name="CodeBase" Value="file:///[#ExactaDatabaseAccess.dll]" Type="string" Action="write" />
</Component>

Basically the heat command generates a wxs file with the above component in it.  Then all you need to do is to include this component or component group in your main installer.  It will then create the registry entries instead of running regasm.  The uninstall would then remove these registry entries.
Here is how you might include it in your main installer:
<Feature Id="ProductFeature" Title="ExactaSmallPick" Level="1">
    <ComponentRef Id="ExactaDatabaseAccess.dll"/>
</Feature>


text:
Q: Script for redirect to member's page after logging in I just want to now the script for redirecting after logging in on my webpage and the script that i put on all the webpages on my website for redirecting to member's page if you are already logged in, like in Facebook if i refresh the page I am still connected.

A: There are a hundred ways of doing it, but you can start by setting a session value right after a successful login attempt, such as:
$_SESSION["loggedin"] = true;

Now in your member pages you can check if the user is authenticated like so:
if(!isset($_SESSION["loggedin"]))
{
    //redirect user to login form
}

//Member page

In the example above, if the user is not logged in, you must redirect him to the login form.
Every place in your app where you desire to use $_SESSION, you must have session_start(); at the beginning of your script. If you don't have, it won't work.


text:
Q: Height of a frame in pixels I have 70 pixel high image. I want to create a frame precisely in such a way that I can tile its background with this image without causing a scrollbar to appear.
Intended result:
-------
|this has 70 pixels
--------
| the rest

my html looks something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
    "http://www.w3.org/TR/html4/frameset.dtd">

<title></title>
<frameset rows="70,*">
    <frame noresize src="a.htm" >
    <frame noresize src="b.htm" >
</frameset>

a.htm looks something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd"
<title></title>

Right now, the inside of the first freame apparently gets more than 70 pixels, making a scrollbar appear. It also messes up the other image inside, since it gets a tiny empty space and the bottom is cropped. Is it possible to make the inner frame in such a way that is has the precise height - I'm wondering if there is some border I have to set somewhere.
I know about scrolling="no".  But this doesn't stop the inner picture looking out of whack. I can "solve" the croping problem by giving the inner picture height:50px but not height:XX% but this doesn't seem right.
I also know frames are evil, and plan to repurpose this into a
 later. Will transition be smooth or will I have to realign things all over again?

A: You need to reset the margins and padding of html and body inside the frames:

This may get you started, but depending on what you want more may be needed. scrolling=no is probably also needed.
Yes, frames are deprecated. Odds are you shouldn't be using them - but only you can know!

A: Use overflow:hidden; to prevent the scrollbars if you don't have content going over the edges.


text:
Q: Windows Batch taking Wrong credentials to coonect to SQL server in between Execution I have windows batch where i need to connect to physical location in between execution of batch. For that i have configured credentials in app settings. My problem is once batch access physical folder and complete its work, after that i again connect to DB for some purpose but account used for connection is not the one defined in connection string instead of that folder access credentials are being used automatically which gets failed SQL connection error. I m clueless why automatically credentials are being changes. any one has any idea? Below is the app.config details -

<appSettings>
  <add key="ConnectionString" value="server=XXX;database=XXX;User ID=sa;Password=XXX;Persist Security Info=False;"/>

  <add key="LOGON32" value="9"/>
  <add key="CrsDataLogin" value="xxxx"></add>
  <add key="CrsDataPassword" value="xxxx"></add>
  <add key="CrsDataDomain" value="xx"></add>
  <add key="ClientSettingsProvider.ServiceUri" value="" />
  <add key="DailyArchieveFolder" value="Archieve//" />
  <add key="WeeklyArchieveFolder" value="Archieve//" />
  <add key="VivisimohttpTimeout" value="100000" />

</appSettings>

A: you have your token generated for windows credentials which are trying to connect to db which will fail db connection. Instead of this try to assign both DB as well as physical path access to your app pool account and bypass configured credentials.


text:
Q: how to configure default X-Pack watchers After installing X-Pack for ES 5.6, several default Watchers appear in ElasticSeach/Watchers tab.
The Watchers are greyed-out and read-only. How to view/configure that Watchers? I can't find them elasticsearch.yml config file.


text:
Q: Conversion Char to double How may I convert a numerical value in the form of a char to a double value?
I've tried just casting the char to a double but... it doesn't work like that I'm guessing as char such as '4' will convert to 52.0 in doubles.
So is there a way to convert a char with a value of say
    char c = '4'
to a double value of 4.0 where I can actually perform mathematical calculations on the value?
This is just a little program I created to show that casting a numeric char directly to a double won't work the way I was expecting.
public class conversion
{
public static void main(String args[])
{
    char eight = '8';
    char four = '4';

    double d2 = (char)eight;
    double d1 = (char)four;

    System.out.println(d2);
    System.out.println(d1);

    double result = (d2 / d1);

    System.out.println(result);
}
}

outputs:
56.0
52.0
1.0769230769230769

A: You can do:
double d2 = (double) Character.digit(eight, 10);
double d1 = (double) Character.digit(four, 10);

Or:
double d2 = (double) (eight - '0');
double d1 = (double) (four - '0');

If you want to convert a whole string, use Double.parseDouble
double d2 = Double.parseDouble("15.5");

Beware of a possible NumberFormatException is the string is an invalid floating point number

A: You can subtract '0' then cast as a double:
char c = '8';

double d = (double) (c - '0');  // <--

System.out.println(d);

8.0

You can check that c is valid via '0' <= c && c <= '9'.

A: You can also use :
double d2 = Double.valueOf(String.valueOf(eight));
double d1 = Double.valueOf(String.valueOf(four));

A: When you cast like that it returns the ASCII code of 4 or 8. The following code is what you want:
char myc='4';
double myd= Double.parseDouble(Character.toString(myc));

A: The character '0' does not correspond to the integer 0.  It corresponds to the ASCII key code for the '0' character.  Fortunately, the key codes for the characters '0' through '9' are sequential, so you can simply subtract '0' to convert a numeric character to the integer number it represents:
double d2 = (char)(eight - '0');
double d1 = (char)(four - '0');

A: How about this?
char doubleChar = '8';
double doubleDouble = Double.parseDouble(Character.toString(doubleChar));

A: You need to convert the char to a string and then to double like this:
double d2 = Double.parseDouble(Character.toString(eight));
double d1 = Double.parseDouble(Character.toString(four));


text:
Q: Find least similar/relevant document with Lucene Is it possible to kind of revert the scoring functionality in Lucene such that a search returns the least similar documents in the index?
Specifically, I want to execute a MoreLikeThis Query (the query itself is a document) and instead of getting the most relevant documents, it shoud return the least relevant/similar documents.
How would this be achievable? Thank you!

A: You can always sort by "score, asc": ascending instead of descending.
Keep in mind that in order to be considered at all, there must be at least be some similarity or else the doc won't be in the recall at all.
Or you can negate the query: filter out all docs that are "like this". Sorting then becomes pointless, as these docs are all equally (fully) distinct from the query.


text:
Q: Random Shuffling listBox items C# How can I shuffle present items in a listBox randomly?
I have this code, but it is very slow and inefficient -
private void shuffleItemsToolStripMenuItem_Click(object sender, EventArgs e)
{
   ListBox.ObjectCollection list = listBox1.Items;
   Random rng = new Random();
   int n = list.Count;
   while ( n > 1 )
   {
      n--;
      int k = rng.Next(n + 1);
      string value = (string)list[k];
      list[k] = list[n];
      list[n] = value;
   }
}

While this code does technically work, it's very slow and doesn't give many variations, often giving the same few shuffles.
I've been searching on Google for the last hour and have been unable to find a solution to this.  I am running out of hair to pull.
Thanks.

A: I guess you're using winforms, a ListBox has a pair of methods BeginUpdate and EndUpdate used to update the items fast (no need to repaint), repainting when changing the items is one of the reason slowing down everything. Also note that you don't need any cast here, it may slow your code a little, try the following:
private void shuffleItemsToolStripMenuItem_Click(object sender, EventArgs e) {
   ListBox.ObjectCollection list = listBox1.Items;
   Random rng = new Random();
   int n = list.Count;
   //begin updating
   listBox1.BeginUpdate();
   while ( n > 1 ) {
    n--;
    int k = rng.Next(n + 1);
    object value = list[k];
    list[k] = list[n];
    list[n] = value;
   }
   listBox1.EndUpdate();
   listBox1.Invalidate();
}

However I agree that even without using some tweaks above, your code should not run so slowly.

A: Try the Fisher-Yates shuffle : http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle


text:
Q: Detecting mismatches against constants in scanf format string From the man page of scanf:

A directive is one of the following:

*

*A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)).  This directive matches any amount of
  white space, including none, in the input.

*An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of
  input. (emphasis mine)

*A  conversion specification, which commences with a '%' (percent) character.  A sequence of characters from the input is
  converted according to this specification, and the result is placed in
  the corresponding pointer
            argument.  If the next item of input does not match the conversion specification, the conversion fails—this is a matching
  failure.

Now, consider the following code:
#include <stdio.h>

int main(void)
{
    const char* fmt = "A %49s B";
    char buf[50];

    printf("%d\n", sscanf("A foo B", fmt, buf));            // 1
    printf("%d\n", sscanf("blah blaaah blah", fmt, buf));   // 0
    printf("%d\n", sscanf("A blah blah", fmt, buf));        // 1

    return 0;
}

Lines 1 and 3 print 1 because matching "A" with "A" succeeds, as does matching "foo"/"blah" with %s. Line 2 prints 0 because "A" cannot be matched with "blah", so parsing stops there.
This is all fine and logical, but is there any way for me to detect that a matching failure occurred after all conversion specifications have been successfully matched and assigned? In that case, the value returned by scanf will be the number of conversion specifiers in my format string, so I can't use it to tell if matching succeeded till the very end.
In other words: the string fed to sscanf in line 3 is not "valid" in the sense that it's not in the format A [something] B. Can I use scanf to detect this, or is strtok my only option?

A: Employ a " %n" at the end of the format.
Directives:
" " scans 0 or more white-space.  It does not fail.
"%n" saves the count of the number of characters parsed so far (as an int).    It does not fail.
Set n to 0 and test to see that it changed.  The change would only happen if the entire preceding format succeeded.  Also test that the scan ended on a null character - thus detecting trail unwanted text.
The added " ", though optional, if very useful as typically a trailing white-space, which is often a '\n', is not offensive.  It negates the needed for a scanned line of text to be preprocessed to have its line ending removed.
#include <stdio.h>

void test(const char *s) {
  const char* fmt = "A %49s B %n";
  char buf[50];
  int n = 0;
  int cnt = sscanf(s, fmt, buf, &n);
  int success = n > 0 && s[n] == '\0';
  printf("sscanf():%2d  n:%2d  success:%d  '%s'\n", cnt, n, success, s);
}

int main(void) {
  test("A foo B");
  test("blah blaaah blah");
  test("A blah blah");
  test("A foo B ");
  test("A foo B x");
  test("");
  return 0;
}

Output
sscanf(): 1  n: 7  success:1  'A foo B'
sscanf(): 0  n: 0  success:0  'blah blaaah blah'
sscanf(): 1  n: 0  success:0  'A blah blah'
sscanf(): 1  n: 8  success:1  'A foo B '
sscanf(): 1  n: 8  success:0  'A foo B x'
sscanf():-1  n: 0  success:0  ''

Note that success is determined by n alone.  On lack of success, the destination scanned variables like buf should not be used.  If a partial result is needed, then use the return value of sscanf().

A: If you want to parse more complex input, use a proper parser/lexxer. Otherwise, have a look at the %n conversion specifier:

No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment- suppressing character or a field width, the behavior is undefined.

You can use this multiple times: after the last variable conversion and one at the end.

A: For OP's use case, regex can equally be used to match the pattern.
/* see http://linux.die.net/man/3/regex */
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>

int regexp(const char *);

int main(int argc, char **argv){
    printf("%d\n", regexp("A foo B"));
    printf("%d\n", regexp("blah blaaah blah"));
    printf("%d\n", regexp("A blah blah"));
    return EXIT_SUCCESS;
}
int regexp(const char *input_str){
    char buf[100];
    regex_t regex;
    int rcval;

    /* compile regexp - see http://linux.die.net/man/3/regcomp */
    rcval = regcomp(&regex, "^A\\s.*\\sB$", 0);
    if (rcval) {
        fprintf(stderr, "Could not compile regex\n");
        return -1;
    }
    /* execute regexp - see http://linux.die.net/man/3/regexec */
    rcval = regexec(&regex, input_str, 0, NULL, 0);
    if (!rcval) {
        fprintf(stdout, "Match\n");
        regfree(&regex);
        return 1;
    }else{
        if (rcval == REG_NOMATCH) {
            fprintf(stdout, "No match\n");
            regfree(&regex);
            return 0;
        }else{
            regerror(rcval, &regex, msgbuf, sizeof(msgbuf));
            fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            regfree(&regex);
            return -1;
        }
    }
    return 0; // default to no match
}

A: If you are only interested in whether the entire format has been scanned, but do not care about trailing text in the stream, you can use this terse method:
int success = 0;
fscanf(stream, "A %49s B%n", buf, &success);
if(!success) handleError();

The trick is, that the "%n" conversion does not happen unless the entire format is matched successfully. Since any matching of the format will consume one or more characters from the stream, the value that the "%n" writes will always be non-zero. Thus, success will be set to a truthy value if, and only if the entire format was matched.


text:
Q: How to get size of root && used size of root I am working with the Google Drive API using the Google PHP client Library.  I am trying to find the current size of the Root directory.
My code is as follows.
$file = $this->service->files->get('root',array( 'fields'=>'size,spaces,quotaBytesUsed',));

Size and quotaBytesUsed are 0;

A: File resource documentation

size  long    The size of the file's content in bytes. This is only
  applicable to files with binary content in Drive.
quotaBytesUsed long The number of storage quota bytes used by the file . This includes the head revision as well as previous revisions with keepForever enabled.

As the documentation states only files contain sizes.  Your going to have to do it the hard way I think and get a list of all the files in your google drive and add them up.
Alternative if you are trying to get info on how much space you have used on google drive you can use the About.get method which returns space for a users google drive account
"storageQuota": {
  "limit": "18253611008",
  "usage": "12738688521",
  "usageInDrive": "2449392360",
  "usageInDriveTrash": "838401665"
   }


text:
Q: Difficulty in ostream ostream& operator<<(ostream& os, const PT& p)
{
   os << "(" << p.x << "," << p.y << ")";
}

PT is a structure and x , y are its members.
Can someone please explain what exactly the above line does. Can't the desired text be printed using cout?
I came across this snippet of code from this site.

A: It's a custom overload for operator<<.
It means you can do this:
PT p = ...;
std::cout << p << "\n";

or this:
PT p = ...;
std::stringstream ss;
ss << p << "\n";
std::cout << ss;

or lots of other useful stuff.
However, it should be noted that the code you quoted won't work properly.  It needs to return os.

A: This provides a method of outputting the PT. Now, you can use this:
PT p;
std::cout << p;

This gets translated into a call of
operator<< (std::cout, p);

That matches your overload, so it works, printing the x and y values in brackets with less effort on the user's part. In fact, it doesn't have to be cout. It can be anything that "is" a std::ostream. There are quite a few things that inherit from it, meaning they are std::ostreams as well, and so this works with them too. std::ofstream, for file I/O, is one example.
One thing that the sample you found doesn't do, but should, though, is return os;. Without doing that, you can't say std::cout << p << '\n'; because the result of printing p will not return cout for you to use to print the newline.

A: It allows the << operator to append the PT object to the stream. It seems the object has elements x and y that are added with a comma separator.

A: This operator << overloading for outputing object of PT class .
Here:
ostream& operator<<(ostream& os, const PT& p)

First param is for output stream where p will be appended.
It returns reference to os for chaining like this:
cout << pt << " it was pt" << endl;


text:
Q: How to keep service alive? Any application that has a service going obviousely counts on it to be always running. It's part of the product and if it's a paid app - the user expects it.
However, it seems that there is no way for a service not to get wacked if the Android OS feels the memory pressure or if something goes wrong and the service crashes.
What is the best way of making sure that a service is always running?
Is it wise to create a second service that once in a while start the "useful" service and if it's alredy running it'll be ignored?

A: To be honest, I am not sure if this is a good idea as all.
If there is enough memory pressure, it would not be fair towards other apps to insist on running. Also services only get kicked out on severe low memory situations.
If you write a reaper service, this one can get kicked out too.
And as you say " and if it's a paid app - the user expects it." -- the user also expects that apps play nicely

A: If your service is 'critical', you can use startForeground which gives your service as much priority as an Activity in the foreground.


text:
Q: Pagination according to search results if i load my mypage.php page from database it will display all page numbers of paginated data. Now i need is to display with a pagination pages accord to number or search results when i search it must show the number of pages according to filtered data.
need to fetch next results on next page means page 2 , 3 like that end of the result says last page instead as all pages to show like 1, 2, 3, 4 , 5. kindly help me on it .. my code is below
        <?php
        include_once("mysqli_connection.php");
        $search = $_GET['search'];
        $sql = "SELECT COUNT(id) FROM employee";
        $query = mysqli_query($db_conx, $sql);
        $row = mysqli_fetch_row($query);
        // Here we have the total row count
        $rows = $row[0];
        $page_rows = 2;
        // This tells us the page number of our last page
        $last = ceil($rows/$page_rows);
        if($last < 1){
            $last = 1;
        }
        $pagenum = 1;
        // Get pagenum from URL vars if it is present, else it is = 1
        if(isset($_GET['pn'])){
            $pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
        }
        if ($pagenum < 1) {
            $pagenum = 1;
        } else if ($pagenum > $last) {
            $pagenum = $last;
        }
        // This sets the range of rows to query for the chosen $pagenum
        $limit = 'LIMIT ' .($pagenum - 1) * $page_rows .',' .$page_rows;

        $sql = "SELECT id, name, lastname FROM employee WHERE name LIKE '%".$search."%' $limit";
        $query = mysqli_query($db_conx, $sql);
        $textline1 = "employee ($rows)";
        $textline2 = "Page $pagenum of $last";
        // Establish the $paginationCtrls variable
        $paginationCtrls = '';
        //count search pages
        if($last != 1){

            if ($pagenum > 1) {
                $previous = $pagenum - 1;
                $paginationCtrls .= 'Previous     ';

                for($i = $pagenum-2; $i < $pagenum; $i++){
                    if($i > 0){
                        $paginationCtrls .= ''.$i.'   ';
                    }
                }
            }
            // Render the target page number, but without it being a link
            $paginationCtrls .= ''.$pagenum.'   ';
            for($i = $pagenum+1; $i <= $last; $i++){
                $paginationCtrls .= ''.$i.'   ';
                if($i >= $pagenum+4){
                    break;
                }
            }
            if ($pagenum != $last) {
                $next = $pagenum + 1;
                $paginationCtrls .= '     Next ';
            }
        }
        $list = '';
        while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
            $id = $row["id"];
            $firstname = $row["name"];
            $lastname = $row["lastname"];
            /*$datemade = $row["datemade"];
            $datemade = strftime("%b %d, %Y", strtotime($datemade));*/
            $list .= '
'.$id.' '.$firstname.' '.$lastname.' Testimonial - Click the link to view this testimonial
Written
';
        }
  // Close your database connection
        mysqli_close($db_conx);

        ?>


text:
Q: SQL data Insertion slow through ssis I am inserting data in to a Table1 from ssis. The data is loading very slow per min(5-10k records) are inserting i have selected fast load option in destination task that option also not helped me.
In the same server for another table (Table2)  data load is happening very fastly which is having more data and more indexes comparing to the  Table1.
Why Table1 data insertion is slow ?
Please help me.

A: The reasons for slowing loading packages could be various. Usually, they are related to memory, destination, indices, loggings and etc. Have you tried the equivalent query's performance? If that is better, you can use Execute SQL Task instead of data flow task.
In your packages, do you have OLE DB Command transformation or other fully-blocking transformations like fuzzy lookup or fuzzy grouping? Because OLE DB Command transformation is on a row-by-row basis and all the fully-blocking transformations will create lots of overhead.
It seems that you are using OLE DB Destination, so you may change the MICS (Maximum Insert Commit Size) and RPB (Row per Batch) accordingly. Because the thing is a large batch will negatively affect memory if you have clustered indexes on the target table.


text:
Q: Не везде работает скрипт Доброго времени суток!
Есть скрипт
jQuery(this).click(function () {
    $("#exampleMenu").animate({
        top: '-600px'
    }, 600, "linear");
});

Он срабатывает в хроме, но не работает в опере. Подскажите, в чем может быть дело?
A: Третий аргумент метода .animate() — функция, срабатывающая после выполнения анимации. Она задаётся либо так:
$("#exampleMenu").animate(a,b,c);

Или же её можно вызвать, задав прежде:
function linear()
    {
        //тело функции
    }
$("#exampleMenu").animate(a,b,'linear');

Видимо, функция linear — какая-то из стандартных функций, заданых в Хроме, либо в какой-то из его js-библиотек.


text:
Q: Stack Overflow in resursive calls I was just going through this Wikipedia entry. Out of curiosity to find the stack size allocated to a simple process, i tried this
int main()
{
    static int count = 0;
    cout<<"  Count = "<<count++<<endl;
    main();
    return 0;
}

Compiler DevC++
I got this :-
Till this point everything is fine, understandable, by the way from last digit i.e. 43385 can i guess the maximum stack size - on 32 bit machine (what if i say 4 bytes(4 bytes for return address on stack for each call), i may sound silly on this.
Now if i modify my program to :-
void foo()
{
    static int count = 0;
    cout<<"  Count = "<<count++<<endl;
    foo();
}

int main()
{
    foo();
    return 0;
}

In this i get Stack Over flow at count :- 130156 (ok, fine)
But my question if, i add one function in between main and foo, i get this count decrements by 1(130155), if 2 functions in b/w foo and main count is decremented by 2(130154) and so on. Why is this behavior? Is it because 1 space is being consumed for each function address.

A: Firstly correct your program by adding Count++ (silly).
Stack size is not fixed, most compilers let you specify the Stack size. Stack size is also dependent on some factors like Platform, toolchain, ulimit,and other parameters.There are many static and dynamic properties that can influence it.
There are three kinds of memory limits:
for 32-bit (windows)
Static data - 2GB
Dynamic data - 2GB
Stack data - 1GB (the stack size is set by the linker, the default is 1MB.  This can be increased using the Linker property System > Stack Reserve Size).
by using your program you can guess the current stack size.
The memory-limits-applications-windows Stack Overflow Recursion in C c-maximum-stack-size-of-program will help you.


text:
Q: How to create a random header location in PHP Is it possible to load 2 different header location in separate blank pages using php?
 <?php

 $state= $_GET['state'];
 $zip= $_GET['zip'];

 header ("Location:http://www.site1.com/test?CID=1&state=$state&zip=$zip");
 header ("Location:http://www.site2.com/test?CID=2&state=$state&zip=$zip");
 ?>

If not, how can I set this up so it randomly loads 1 of them?

A: You can have the page redirected to a random URL using array_rand():
<?php
$arr = array("http://www.site1.com", "http://www.site2.com");
header ("Location: " . $arr[array_rand($arr)]);


text:
Q: CGAffineTransformMake shifts my object before transforming I have a button (actually four of them) in a specific position that I want to rotate and translate at the same time, therefore I opted to use CGAffineTransformMake and provide the transformation matrix.
However I noticed that if I want to translate x = -100, for instance, the button will first be instantly shifted x = +200 and then will animate it's transformation to x = -100.
Is there any way to make it translate without this shift to the opposite direction?
CGAffineTransform transform = CGAffineTransformMake(-1, 0, 0, -1, -100, 0); // Spins 180° and translates

[UIView beginAnimations:@"Show Menu" context:nil];
[UIView setAnimationDuration:2.4];
_menuButton1.transform = transform;
[_menuButton1 setAlpha:1.0];
[UIView commitAnimations];

A: You shouldn't be using that animation method. It is discouraged by Apple after iOS 4.0. https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/UIView/UIView.html#//apple_ref/occ/clm/UIView/beginAnimations:context:
The preferred method is...
[UIView animateWithDelay:0.0
                duration:2.4
                 options:0
              animations:^() {
                  _menuButton1.transform = CGAffineTransformMake(-1, 0, 0, -1, -100, 0);
                  _menuButton1.alpha = 1.0;
              }
              completion:nil];

Will edit my answer when you reply to my comment.
OK, the cause for this shift is that you are trying to translate the view whilst using AutoLayout to constrain it.
I don't know why it causes an issue, but it does.
Your two options for fixing it are...

*

*Turn of AutoLayout and then you code will work.

*Keep AutoLayout enabled and learn how to animate constraints.

For the second option I can recommend the book "iOS6 by Tutorials" by Ray Wenderlich and his team.
http://www.raywenderlich.com/store/ios-6-by-tutorials
I used this to learn how to do AutoLayout properly.

A: You can start with one of the transforms, let's say translation:
CGAffineTransform transform = CGAffineTransformMakeTranslation(-100.0f, 0.0f);

And then add rotation to it:
transform = CGAffineTransformRotate(transform, (float)M_PI_2);

And finally set this transform to your view's transform property.


text:
Q: Continuity of the dual product reloaded Let $X$ be a Banach space with topological dual $X^*$. Then the dual product $(x,x^*)\in X\times X^*\to x^*(x)\in\mathbb{R}$ is strongly$\times$strongly continuous in $X\times X^*$.
That does not hold if the topology considered on $X^*$ is the weak-star topology and the space is non-reflexive. Let $\tau^*_M$ the Mackey topology on $X^*$ with respect to the duality $(X^*,X)$. Then
$X$ is reflexive iff the dual product is strongly$\times\tau^*_M$ (lower)(upper)(semi-)continuous.
My question is:
$\ \ Q:\ $ If $X$ is a Banach non-reflexive space what is the coarsest topology $\tau$ on the dual $X^*$ for which the dual product is strongly$\times\tau$ continuous in $X\times X^*$?
Clearly $\tau$ is weaker than the strong topology on $X^*$ and finer than $\tau^*_M$.


text:
Q: python: how to get the class of a calling method through inspection? For my exception class I'd like to find out whether the function which instantiated the exception object is a method and if so, show the class name.
So in the init method of my exception class I get the name of the calling function:
frame, module, line, function, context, index = inspect.stack()[1]

But is there any way the get the class name (if any) of the calling function?

A: Assuming the frame is for an instance method:
self_argument = frame.f_code.co_varnames[0]  # This *should* be 'self'.
instance = frame.f_locals[self_argument]
class_name = instance.__class__.__name__


text:
Q: Select only top level UL in css Trying to select only the top level UL element and exclude any nested UL elements in CSS. I've tried so many different variations but can't find a solution.
As an example, the html code could look like something below. Now I want to go ahead and style only the top level UL and don't apply the styling to the nested ULs. In my scenario, I can't add any classes or IDs to the html code - no changes to the html, css only.
Thanks a lot!

A: I settled for *:not(li) > ul to only select top level
 elements and exclude
 elements that are inside of other
 elements.

A: You can use the universal selector to capture anything that owns a 'ul', since you don't have insight. However, you do have insight in the sub lists so you can ensure you are only getting top-level by negating li elements that own one. Not sure what all your edge cases are but that's one way to do it.

ul {
  background-color: pink; /* just for visual reference */
}

*:not(li)>ul {
  background-color: green;
}

nav sub 1

nav sub 2

nav 1

footer 1

Otherwise you can just compound rules with all the elements that you think are possiblilites:
div > ul,
nav > ul,
body > ul
...etc {
   background-color: red;
}


text:
Q: Software keyboard resizes background image on Android Whenever the software keyboard appears, it resizes the background image. Refer to the screenshot below:

As you can see, the background is sort of squeezed. Anyone can shed a light on why the background resizes?
My Layout is as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/page_bg"
    android:isScrollContainer="false"
>
    <LinearLayout android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
    >
        <EditText android:id="@+id/CatName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textCapSentences"
            android:lines="1"
        />
        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/save"
            android:onClick="saveCat"
        />
    </LinearLayout>
    <ImageButton
        android:id="@+id/add_totalk"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:background="@null"
        android:src="@drawable/add_small"
        android:scaleType="center"
        android:onClick="createToTalk"
        android:layout_marginTop="5dp"
    />
</LinearLayout>

A: In case if somebody need an adjustResize behavior and don't want his ImageView to be resized here is another workaround.
Just put ImageView inside ScrollView => RelativeLayout with ScrollView.fillViewport = true.
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <FrameLayout
            android:layout_width="100dp"
            android:layout_height="100dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/gift_checked" />

        </FrameLayout>
    </RelativeLayout>
</ScrollView>

A: After studying and implementing all available answers, here I am adding a solution.
This answer is combination of code from:
https://stackoverflow.com/a/45620231/1164529
https://stackoverflow.com/a/27702210/1164529
Here is the custom AppCompatImageView class which showed no stretching or scrolling w.r.t. soft keyboard:-
public class TopCropImageView extends AppCompatImageView {

    public TopCropImageView(Context context) {
        super(context);
        setScaleType(ImageView.ScaleType.MATRIX);
    }

    public TopCropImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setScaleType(ImageView.ScaleType.MATRIX);
    }

    public TopCropImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setScaleType(ImageView.ScaleType.MATRIX);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        computeMatrix();
    }

    @Override
    protected boolean setFrame(int l, int t, int r, int b) {
        computeMatrix();
        return super.setFrame(l, t, r, b);
    }

    private void computeMatrix() {
        if (getDrawable() == null) return;
        Matrix matrix = getImageMatrix();
        float scaleFactor = getWidth() / (float) getDrawable().getIntrinsicWidth();
        matrix.setScale(scaleFactor, scaleFactor, 0, 0);
        setImageMatrix(matrix);
    }
}

To use it as background to my Fragment class, I set it as first element to FrameLayout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <complete.package.TopCropImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/my_app_background" />

    <!-- Enter other UI elements here to overlay them on the background image -->

<FrameLayout>

A: I encountered the main problem when working on my app. At first, I use the method provided by @parulb to solve the problem. Thank him a lot. But later I noticed that the background image is partially hided by actionbar (and statusbar I am sure). This small issue is already proposed by @zgc7009 who commented below the answer of @parulb one year and a half ago but no one replied.
I worked a whole day to find out a way and fortunately I can at least solve this problem perfectly on my cellphone now.
First we need a layer-list resource in drawable folder to add padding on the top to the background image:
<!-- my_background.xml -->
<?xml version="1.0" encoding="utf-8"?>

<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="75dp">
        <bitmap android:src="@drawable/bg" />
    </item>
</layer-list>

Second we set this file as resource for background as mentioned above:
getWindow().setBackgroundDrawableResource(R.drawable.my_background);

I am using Nexus 5. I found a way to get height of actionbar in xml but not the statusbar, so I have to use a fixed height 75dp for top padding. Hope anyone can find the last piece of this puzzle.

A: Here is the best solution to avoid such kind of problem.
Step 1: Create a style
<style name="ChatBackground" parent="AppBaseTheme">
    <item name="android:windowBackground">@drawable/bg_chat</item>
</style>

Step 2: Set your activity style in the AndroidManifest file
<activity
    android:name=".Chat"
    android:screenOrientation="portrait"
    android:theme="@style/ChatBackground" >

A: Through  android:windowSoftInputMode="adjustPan"  giving bad user experience because through that entire screen goes on top (shift to top ) So, following is one of the best answeres.
I have same Problem  but after that , i Found Awesome answeres from the @Gem
In Manifest
android:windowSoftInputMode="adjustResize|stateAlwaysHidden"

In xml
Dont Set any background here and keep your view under ScrollView
In Java
You need to set the background to window:
    getWindow().setBackgroundDrawableResource(R.drawable.bg_wood) ;

Thanks to @Gem.

A: I suffered similar issues, but it seems like using adjustPan with android:isScrollContainer="false" still didn't fix my layout (which was a RecyclerView below a LinearLayout). The RecyclerView was fine, but every time the virtual keyboard showed up, the LinearLayout re-adjusted.
To prevent this behavior (I simply wanted to have the keyboard go over my layout), I went with the following code:
    <activity
        android:name=".librarycartridge.MyLibraryActivity"
        android:windowSoftInputMode="adjustNothing" />

This tells Android to basically leave your layout alone when the virtual keyboard is called.
More reading about possible options can be found here (though oddly enough, it doesn't seem like there's an entry for adjustNothing).

A: Add this line in AndroidManifest.xml file:
android:windowSoftInputMode=adjustUnspecified

refer to this link for more info.

A: I faced with this problem, when my background image was just a ImageView inside a Fragment, and it was resized by the keyboard.
My solution was: using custom ImageView from this SO Answer, edited to be compatible with androidx.
import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;

/**
 * Created by chris on 7/27/16.
 */
public class TopCropImageView extends AppCompatImageView {

    public TopCropImageView(Context context) {
        super(context);
        setScaleType(ScaleType.MATRIX);
    }

    public TopCropImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setScaleType(ScaleType.MATRIX);
    }

    public TopCropImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setScaleType(ScaleType.MATRIX);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        recomputeImgMatrix();
    }

    @Override
    protected boolean setFrame(int l, int t, int r, int b) {
        recomputeImgMatrix();
        return super.setFrame(l, t, r, b);
    }

    private void recomputeImgMatrix() {
        if (getDrawable() == null) return;

        final Matrix matrix = getImageMatrix();

        float scale;
        final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
        final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
        final int drawableWidth = getDrawable().getIntrinsicWidth();
        final int drawableHeight = getDrawable().getIntrinsicHeight();

        if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
            scale = (float) viewHeight / (float) drawableHeight;
        } else {
            scale = (float) viewWidth / (float) drawableWidth;
        }

        matrix.setScale(scale, scale);
        setImageMatrix(matrix);
    }

}

A: Ok I fixed it by using
android:windowSoftInputMode="stateVisible|adjustPan"

entry inside <Activity > tag in manifest file. I think it was caused by having ScrollView inside the Activity.

A: just for addition...
if u have a listview on your activity
u need to add this android:isScrollContainer="false" in your listview properties...
and don't forget to add android:windowSoftInputMode="adjustPan" in your manifest xml at your activity...
if you guys using android:windowSoftInputMode="adjustUnspecified" with scrollable view on your layout, then your background will still resized by the soft keyboard...
it would be better if you use "adjustPan" value to prevent your background from resizing...

A: I faced the same problem while developing a chat app, chat screen with a background image. android:windowSoftInputMode="adjustResize" squeezed my background image to fit the available space after the soft keyboard was displayed and "adjustPan" shifted the whole layout up to adjust the soft keyboard.
The solution to this problem was setting the window background instead of a layout background inside an activity XML. Use getWindow().setBackgroundDrawable() in your activity.

A: My solution is to substitute the background of the window with the one of the layout, then set the layout background to null. In this way I keep the image in the XML preview window:
So keep the background in the layout and add an id for it.
Then in the activity onCreate() put this code:
    ConstraintLayout mainLayout = (ConstraintLayout)findViewById(R.id.mainLayout);
    getWindow().setBackgroundDrawable(mainLayout.getBackground());
    mainLayout.setBackground(null);

A: I faced this same problem before but no solution worked for me so long because i was using a Fragment, and also
getActivity().getWindow().setBackgroundDrawable()  was not a solution for me.
Solution which worked for me is to override FrameLayout with a logic to handle keyboard which should appear and change the bitmap on the go.
Here is my FrameLayout code (Kotlin):
class FlexibleFrameLayout : FrameLayout {

    var backgroundImage: Drawable? = null
        set(bitmap) {
            field = bitmap
            invalidate()
        }
    private var keyboardHeight: Int = 0
    private var isKbOpen = false

    private var actualHeight = 0

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        init()
    }

    fun init() {
        setWillNotDraw(false)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        if (actualHeight == 0) {
            actualHeight = height
            return
        }
        //kb detected
        if (actualHeight - height > 100 && keyboardHeight == 0) {
            keyboardHeight = actualHeight - height
            isKbOpen = true
        }
        if (actualHeight - height < 50 && keyboardHeight != 0) {
            isKbOpen = false
        }
        if (height != actualHeight) {
            invalidate()
        }
    }

    override fun onDraw(canvas: Canvas) {
        if (backgroundImage != null) {
            if (backgroundImage is ColorDrawable) {
                backgroundImage!!.setBounds(0, 0, measuredWidth, measuredHeight)
                backgroundImage!!.draw(canvas)
            } else if (backgroundImage is BitmapDrawable) {
                val scale = measuredWidth.toFloat() / backgroundImage!!.intrinsicWidth.toFloat()
                val width = Math.ceil((backgroundImage!!.intrinsicWidth * scale).toDouble()).toInt()
                val height = Math.ceil((backgroundImage!!.intrinsicHeight * scale).toDouble()).toInt()
                val kb = if (isKbOpen) keyboardHeight else 0
                backgroundImage!!.setBounds(0, 0, width, height)
                backgroundImage!!.draw(canvas)
            }
        } else {
            super.onDraw(canvas)
        }
    }
}

And I used it as like an usual FrameLayout's background.
frameLayout.backgroundImage = Drawable.createFromPath(path)
Hope it helps.

A: Just add in your activity
getWindow().setBackgroundDrawable(R.drawable.your_image_name);

A: You can wrap your LinearLayout with FrameLayout and add ImageView with Background:
<FrameLayout>

  <ImageView
    android:background="@drawable/page_bg"
    android:id="@+id/backgroundImage" />

  <LinearLayout>
    ....
  </LinearLayout>
</FrameLayout>

And You can set it height when you creating activity/fragment (to prevent from scaling when open keyboard). Some code in Kotlin from Fragment:
activity?.window?.decorView?.height?.let {
        backgroundImage.setHeight(it)
}

A: if you are set image as windowbackground and ui going to stuck. then there may be possibility you are uses drawable which is in single drawable folder,
if yes then you have to paste it in drawable-nodpi or drawable-xxxhdpi.


text:
Q: send broadcast message when service is stopped I would like to send the broadcast message back to the activity when the service is stopped by the user or OS. I have tried to add the code in onDestroy of the service while onDestroy have not been called every time.
Can anyone give me suggestion how I can send the message when the service is stopped?

A: Try using StartSticky and sending a broadcast every time the service start(onStart). So when it is destroyed, the service will try to run again by itself and will send the broadcast. This way you will know when the server have been closed and open again.
P.D: Remember to send the broadcast in the onStart, not in onCreate.(Service Lifecycle.)


text:
Q: How to generate a output with the list of permutations of a set in Prolog? Code:
del( A, [A|B], B ).
del( A, [B|C], [B|D] ) :-
    del( A, C, D ).

same_set( [], [] ).
same_set( A, [B|C] ) :-
    del( B, A, D ),
    same_set( D, C).

Current output:
?- mesmo_conjunto([1,a,3], Xs).
Xs = [1, a, 3] ;
Xs = [1, 3, a] ;
Xs = [a, 1, 3] ;
Xs = [a, 3, 1] ;
Xs = [3, 1, a] ;
Xs = [3, a, 1] ;
false.

What must be changed in the code so that it has the output below?
Expected output:
Xs=[[1,a,3],[1,3,a],[a,1,3],[a,3,1],[3,a,1],[3,1,a]]


text:
Q: Parse MySQL Community Edition 5.7 auto-generated temporary root password in bash shell script I am installing MySQL 5.7 on CentOS 7 (x64) like this:
yum localinstall -y https://dev.mysql.com/get/mysql57-community-release-el7-7.noarch.rpm;
yum install -y mysql-community-server;

The new version of mysql automatically generates a random root password. This can be found with the following command:
grep 'A temporary password is generated for root@localhost' /var/log/mysqld.log | tail -1
e.g. output:

2016-01-01T20:51:50.861279Z 1 [Note] A temporary password is generated for root@localhost: s8,arY7l_xQ:

Is there a way to parse the randomly generated root pass s8,arY7l_xQ: to a variable from the above command's output?

A: This seems to work for me:
dan@ebony ~ $ cat file
2016-01-01T20:51:50.861279Z 1 [Note] A temporary password is generated for root@localhost: s8,arY7l_xQ:
dan@ebony ~ $ grep 'temporary.*root@localhost' file | sed 's/.*root@localhost: //'
s8,arY7l_xQ:
dan@ebony ~ $ passwd="`grep 'temporary.*root@localhost' file | sed 's/.*root@localhost: //'`"
dan@ebony ~ $ echo $passwd
s8,arY7l_xQ: