Q: Why does Microsoft Visual C# 2008 Express Edition debugger randomly exit? I am writing a multi-threaded Windows application in Microsoft Visual C# 2008 Express Edition.  Recently, the debugger has been acting strangely.
While I am Stepping Over lines of code using the F10, sometimes it will interpret my Step Over (F10) command just like a Continue command (F5) and then the program will resume running and the debugging session will be done.
Does anyone know why this happening?  In what circumstances can the Step Over command result in the debugger stopping?
It's not a problem with the code being debugged: it doesn't just happen on particular lines of code.  It happens on a random line that is different each time I run the debugger.
It's not a problem with my keyboard: the same thing happens when I just click Step Over in the Debug toolbar.
It may be a problem with the other threads in my program.  Maybe one of them is randomly doing something that has a side effect of interrupting the debugger.  Is that possible?
Thanks in advance!

A: I've seen this a few times. It generally happens when there's a context switch to another thread. So you might be stepping through thread with ID 11, you hit F10, and there's a pre-emptive context switch so now you're running on thread ID 12 and so Visual Studio merrily allows the code to continue.
There are some good debugging tips here:

Tip: Break only when a specific thread calls a method: To set a per-thread breakpoint, you need to uniquely identify a particular thread that you have given a name with its Name property. You can set a conditional breakpoint for a thread by creating a conditional expression such as "ThreadToStopOn" == Thread.CurrentThread.Name .
You can manually change the name of a thread in the Watch window by watching variable "myThread" and entering a Name value for it in the value window. If you don't have a current thread variable to work with, you can use Thread.CurrentThread.Name to set the current thread's name. There is also a private integer variable in the Thread class, DONT_USE_InternalThread, this is unique to each thread. You can use the Threads window to get to the thread you want to stop on, and in the Watch window, enter Thread.CurrentThread.DONT_USE_InternalThread to see the value of it so you can create the right conditional breakpoint expression.

EDIT: There are also some good tips here. I found this by googling for 'visual studio prevent thread switch while debugging'.

A: You ought to take a look at this KB article and consider its matching hotfix.
EDIT: the hotfix does solve these kind of debugging problems.  Unfortunately, the source code changes for the hotfix didn't make it back into the main branch and VS2010 shipped with the exact same problems.  This got corrected again by its Service Pack 1.

A: I find using a logfile is very handy when dealing with multiple threads.
Debugging threads is like the Huysenberg principle - observe too closely and you'll change the outcome !

A: Try this http://support.microsoft.com/kb/957912. Worked for me.


Q: Null Pointer Exception While trying to Connect to FTP server FTPClient mFTPClient;

mFTPClient = new FTPClient();

// connecting to the host

mFTPClient.connect(host, port);

After this line of code, the following exception thrown.

Method threw 'java.lang.NullPointerException' exception. Cannot evaluate android.system.StructAddrinfo.toString()


Q: Accidentally import the MySQL user table into TiDB, or forget the password If I accidentally import the MySQL user table into TiDB, or forget the password and cannot log in, how to deal with it?

A: Restart the TiDB service, add the -skip-grant-table=true parameter in the configuration file. Log into the cluster without password and recreate the user, or recreate the mysql.user table using the following statement:
DROP TABLE IF EXIST mysql.user;

CREATE TABLE if not exists mysql.user (
    Host        CHAR(64),
    User        CHAR(16),
    Password      CHAR(41),
    Select_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Insert_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Update_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Delete_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Create_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Drop_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Process_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Grant_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    References_priv     ENUM('N','Y') NOT NULL DEFAULT 'N',
    Alter_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Show_db_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Super_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Create_tmp_table_priv   ENUM('N','Y') NOT NULL DEFAULT 'N',
    Lock_tables_priv    ENUM('N','Y') NOT NULL DEFAULT 'N',
    Execute_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Create_view_priv    ENUM('N','Y') NOT NULL DEFAULT 'N',
    Show_view_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Create_routine_priv   ENUM('N','Y') NOT NULL DEFAULT 'N',
    Alter_routine_priv    ENUM('N','Y') NOT NULL DEFAULT 'N',
    Index_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Create_user_priv    ENUM('N','Y') NOT NULL DEFAULT 'N',
    Event_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    Trigger_priv      ENUM('N','Y') NOT NULL DEFAULT 'N',
    PRIMARY KEY (Host, User));

INSERT INTO mysql.user VALUES ("%", "root", "", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y");


Q: Exclude results from MySQL based on Content I am currently searching my database with the following query. What I really need to do is get 30 results that do not include the tag #DONE# that is contained in the information column. The structure of the database is below:
ID                  Info1       Info2   Info3           DateAdded
-----------------------------------------------------------------
1235                0000        6       #DONE#infohere  35:27.9
5678                1111        5       #DONE#infohere  47:15.4
4583                2222        7       otherinfohere   47:36.8
1238                3333        9       otherinfohere   47:12.6

Current Query:
SELECT * FROM $tablename WHERE `Info3` <> '' LIMIT 0,30

So in the full database there is more than 30 of both Info3 columns that have the #DONE# tag and do not have the #DONE# tag. What I need to be able to do it to exclude all the results that have the #DONE# tag. I do not want to just get all results as that would be extensive on the database when it gets larger but I do need 30 results in the end. Any suggestions?

A: you want NOT LIKE
SELECT * FROM $tablename WHERE `Info3` NOT LIKE '#DONE#%' LIMIT 0,30

EDIT: if #DONE# is not always at the beginning, use %#DONE#%
SELECT * FROM $tablename WHERE `Info3` NOT LIKE '%#DONE#%' LIMIT 0,30

A: Try this -
SELECT * FROM $tablename WHERE `Info3` not like '#DONE#%' LIMIT 0,30


Q: actionscript 3.0 I have a picture sliding on my scene, with fade  in and out pictures between frames 1 and 100. I would like to create 2 buttons that could go to previous picture and next picture and I just can figure out the code. Need help pls. I tryed like this on last frame, 2 ways:
gotoAndPlay(1);

btnA.addEventListener(MouseEvent.CLICK, backward);
btnB.addEventListener(MouseEvent.CLICK, forward);

function backward(event:MouseEvent)
{
    if(this.currentFrame == (1, 30))
    {
        gotoAndPlay(66);
    }
    else
    {
        gotoAndPlay(1);
    }
}

function forward(event:MouseEvent)
{
    if(this.currentFrame == 1, 30)
    {
        gotoAndPlay(31);
    }
    if(this.currentFrame == 31, 65)
    {
        gotoAndPlay(66);
    }
    if(this.currentFrame == 66, 100)
    {
        gotoAndPlay(1);
    }
}

A: for all statements you should do:
...
if(event.target.currentFrame == 1  ||  event.target.currentFrame == 30)
    {
        gotoAndPlay(31);
    }
....


Q: Node JS Needle Post Response Body Returned as Buffer I am currently trying to call a remote API from a node.js application that I am writing using needle. The API requires that I make all requests as post requests. when I try to print out the response.body in the console log the only thing that prints out is <Buffer >.
My node.js code is as follows:
var needle = require('needle');
var options = {
    data: { "username": "**********", "password":"******************" },
    headers: {  "Accept":"application/json", "Accept-Encoding":"gzip,deflate", "Content-Type":"application/json" }
};
needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', options, function(err, resp, body) {
  // you can pass params as a string or as an object.
    console.log(body.toString());

Additionally I have tried printing resp, resp.body, body, and all of the aforementioned items with the .toString() method attached. I just want to be able to see the response data returned from the API POST call.

A: The issue is that needle offers shortcuts to create a header for your REST requests. These were overriding my headers and caused a compressed response body to be returned. I simply removed my custom header and used Needle's format instead:
var options = {
    compressed: true,
    accept: 'application/json',
    content_type: 'application/json'
};

I then moved my body to a separate array:
var data = {
  "username": "***********", "password":"*********"
}

Finally I created the request:
needle.post('http://www.linxup.com/ibis/rest/linxupmobile/map', data, options, function(err, resp, body) {
...
}

this then allowed me to access the response body without issues.


Q: How to implement some convenient methods (e.g., flat_map, flatten) on Option? It would be nice if Rust's Option provided some additional convenience methods like Option#flatten and Option#flat_map, where flatten would reduce an <Option<Option<T>> to Option<T>, and flat_map would work like map, but takes a method/closure that returns an Option and flattens it.
flat_map is pretty straightforward:
fn opt_flat_map< T, U, F: FnOnce(T) -> Option<U> >(opt: Option<T>, f: F) -> Option<U> {
  match opt {
    Some(x) => f(x),
    None => None
  }
}

flatten is more complex, and I don't really know how to go about defining it. It might look something like:
fn opt_flatten<T, U>(opt: Option<T>) -> Option<U> {
  match opt {
      Some( Some(x) ) => flatten_option( Some(x) ),
      _ => opt
  }
}

But that certainly doesn't work. Any thoughts?
Also, how would I go about implementing these methods on the Option enum, so that I can use them natively on an Option instance? I know I need to add the type signature in somewhere around impl OptionExts for Option<T>, but I'm at a loss...
Hope this makes sense and I apologize for my imprecise terminology--I'm brand new to Rust.

A: fn flatten<T>(x: Option<Option<T>>) -> Option<T> {
    x.unwrap_or(None)
}

In my case, I was dealing with an Option-returning method in unwrap_or_else and forgot about plain or_else method.

A: These probably already exist, just as different names to what you expect. Check the docs for Option.
You'll see flat_map more normally as and_then:
let x = Some(1);
let y = x.and_then(|v| Some(v + 1));

The bigger way of doing what you want is to declare a trait with the methods you want, then implement it for Option:
trait MyThings {
    fn more_optional(self) -> Option<Self>;
}

impl<T> MyThings for Option<T> {
    fn more_optional(self) -> Option<Option<T>> {
        Some(self)
    }
}

fn main() {
    let x = Some(1);
    let y = x.more_optional();
    println!("{:?}", y);
}

For flatten, I'd probably write:
fn flatten<T>(opt: Option<Option<T>>) -> Option<T> {
    match opt {
        None => None,
        Some(v) => v,
    }
}

fn main() {
    let x = Some(Some(1));
    let y = flatten(x);
    println!("{:?}", y);
}

But if you wanted a trait:
trait MyThings<T> {
    fn flatten(self) -> Option<T>;
}

impl<T> MyThings<T> for Option<Option<T>> {
    fn flatten(self) -> Option<T> {
        match self {
            None => None,
            Some(v) => v,
        }
    }
}

fn main() {
    let x = Some(Some(1));
    let y = x.flatten();
    println!("{:?}", y);
}

Would there be a way to allow flatten to arbitrary depth

See How do I unwrap an arbitrary number of nested Option types?


Q: How to read time from a file without converting My question is general, but I will explain it using a specific example.
Suppose I need to communicate time between two applications. A simple way is to have one application write the output of gettimeofday() (tv_sec and tv_usec) to a file and let the other app read it. The second app needs to 'convert' the strings in order to get an instance of timeval.
Is there any way to avoid the conversion?
Is there a better way to do this than simple file write/read?

A: Assuming both processes are on the same machine (or at least on machines of the same architecture), the results of std::time() (from <ctime>) will be seconds since the Epoch, and will not need any conversion:
std::time_t seconds_since_epoch = std::time(NULL);

Disclaimer: This is not the best method of ipc and you will need to lock the file for reading while it is being written, etc. Just answering the question.

Update, following comment.
If you need to write a timeval, perhaps the easiest way is to define << and >> operators for timeval and write and read these as text to the file (no need to worry about byte-ordering) as-is (with no conversion):
std::ostream& operator <<(std::ostream& out, timeval const& tv)
{
    return out << tv.tv_sec << " " << tv.tv_usec;
}

std::istream& operator >>(std::istream& is, timeval& tv)
{
    return is >> tv.tv_sec >> tv.tv_usec;
}

This will allow you to do the following (ignoring concurrency):
// Writer
{
    timeval tv;
    gettimeofday(&tv, NULL);
    std::ofstream timefile(filename, std::ofstream::trunc);
    timefile << tv << std::endl;
}

// Reader
{
    timeval tv;
    std::ifstream timefile(filename);
    timefile >> tv;
}

If both process are running concurrently, you'll need to lock the file. Here's an example using Boost:
// Writer
{
    timeval tv;
    gettimeofday(&tv, NULL);
    file_lock lock(filename);

    scoped_lock<file_lock> lock_the_file(lock);

    std::ofstream timefile(filename, std::ofstream::trunc);
    timefile << tv << std::endl;
    timefile.flush();
}

// Reader
{
    timeval tv;
    file_lock lock(filename);

    sharable_lock<file_lock> lock_the_file(lock);

    std::ifstream timefile(filename);
    timefile >> tv;

    std::cout << tv << std::endl;
}

...I've omitted the exception handling (when the file does not exist) for clarity; you'd need to add this to any production-worthy code.


Q: How to submit multiple inputs with jquery Seems I can't google the right answer, because I don't know how to ask the question... So I will try to describe the situation.
I have HTML (smarty template):
{foreach $dns_records as $record}

                      <input type="text" name="record[]" id="name" class="form-control" value="{$record.name|escape:html}" />

                      <select class="form-select" name="record[]" id="ttl" {if !$record.ttl}disabled{/if}>
                        <option value="">-</option>
                        {if $record.ttl}
                        {foreach from=$dns_allowed_ttl item=ttl key=key}
                            <option value="{$ttl}" {if $ttl eq $record.ttl}selected{/if}>{$ttl} min.</option>
                        {/foreach}
                        {/if}
                      </select>

                      <select class="form-select" name="record[]" id="type">
                        <option value="">-</option>
                        {foreach from=$dns_record_types item=type key=key}
                            <option value="{$type}" {if $type eq $record.type}selected{/if}>{$type}</option>
                        {/foreach}
                      </select>

                      <input type="text" name="record[]" id="prio" class="form-control" value="{if $record.priority}{$record.priority|escape:html}{else}-{/if}" {if $record.type neq 'MX'}disabled{/if}/>

                      <input type="text" name="record[]" id="content" class="form-control" value="{$record.content|escape:html}"/>

                  {foreachelse}

No records found.

                  {/foreach}

I want to submit those input fields to my PHP like this:
0: ['name', 'ttl', 'type', 'prio', 'content'],
1: ['name', 'ttl', 'type', 'prio', 'content'],
2: ['name', 'ttl', 'type', 'prio', 'content'],
<...>

I use AJAX via jquery:
 $("#records-table").submit(function(event) {

        event.preventDefault();

        if (request) {
            request.abort();
        }

        var $inputs = $("#records-table").find("input, select");

        var record = $('input[name="record[]"]').map(function(){
            return this.value;
        }).get();

        var data = {
            records:  record,
            zone_id:  $inputs.find("#zone_id").val(),
            action:  $inputs.find("#action").val(),
            csrf: $inputs.find("#csrf").val(),
        }

        console.log(data);

        request = $.ajax({
            cache: false,
            url: 'ajax/dns_zone.php',
            type: "post",
            dataType: "json",
            data: JSON.serialize(data)
        });

        request.done(function (response) {
            if (response.response == '1') {
                window.location = response.redirecturl;
            }
        });
    });

How to achieve my goal? I understand that input field must have unique ID's, but I select them via  name with [].

A: So all of your input's name is record[], that will make the record[] value to be something like:
['name', 'ttl', 'type', 'prio', 'content','name', 'ttl', 'type', 'prio', 'content','name', 'ttl', 'type', 'prio', 'content']

Then you could try this:
var final = [];
var value = [];
var i = 1;
$("input[name='record[]']").each(function() {
  value.push($(this).val());
  if(i % 5 == 0) {
    final.push(value);
    value = [];
  }
  i++;
});

It will iterate over all of the record[], creating the new variable for each grouped input. It will be:
[["name", "ttl", "type", "prio", "content"], ["name", "ttl", "type", "prio", "content"], ["name", "ttl", "type", "prio", "content"]]

A: Here is a solution to my problem:
var final = [];
        var value = [];
        var i = 1;
        $("input[name='record[]']").each(function() {
        value.push($(this).val());
        if(i % 5 == 0) {
            final.push(value);
            value = [];
        }
        i++;
        });

        var data = {
            records:  value,
            zone_id:  $(this).find("input[name='zone_id']").val(),
            action:  $(this).find("input[name='action']").val(),
            csrf: $(this).find("#csrf").val(),
        }

        request = $.ajax({
            cache: false,
            url: 'ajax/dns_zone.php',
            type: "post",
            dataType: "json",
            data: $(this).serialize(data)
        });

Here is HTML part:
<form id="records-table">
                {$csrf}
                <input type="hidden" name="action" value="edit_records" />
                <input type="hidden" name="zone_id" value="{$zone.id}" />
                {counter assign=i start=1 print=false}
                {foreach $dns_records as $record}

                      <input type="text" name="record[{$i}][name]" id="name" class="form-control" value="{$record.name|escape:html}" />

                      <select class="form-select" name="record[{$i}][ttl]" id="ttl" {if !$record.ttl}disabled{/if}>
                        <option value="">-</option>
                        {if $record.ttl}
                        {foreach from=$dns_allowed_ttl item=ttl key=key}
                            <option value="{$ttl}" {if $ttl eq $record.ttl}selected{/if}>{$ttl} min.</option>
                        {/foreach}
                        {/if}
                      </select>

                      <select class="form-select" name="record[{$i}][type]" id="type">
                        <option value="">-</option>
                        {foreach from=$dns_record_types item=type key=key}
                            <option value="{$type}" {if $type eq $record.type}selected{/if}>{$type}</option>
                        {/foreach}
                      </select>

                      <input type="text" name="record[{$i}][prio]" id="prio" class="form-control" value="{if $record.priority}{$record.priority|escape:html}{else}-{/if}" {if $record.type neq 'MX'}disabled{/if}/>

                      <input type="text" name="record[{$i}][content]" id="content" class="form-control" value="{$record.content|escape:html}"/>

                  {counter}
                  {foreachelse}

No records found.

                  {/foreach}
                 </form>

Take a note at counter. It iterates array. It is important!


Q: Parse (possibly empty) text and variable definitions inside brackets I'm trying to parse an input into text and variable items. The input may be empty, have only text items, only variable items, or a mix of them.
The following is some sample input:
<>
<a text>
<an escaped \< and an escaped \>>
<${aVar}>
<a text and ${aVar}>
<${aVar} and a text>
<a text ${aVar} ${someMoreVars} and more text>

I tried to parse it with the following grammar:
grammar Translation;

file : ( translation | comment)* EOF ;

translation : '<' ( text | varDef )* '>' ;

varDef : '${' VARDEF '}';

text : TEXT ;

But whatever I tried for the TEXT rule, I either end up parsing everything as text or I get the nasty problem

non-fragment lexer rule TEXT can match the empty string

Which sends me straight on to a stack overflow.
How can I solve the problem?  Do I have to go to an 'island grammar'? I can't see how that would help.
The problem can't be this hard to solve but I am really stuck now.

A: You didn't post your entire grammar, so I cannot tell you what exactly is wrong with your grammar. You can however do something like this to parse your input:
file
 : ( translation | COMMENT )* EOF
 ;

translation : '<' ( text | var_def )* '>' ;

text
 : TEXT+
 ;

var_def
 : VAR_DEF_START text VAR_DEF_END
 ;

COMMENT
 : '//' ~[\r\n]*
 ;

SPACES
 : [ \t\r\n]+ -> skip
 ;
VAR_DEF_START
 : '${'
 ;

VAR_DEF_END
 : '}'
 ;

TEXT
 : '\\' [\\<>]
 | ~[\\<> \t\r\n]
 ;

It is important to match single (!) TEXT characters in the lexer, and "glue" them together inside the text parser rule. If you try to match multiple TEXT chars in the lexer, you will end up matching too much characters.


Q: asp.net Razor output xml dynamicxml How do you just dump/output xml to the page from a razor macro?
I've got a variable which just returns "umbraco.MacroEngines.DynamicXml" with @field
But could do with just outputting just to see what nodes it contains.
Thanks

A: The problem is due to the Razor Scripting settings in the umbracoSettings.config file. It is there that several HTML items are listed that will be ignored as DynamicXml. I have added several to mine to make this problem go away.
<scripting>
    <razor>
        <!-- razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml -->
        <notDynamicXmlDocumentElements>
            <element>p</element>
            <element>div</element>
            <element>ul</element>
            <element>span</element>
            <element>script</element>
            <element>iframe</element>
        </notDynamicXmlDocumentElements>
    </razor>
</scripting>


Q: Notify Raspberry when a new device is connected (USB,SPI,I2C...) What i´m trying to do is: having a daemon running in the background that notify when a new "wired" device is connected to the raspberry.
Can anyone help me?
Thanks all!

A: You can check udev. It's possible to write an udev rule to achieve the behavior. In that way you don't even have to write a daemon.


Q: Oracle-Apex Switch Item value I have column which is data type number(1,0), I decide to use switch item for this column.
I set custom settings. 1 for On and 0 for off.
When I try to edit column, and use off(0) I get error - Column_name must match the values 1 and 0.
When I use On value all works fine.

A: Goku, in apex, the best way to learn (you said yourself you're a beginner) is to write a lot of small apps in a dev environment that only perform one thing. That way you can isolate issues and study behavior in detail. I suggest you do the same for this switch item issue to figure out what the problem is. You have not provided enough information for anyone to answer it so users are giving you their best guesses.
So this is what I did. Create test table
create table so_test_with_switch (
    so_test_with_switch_id         number generated by default on null as identity
                                   constraint so_test_with_switc_id_pk primary key,
    name                           varchar2(255),
    switchval                      number
);

Create a report and form in apex, change the form item for switchval page item (P32_SWITCHVAL) to "Switch" with custom settings: 1 for On and 0 for off. I tested and my form worked fine. The error message indicates that the value apex is getting does not match either 1 or 0 so it must get that value from somewhere else. In my case I added an after submit computation to set the value of P32_SWITCHVAL to 'Y'. Saved my changes, ran the form, clicked "Apply Changes" and I got the same error as you.
It is up to you to figure out where your page item is getting the other value from. Go through your page, investigate and debug. The key to finding the solution is in your code.
--Koen


Q: dc linecharts in a composite chart with group reduction using reduce callback methods I want to make a composite chart with an unknown number of lincharts all based on the same dimension but each of them with call-back reduction functions to calculate count, sum and average but every one filtering data for a given field value of the dimension.
I don't know how to make it work. The graph coordinates and legends appear but no line is painted.
This is what I'm currently doing:
var tablaCount = dc.dataCount("#dataCount");
var tablaDatos = dc.dataTable("#tabla");

var ofs = 0, pag = 10, ndxSize = 0;
var ndx, all;
d3.json("/PruebaConcepto/json/userdashboard-vgodoy-pruebax_20181023111343.json").then(function(data) {
    ndx = crossfilter(data);
    ndxSize = ndx.size();
    all = ndx.groupAll();

    var compositeChartline1 = dc.compositeChart("#lineChartline1");
    var dimensionline1 = ndx.dimension(function(d) { return [d.horasacta, d.aerodromo] ; });
    var groupline1 = dimensionline1.group().reduce(
    function (p, v) {
        ++p.count;
        p.pct = (p.count / ndxSize) * 100;
        p.sum += ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
        p.avg = ((p.sum ? p.sum : 0) / p.count);
        return p;
    },
    function (p, v) {
        --p.count;
        p.pct = (p.count / ndxSize) * 100;
        p.sum -= ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
        p.avg = ((p.sum ? p.sum : 0) / p.count);
        return p;
    },
    function () {
        return {count: 0, pct: 0, sum: 0, avg: 0};
    }
    );

    var keysline1 = groupline1.all().filter(function(d) {return d.key[0]});
    var seriesline1 = [];
    var tmpseriesline1 = [];
    for (var i = 0; i < keysline1.length; i++) {
        tmpseriesline1.push(keysline1[i].key[1]);
    }
    seriesline1 = (tmpseriesline1.filter(function(item, pos) { return tmpseriesline1.indexOf(item) == pos;})).slice();
    tmpseriesline1 = 0;

    var yMaxline1 = 0;
    for (var i = 0; i < groupline1.size() && !(groupline1.top(Infinity)[i] == null); i++) {
        if (yMaxline1 < groupline1.top(Infinity)[i].value.avg) {
        yMaxline1 = groupline1.top(Infinity)[i].value.avg;
        }
    }
    var yMagline1 = Math.pow(10, Math.floor((Math.log(yMaxline1) / Math.LN10 + 0.000000001))) / 10;
    yMaxline1 = Math.ceil(yMaxline1 + yMagline1);

    var xRangeline1 = [];
    var tmpxRangeline1 = [];
    for (var i = 0; i < keysline1.length; i++) {
        tmpxRangeline1.push(keysline1[i].key[0]);
    }
    xRangeline1 = tmpxRangeline1.filter(function(item, pos) { return tmpxRangeline1.indexOf(item) == pos;});
    tmpxRangeline1 = 0;

    var color = ["red", "green", "yellow"];
    var groupsline1 = [seriesline1.length];
    var lineChartsline1 = [seriesline1.length];
    for (var i = 0; i < seriesline1.length; i++) {
    var tmpSeriesline1 = seriesline1[i]
    var tmpGroupline1 = dimensionline1.group().reduce(
                                    function (p, v) {
                                        ++p.count;
                                        p.pct = (p.count / ndxSize) * 100;
                                        p.sum += ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
                                        p.avg = ((p.sum ? p.sum : 0) / p.count);
                                        return p;
                                    },
                                    function (p, v) {
                                        --p.count;
                                        p.pct = (p.count / ndxSize) * 100;
                                        p.sum -= ("viento_int_viento" != "kpigroup" ? (v.viento_int_viento ? v.viento_int_viento : 0) : 0);
                                        p.avg = ((p.sum ? p.sum : 0) / p.count);
                                        return p;
                                    },
                                    function () {
                                        return {count: 0, pct: 0, sum: 0, avg: 0};
                                    }
                                );

    groupsline1[i] = tmpGroupline1.all().filter(function(d) { return d.key[1] == tmpSeriesline1; });

    lineChartsline1[i] = dc.lineChart(compositeChartline1)
                                .group(groupsline1[i], seriesline1[i])
                                .valueAccessor(function(d) {
                                    return parseFloat(d.value.avg);
                                })
                                .title(function(d) {
                                    var s = [];
                                    s.push(d.key[1] + ":");
                                    s.push("Conteo: " + (isNaN(d.value.count) ? "-" : d.value.count + " (" + d.value.pct.toFixed(2) + "%)"));
                                    if ("avg" != "count") {
                                        s.push("Media: " + (isNaN(d.value.avg) ? "-" : d.value.avg.toFixed(2) + ("avg" != "pct" ? "" : "%")));
                                    }
                                    return s.join("\n");
                                })
                                .colors(color[i])
                                .dashStyle([5,5]);
    }

    compositeChartline1
    .width(500).height(500)
    .margins({top: 60, right: 60, bottom: 120, left: 120})
    .x(d3.scaleOrdinal().domain(xRangeline1))
    .xUnits(dc.units.ordinal)
    .y(d3.scaleLinear().domain([0, yMaxline1]).range([500,0]))
    .xAxisLabel("X")
    .yAxisLabel("Y")
    .legend(dc.legend().x(40).y(20).itemHeight(seriesline1.length).gap(10))
    .dimension(dimensionline1)
    .renderHorizontalGridLines(true)
    .brushOn(false)
    .elasticY(true)
    .renderlet(function (chart) {
    chart.selectAll('g.x text').attr('transform', 'translate(-30,30) rotate(315)');
    })
    .compose(lineChartsline1);
}

Thanks in advance.


Q: Ruby on Rails Fields For Issue I'm new to Ruby. Im working on a project and i got stuck at someplace. I have two html pages, company_profile and job. This job page is rendered inside company_profile page and there is an add job button which renders this. This is inside company_profile.html.erb
<% @job_count = 0 %>
<script type="text/html" id="new_company_job_div">
 <%= render 'job', job: Job.new(company_id: @company.id), f: f %>
</script>

and inside my job.html.erb i've
<% @job_count += 1 %>
<%= @job_count %>

and some other codes too..
My issue:  First time when i add a job, job_count goes to 1 and from there that job_count value is not increasing. It is stuck there.
I have also written a code to render the jobs page if its present in database.. this is that part of code in comapny_profile that loads the existing columns.
 <% if @company.jobs.present? %>
                        <% @company.jobs.each do |job| %>
                            <%= render 'job', job: job, f: f %>
                        <% end %>
                    <% end

%>

That is if there are 2 columns inside jobs table with matching id those 2 will be present in the page as soon as it loads and also with add job we can add more. In this case if 2 jobs are in table job_count will be 2 and on pressing add_count count value will be 3 and from there onwards count_value is not increased. Appending and all are working fine..
pls help

A: My issue at first time when i add a job job_count goes to 1 and from there taht job_count value is not increasing

The problem is probably because you're using an instance variable
From what I can see, you're reloading the page each time you wish to load job (it's a one time thing); meaning the data is not going to persist between requests
If you want to store a variable over different requests, you'll either have to populate it continuously in the backend, or use a persistent data store - such as a cookie or session

Try this:
<% session[:job_count] = 0 %>
<script type="text/html" id="new_company_job_div">
 <%= render 'job', job: Job.new(company_id: @company.id), f: f %>
</script>

<% session[:job_count] += 1 %>
<%= session[:job_count] %>

This is the best I can do without any further context

A: Use collection partial:
In app/views/companies/show.html.erb
<%= render @company.jobs %>

In app/views/jobs/_job.html.erb
<%= job_counter %> # value based on the number of jobs you have
<%= job.foo %>


Q: Java Scheduling task I am developing a spring mvc project where a notification will send to user mobile.User will select a datetime at format 'yyyy-MM-dd HH:mm' from frontend and save it to the database.when system time reach that time a notification will be send to the user mobile .
I created scheduler like this
  @Component
  public class NotificationScheduler extends BaseService {

  @Scheduled(fixedRate = 300000)
  public void sendNotification() {

    Date currentDate = new Date();

    System.err.println("HHHHHHHHHKKKKKK");

    List<ImageInfo> listImageInfo = imageInfoDao.getImageOfParticularDate(currentDate);

 }
}

this is my dao function which run a wuery to database
  public List getImageOfParticularDate(Date date) {
    session = getSession();
    session.beginTransaction();
    List<ImageInfo> imageInfoList = session.createQuery("select img from ImageInfo img where img.publishedTime =:publishedTime  ").setParameter("publishedTime", date).list();
    session.getTransaction().commit();
    return imageInfoList;
}

this code is checking repeatedly at 5 min interval whether system time equal to publish time.if it is equal then a notification will be sent.I used Date type in model and Date type column in database. I want to know my approach is right or wrong because i can not get desire output.

A: Why don't you use a debug mode? Change, your the time rate you use in order to not wait too much, but I think you could determine that yourself, could you?


Q: Vue 3 render dynamic comment How can I properly render a dynamic comment in Vue 3? I tried v-html which is not working in my case, for example, https://i.imgur.com/EtrVmGu.png
<template>

  <template v-html="COMMENT" />

  {{ COMMENT }}

   content here

</template>

A: The v-html should be mounted in real html tag not the virtual template :

You could see the comment inside the inspected DOM

A: You may also use dynamic component with the <component is>
Vue JS Dynamic Components
And put all your comment component code in a different file: comment.vue
<template>

Dynamic Component

  <component :is='currentComponent'>
</template>

A: Create a component Comment.vue that uses render function to create a comment

Usage:

<template>
  <Comment content="Hi, I'm just a comment!"/>
</template>

Rendered comment:

The vue internal api is not designed for these kinda hacks. So, please use carefully.


Q: May I place


Q: Invalid date django form validation I am learning Django and building a CRUD but I'm getting an error in my form validation.
This is the form that ** I created**
class addSignForm(forms.ModelForm):
active = forms.CharField(max_length=10)

class Meta:
    model = signs
    fields = ("id", "active", "action", "date", "expiration_date", "add_by", "user_sign")
    widgets = {
        'date': forms.DateTimeInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'),
    }

This is the date that I am receiving from the request **(also tried format: '%y-%m-%dT%H:%M'
'2000-04-16T18:57'

And when I try to:
if (form.is_valid()):

says that it is an invalid form and that I typed an invalid date

Enter a valid date/time.

can someone help me

A: "2000-04-16T18:57" is not %d/%m/%Y %H:%M format but %Y-%m-%dT%H:%M format. Check list date formatters here https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes

A: Your widget format just show for client, not for Form.So you can try add a method named clean_date(self) to replace 'T' with whitespace then return it.
or add your format into DATETIME_INPUT_FORMATS list of settings.py.

A: i ended up managing to solve the problem, however I did not like the solution because it does not seem the most right ... however I will share it here in case people experience the same problem :)
What i did was:
create a copy of my GET so it becomes mutable
getCopy = request.GET.copy()

after that i converted the DATE that was comming from GET
ts = time.strptime(request.GET['date'], "%Y-%m-%dT%H:%M")
getCopy['date'] = time.strftime("%m/%d/%Y", ts)

and when i call my form.is_valid instead of passing request.GET, i pass my mutable copy of GET with my formatted date :)


Q: Kendo UI how to get the id of elements during drop event? I have the following HTML and would like to get the DOM elements for the elements involved in the drag and drop event. Also, if you could tell me how i might be able to figure this out using debugger, that would be even better!
Here is the code:

proud

strong

merry

friendly

Drop here

Drop here

Drop here

Drop here

A:  function onDrop(e) {
     // Get the id of the elements involved in the drag and drop event
         var source = $(e.draggable.element).attr('id');
         var target = e.dropTarget.attr('id');
 }


Q: Avoid Terraform module to create duplicate resources? I have the following project structure to build Lambda functions on AWS using Terraform :
.
├── aws.tf
├── dev.tfvars
├── global_variables.tf -> ../shared/global_variables.tf
├── main.tf
├── module
│   ├── data_source.tf
│   ├── main.tf
│   ├── output.tf
│   ├── role.tf
│   ├── security_groups.tf
│   ├── sources
│   │   ├── function1.zip
│   │   └── function2.zip
│   └── variables.tf
└── vars.tf

In the .main.tf file i have this code that will create 2 different lambda functions :
module "function1" {
  source = "./module"

  function_name    = "function1"
  source_code      = "function1.zip"

  runtime          = "${var.runtime}"
  memory_size      = "${var.memory_size}"
  timeout          = "${var.timeout}"
  aws_region       = "${var.aws_region}"
  vpc_id           = "${var.vpc_id}"
}

module "function2" {
  source = "./module"

  function_name    = "function2"
  source_code      = "function2.zip"
  runtime          = "${var.runtime}"
  memory_size      = "${var.memory_size}"
  timeout          = "${var.timeout}"
  aws_region       = "${var.aws_region}"
  vpc_id           = "${var.vpc_id}"
}

The problem is that in deployment terraform create all resources twice. For Lambda it's Ok, that's the purpose, but for security groups and Roles that's not what i want.
For example this security group is create 2 times :
resource "aws_security_group" "lambda-sg" {
  vpc_id = "${data.aws_vpc.main_vpc.id}"
  name   = "sacem-${var.project}-sg-lambda-${var.function_name}-${var.environment}"

  egress {
    protocol    = "-1"
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    protocol        = "-1"
    from_port       = 0
    to_port         = 0
    cidr_blocks     = "${var.authorized_ip}"
  }
  # To solve dependcies error when updating the security groups
  lifecycle {
    create_before_destroy = true
    ignore_changes        = ["tags.DateTimeTag"]
  }

  tags = "${merge(var.resource_tagging, map("Name", "${var.project}-sg-lambda-${var.function_name}-${var.environment}"))}"

}

So that's clear that the problem is the structure of the project. Could you help to solve that ?
Thanks.

A: If you create the SecurityGroup within the module, it'll be created once per module inclusion.
I believe that some of the variable values for the sg name change when you include the module, right? Therefore, the sg name will be unique for both modules and can be created twice without errors.
If you'd choose a static name, Terraform would throw an error when trying to create the sg from module 2 as the resource already exists (as created by module 1).
You could thus define the sg resource outside of the module itself to create it only once.
You can then pass the id of the created sg as variable to the module inclusion and use it there for other resources.


Q: Square root inside a square root python I was wondering how to write a code showing the square root inside a square root. This is what I have so far:
number=float(input("Please enter a number: "))
square = 2*number**(1/2)**(1/3)
print(square)

But that's not right as I'm getting a different number from the calculator.

A: Import math and use math.sqrt(math.sqrt(number))
import math
number=float(input("Please enter a number: "))
square = math.sqrt(math.sqrt(number))
print(square)

A: It looks like it is doing the square root (i.e., 1/2) of 1/3 and then applying that to number. You'll want to force the order of operations since it's evaluating the exponent operator from right to left.
square = 2*(number**(1/2))**(1/3)

By adding parenthesis, you are forcing it to take the square root first, and then the cube root.

You are using Python3, but for future readers, Python2 would evaluate 1/2 and 1/3 to 0. To change that you'd use floats instead:
square = 2*(number**(1.0/2.0))**(1.0/3.0)

A: If you want to find the square root of the square root of a number you can see using some algebra we can see that ((x)^0.5)^0.5) simplifies down to x^(0.25)
So you can either do x**(0.25)
or you can do the following:
import math
math.sqrt(math.sqrt(x))

One other thing, in your code you say:
square = 2*number**(1/2)**(1/3)

and in the title you say "Square root inside a square root python". This indicates to me that you might have made either a typo in your code or mistake in naming the title of your question. If you do want to find a square root of a square root then my suggestions above should be sufficient to do that.


Q: Running rospy dependent file in Github Actions I'm trying to implement CI with Github Actions to a repository. In the workflow, I would like to run a test script using pytest. However, the test script and the script it is testing had a rospy dependency, although the dependency is not vital to the test, where it is publishing the result of certain calculation (node.Publisher is mocked using pytest).
I'm still new to ROS and I am a bit confused about what I need to install. Do I need to install the whole ROS library for the test or do I only need to install rospy? What is the best way to install the package and add it to the path in Github Actions?
I tried sudo apt-get install -y python-rospy, but the package is not detected by python with ImportError: No module named rospy.
I am running the test in Ubuntu 18.04.
Thank you in advance


Q: What is the correct way to resolve warnings at Redis startup when using Docker? When I run my Redis Docker image, I face these warnings:
# Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
( ... )
# WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
( ... )
# WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.

Among the solutions I found in the internet, this one looks cover everything, but when I try it in Docker scope (Eg.: changing my Dockerfile to apply them), I get the error "Read-only file system". Manually example give me the same issues:
[root@769368ed0fc5 /]# sysctl -w net.core.somaxconn=65535
sysctl: setting key "net.core.somaxconn": Read-only file system
[root@769368ed0fc5 /]# echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
[root@769368ed0fc5 /]# sysctl vm.overcommit_memory=1
sysctl: setting key "vm.overcommit_memory": Read-only file system
[root@769368ed0fc5 /]# echo never > /sys/kernel/mm/transparent_hugepage/enabled
bash: /sys/kernel/mm/transparent_hugepage/enabled: Read-only file system
[root@769368ed0fc5 /]# echo never > /sys/kernel/mm/transparent_hugepage/enabled
bash: /sys/kernel/mm/transparent_hugepage/enabled: Read-only file system

Does anyone know how to fix it in a proper way? I have found a lot of tricks to workaround it, like:

*

*Run container in privileged mode

*Mount host /proc inside a container

*Use host network stack (--net=host)

*

*Looks like this one is inevitable, because Redis doesn't support NATed environments, but anyway it doesn't solve everything.

I want to know what is the correct way to deal with it in Docker. Answers that provide technical explanation about the proposed solution will be appreciated.


Q: Get vs Post Auto Mapping dates C# I am having some confusion figuring out why I am experiencing the following:
If I using jquery AJAX to "post" some Json data containing a date to an MVC controller the automapper maps the date in the format dd/mm/yyyy however if I use "get" instead the automapper seems to convert the date in to the format mm/dd/yyyy.
Does anybody know why this would be the case? When I check the json payload and querystrings for the post and get respectively they are both in the same format. The date I am using goes across as "1/7/2013" in both cases.
Regards,
Gary

A: Are you using a JSON serializer for the POST but a DateTime.Parse for the GET? This could yield two different results.
User DateTime.ParseExact to ensure consistent results. I.E.
DateTime.ParseExact(input, "dd/MM/yyyy HH:mm", null);


Q: Set Meta Tag With jQuery I'm having trouble with a mobile page that uses a site of ours in an iframe.
It works fine on desktop but on mobile the page doesn't resize correctly. Based on internal testing it seems that the page is missing this meta tag:
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
Is there any way to set that via jQuery and have it actually take effect?
In theory I believe that using this SO article I could inject the meta tag like this:
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">');

But it seems the problem really comes down to forcing it to re-parse the html. Is there a way I could do that?

A: Yes you can append a meta tag, but no you can't force reparsing of the html. The browser is going to ignore any changes you make.


Q: Calling multiple httpclient that contain two different base address I have read up on named clients and typed clients in order to achieve my ultimate goal. However, I still do not understand how I need to implement either or. I have a blazor server side project that in the startup.cs file I have it set up as
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("http://localhost:36626") });
services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5443") });
I know that if I do this, the baseaddress of the first one will completely be overwritten and no longer be the set base address due to the second baseaddress. How would I go about making this work so that way I have two separate httpclients that will have two separate baseaddress without having to lose one because of the most recent line of code?

A: As said in the doc, the main differences are in how you are going to get an instance through Dependency Injection.
With Named Client you need to inject the factory and then get the client by a string.
var client = _clientFactory.CreateClient("github");

With Typed Client you can inject the client needed as a type.
//GitHubService encapsulate an HTTP client
public TypedClientModel(GitHubService gitHubService)
    {
        _gitHubService = gitHubService;
    }

Both of them give the solution to your problem. The selection is more in how comfortable you are with the dependency injection method of each one. I personally prefer the Typed client.


Q: Unable to create directory in External Storage public directory I am attempting to create a directory and file so that I can store files that I have downloaded from the Internet. However, I am unable to create the directory and file in the external public storage. If I write to the external private storage (specific storage location for the app) I am perfectly able to do so.
Here is the code:
    String storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
    System.out.println(storageDirectory);
    File mediaDir = new File(storageDirectory);
    if (!mediaDir.exists()) {
        System.out.println(mediaDir.mkdirs());
        System.out.println(mediaDir.isDirectory());
    }
    File mediaFile = new File(storageDirectory, "boga.jpg");
    try {
        mediaFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

The above code results in:

09-13 05:33:45.258    5867-5867/? I/System.out﹕ /storage/0CED-0F09/Pictures

09-13 05:33:45.260    5867-5867/? I/System.out﹕ false
09-13 05:33:45.260    5867-5867/? I/System.out﹕ false
With an IOException (No such file or directory):

09-13 05:33:45.260    5867-5867/? W/System.err﹕ java.io.IOException: open failed: ENOENT (No such file or directory)
09-13 05:33:45.260    5867-5867/? W/System.err﹕ at java.io.File.createNewFile(File.java:939)
09-13 05:33:45.260    5867-5867/? W/System.err﹕ at com.example.terabyte.tut1app.MainActivity.onCreate(MainActivity.java:78)

And this is my manifest:
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

What could be the issue?

A: Turns out I am fully capable of writing to the external storage directory on a real smartphone device (Huawei P8 api level 21, Version 5.0). But not to the emulator's external storage, even though the storage is fully available and can be browsed from within the emulator.
This also helped me in figuring out issues with the external storage on a real device: https://stackoverflow.com/a/6311955/5330055
I have no longer urgently require a solution on this, but it would be nice to know what is wrong with the emulator.

A: Actually nothing wrong with emulator.
Probably device you have used on emulator were on android equal or higher than version 6.0
In 6.0 and higher versions you need to request write permission at runtime. WRITE_EXTERNAL_STORAGE
in your smartphone it worked because it was on android 5.0
if this help someone I will glad.


Q: Accumulate promise values "functionally" Say I have this:
function getAllPromises(key: string, val: any): Promise {

 const subDeps = someHash[key];
 const acc = {}; // accumulated value

 return subDeps.reduce(function (p, k) {

  return p.then(v => getAllPromises(k, v)).then(function (v) {
        acc[k] = v;
        return acc;
   });

 }, Promise.resolve(val));

}

is there a way to avoid having to declare a separate variable:
const acc = {}; // accumulated value

and somehow return that from the promise chain instead?
Ultimately the acc variable is what gets resolved from the promise chain, but wondering if I can somehow avoid having to declare it "outside" the chain.
Edit: the seed data for something like this looks like:
  {
    'one': [function (v) {
      return Promise.resolve('one');
    }],

    'two': ['one', function (v) {
      return Promise.resolve('two');
    }],

    'three': ['one', 'two', function (v) {
      return Promise.resolve('three');
    }],

  }

It's just a declarative dependency tree. Dependencies can be resolved in parallel; but may effectively block, as they run. For example, if I have a function like so:
function foo(one,two,three){

}

I want to inject these 3 dependencies. They can be sourced "in parallel", but three will be blocked until one and two are procured.
What is the subDeps variable? In the case of key="three", subDeps is ['one','two'].

A: You can pass an array at second parameter to .reduce(), within .reduce() callback use destructing assignment to get Promise and object passed
return subDeps.reduce(([p, acc], k) =>
         [p.then(v => getAllPromises(k, v)).then(v => Object.assign(acc, {[k]:v}))
         , acc];
       }, [Promise.resolve(val), {}]).shift()//.then(result => /* result : acc */)

A: I'm going out on a bit of a limb, here, in thinking that the whole list of subDeps for any child node can be loaded in parallel. In looking at the problem, deeper, I see no reason for that not to be the case. In fact, the only potential problem I could see is that some value above but not below this point could be a promise, and thus, you might even be able to strike the promises from this particular recursive function...
but...
Here's what I saw as a plausible refactor. Let me know if that's missing some obvious need.
const appendKeyValue = (dict, [key, value]) => {
  dict[key] = value;
  return dict;
};

const getKeyValuePair = hash => key =>
  getRefactoredPromises(hash, hash[key])
    .then(value => [key, value]);

const getRefactoredPromises = (someHash, subDeps) => {
  return Promise.all(subDeps.map(getKeyValuePair(someHash)))
    .then(pairs => pairs.reduce(appendKeyValue, {}));
};

In fact, if I'm right about this refactor, then you don't even need the promises in there. It just becomes:
const appendKeyValue = (dict, [key, value]) => {
  dict[key] = value;
  return dict;
};

const getKeyValuePair = hash => key =>
  [key, getRefactoredHash(hash, hash[key])];

const getRefactoredHash = (someHash, subDeps) =>
  subDeps.map(getKeyValuePair(someHash))
         .reduce(appendKeyValue, {});

If the root level of this call happens to be a promise, that should be inconsequential at this point, unless there's something I'm missing (it IS 6:20am, and I've yet to close my eyes).


Q: Protect sidekiq admin with devise (documented way not working) I have an app that uses devise/omniauth for authentication, and runs a bunch of sidekiq workers.
I would like to protect /sidekiq and /sidekiq_monitor routes with devise as well, but so far I am running into a lot of trouble doing that.
The documented solution is to do this in routes.rb:
authenticate :user do
  mount Sidekiq::Web => '/sidekiq'
end

But that isn't working for me - what happens when I add that is that if a user goes to /sidekiq they are prompted to login regardless of their auth status, and if they login and go back to /sidekiq they are once again prompted to login.
Possible wrinkles - I am logging in via omniauth-saml, which means some redirects are happening in the mix here - but that's working fine with all other auth on my site. I am also only using a very minimal bit of devise, just:
devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:saml]

A: Try changing in your routes.rb file to this:
authenticate :user do
  mount Sidekiq::Web, at: "/sidekiq"
end

Also notice that :user refers to your app user model. If your user model has another name, let's say :admin, you should replace :user to :admin in the snipped code above.

A: try this inside of your routes:
Sidekiq::Web.use Rack::Auth::Basic do |username, password|
   username == USERNAME && password == PASSWORD
end if Rails.env.production?

mount Sidekiq::Web, at: "/sidekiq"


Q: Tomcat + Grails cluster doesnt work I have a Tomcat cluster over Debian Jessie, Tomcat 8.0.29 2 instances , PostgreSQL 9.5 ,Apache 2.4 , Mod_jk. When I try to run my project in this environment I get eerror. I tested with examples project and it works fine. My log iis this
01-Feb-2016 19:07:39.474 SEVERE [main] org.apache.catalina.ha.deploy.FarmWarDeployer.start FarmWarDeployer can only work as host cluster subelement!
01-Feb-2016 19:07:39.537 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo /opt/tomcat8_nodo1/webapps/clusterjsp.war de la aplicación web
01-Feb-2016 19:07:40.886 INFO [MessageDispatch15Interceptor.MessageDispatchThread1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:1 messages
        Sent:0.00 MB (total)
        Sent:0.00 MB (application)
        Time:0.01 seconds
        Tx Speed:0.06 MB/sec (total)
        TxSpeed:0.06 MB/sec (application)
        Error Msg:0
        Rx Msg:2 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:0.00 MB]

01-Feb-2016 19:07:42.068 INFO [localhost-startStop-1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1.489] milliseconds.

01-Feb-2016 19:07:42.088 INFO [localhost-startStop-1] org.apache.catalina.tribes.tipis.AbstractReplicatedMap.init Initializing AbstractReplicatedMap with context name:localhost#/clusterjsp-map

01-Feb-2016 19:07:42.310 INFO [localhost-startStop-1] org.apache.catalina.tribes.tipis.AbstractReplicatedMap.init AbstractReplicatedMap[localhost#/clusterjsp-map] initialization was completed in 222 ms.

01-Feb-2016 19:07:42.585 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/clusterjsp.war has finished in 3.048 ms

01-Feb-2016 19:07:45.652 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Despliegue del archivo /opt/tomcat8_nodo1/webapps/abacus.war de la aplicación web
01-Feb-2016
19:14:05.387 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars Al menos un JAR, que se ha explorado buscando TLDs, aún no contenía TLDs. Activar historial de depuración para este historiador para una completa lista de los JARs que fueron explorados y de los que nos se halló TLDs. Saltarse JARs no necesarios durante la exploración puede dar lugar a una mejora de tiempo significativa en el arranque y compilación de JSP .
feb 01, 2016 7:14:05 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: Initializing AtmosphereFramework

feb 01, 2016 7:14:05 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: No Spring WebApplicationInitializer types detected on classpath
feb 01, 2016 7:14:06 PM org.apache.catalina.core.ApplicationContext log

INFORMACIÓN: Initializing Spring root WebApplicationContext
feb 01, 2016 7:14:54 PM org.apache.tomcat.jdbc.pool.ConnectionPool init
ADVERTENCIA: maxActive is smaller than 1, setting maxActive to: 100

<strong>
2016-02-01 19:14:59,345 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing the application: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
2016-02-01 19:14:59,346 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing Grails: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
feb 01, 2016 7:14:59 PM org.apache.catalina.core.StandardContext listenerStart

GRAVE: Excepción enviando evento inicializado de contexto a instancia de escuchador de clase org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in class path resource [org/springframework/scheduling/annotation/ProxyAsyncConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor org.springframework.scheduling.annotation.ProxyAsyncConfiguration.asyncAdvisor()] threw exception; nested exception is java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more
Caused by: java.lang.IllegalArgumentException: @EnableAsync annotation metadata was not injected
        ... 5 more

01-Feb-2016 19:14:59.347 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal One or more listeners failed to start. Full details will be found in the appropriate container log file
01-Feb-2016 19:14:59.349 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Falló en arranque del Contexto [/abacus] debido a errores previos
feb 01, 2016 7:14:59 PM org.apache.catalina.core.ApplicationContext log
INFORMACIÓN: Closing Spring root WebApplicationContext
01-Feb-2016 19:14:59.363 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesJdbc La aplicación web [abacus] registró el conductor JDBC [org.postgresql.Driver] pero falló al anular el registro mientras la aplicación web estaba parada. Para prevenir un fallo de memoria, se ha anulado el registro del conductor JDBC por la fuerza.
</strong>

01-Feb-2016 19:14:59.371 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat8_nodo1/webapps/abacus.war has finished in 433.719 ms
01-Feb-2016 19:14:59.373 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/ROOT de la aplicación web
01-Feb-2016 19:14:59.434 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/ROOT has finished in 61 ms

01-Feb-2016 19:14:59.435 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/manager de la aplicación web
01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/manager has finished in 45 ms
01-Feb-2016 19:14:59.479 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/examples de la aplicación web
01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/examples has finished in 247 ms
01-Feb-2016 19:14:59.726 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Despliegue del directorio /opt/tomcat8_nodo1/webapps/host-manager de la aplicación web
01-Feb-2016 19:14:59.743 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /opt/tomcat8_nodo1/webapps/host-manager has finished in 17 ms
01-Feb-2016 19:14:59.750 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]

01-Feb-2016 19:14:59.760 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 442905 ms
01-Feb-2016 22:35:59.831 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:10,000 messages
        Sent:6.81 MB (total)
        Sent:6.81 MB (application)
        Time:2.39 seconds
        Tx Speed:2.85 MB/sec (total)
        TxSpeed:2.85 MB/sec (application)
        Error Msg:0
        Rx Msg:10,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:6.81 MB]

01-Feb-2016 22:35:59.832 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:10,000 messages
        Sent:6.81 MB (total)
        Sent:6.81 MB (application)
        Time:2.39 seconds
        Tx Speed:2.85 MB/sec (total)
        TxSpeed:2.85 MB/sec (application)
        Error Msg:0
        Rx Msg:10,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:6.81 MB]

02-Feb-2016 02:04:23.818 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:20,000 messages
        Sent:13.62 MB (total)
        Sent:13.62 MB (application)
        Time:4.07 seconds
        Tx Speed:3.35 MB/sec (total)
        TxSpeed:3.35 MB/sec (application)
        Error Msg:0
        Rx Msg:20,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:13.62 MB]

02-Feb-2016 02:04:23.820 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:20,000 messages
        Sent:13.62 MB (total)
        Sent:13.62 MB (application)
        Time:4.07 seconds
        Tx Speed:3.35 MB/sec (total)
        TxSpeed:3.35 MB/sec (application)
        Error Msg:0
        Rx Msg:20,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:13.62 MB]

02-Feb-2016 05:32:47.761 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:30,000 messages
        Sent:20.43 MB (total)
        Sent:20.43 MB (application)
        Time:5.72 seconds
        Tx Speed:3.57 MB/sec (total)
        TxSpeed:3.57 MB/sec (application)
        Error Msg:0
        Rx Msg:30,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:20.42 MB]

02-Feb-2016 05:32:47.763 INFO [Tribes-Task-Receiver-6] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:30,000 messages
        Sent:20.43 MB (total)
        Sent:20.43 MB (application)
        Time:5.72 seconds
        Tx Speed:3.57 MB/sec (total)
        TxSpeed:3.57 MB/sec (application)
        Error Msg:0
        Rx Msg:30,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:20.42 MB]

02-Feb-2016 09:01:11.617 INFO [Tribes-Task-Receiver-5] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:40,000 messages
        Sent:27.23 MB (total)
        Sent:27.24 MB (application)
        Time:7.38 seconds
        Tx Speed:3.69 MB/sec (total)
        TxSpeed:3.69 MB/sec (application)
        Error Msg:0
        Rx Msg:40,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:27.23 MB]

02-Feb-2016 09:01:11.618 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:40,001 messages
        Sent:27.24 MB (total)
        Sent:27.24 MB (application)
        Time:7.38 seconds
        Tx Speed:3.69 MB/sec (total)
        TxSpeed:3.69 MB/sec (application)
        Error Msg:0
        Rx Msg:40,002 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:27.23 MB]

02-Feb-2016 12:29:35.561 INFO [Tribes-Task-Receiver-2] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:49,999 messages
        Sent:34.04 MB (total)
        Sent:34.04 MB (application)
        Time:8.99 seconds
        Tx Speed:3.79 MB/sec (total)
        TxSpeed:3.79 MB/sec (application)
        Error Msg:0
        Rx Msg:50,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:34.04 MB]

02-Feb-2016 12:29:36.108 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:50,000 messages
        Sent:34.04 MB (total)
        Sent:34.05 MB (application)
        Time:8.99 seconds
        Tx Speed:3.79 MB/sec (total)
        TxSpeed:3.79 MB/sec (application)
        Error Msg:0
        Rx Msg:50,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:34.04 MB]

02-Feb-2016 15:57:59.873 INFO [Tribes-Task-Receiver-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:59,999 messages
        Sent:40.85 MB (total)
        Sent:40.85 MB (application)
        Time:10.64 seconds
        Tx Speed:3.84 MB/sec (total)
        TxSpeed:3.84 MB/sec (application)
        Error Msg:0
        Rx Msg:60,000 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:40.85 MB]

02-Feb-2016 15:58:00.431 INFO [GroupChannel-Heartbeat-1] org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor.report ThroughputInterceptor Report[
        Tx Msg:60,000 messages
        Sent:40.85 MB (total)
        Sent:40.85 MB (application)
        Time:10.64 seconds
        Tx Speed:3.84 MB/sec (total)
        TxSpeed:3.84 MB/sec (application)
        Error Msg:0
        Rx Msg:60,001 messages
        Rx Speed:0.00 MB/sec (since 1st msg)
        Received:40.85 MB]

A: There are many different possible causes to this problem. Two top suspects are:

*

*You are using a plug-in that is triggering a component scan of Spring classes.

*Your code has added a component scan that is hitting Spring classes.

A search for "component-scan" throughout your project can help you check for those two causes.


Q: Bootstrap 4: I'd like my columns to take the full width of my container I would like my columns to take the full width of my container, I have tried many things but haven't find a solution how to fix it.
Here's an example of what I want:

While it looks like this for now:

See the little red arrows? This is the space that I don't want to see.
HTML:

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

CSS:
.framework {
    background: rgb(27,28,30);
    background: linear-gradient(180deg, #1b1c1e 0%, #27262d 200%);
    display:grid;
    max-width:100%;
    padding:30px 10px 30px 10px;
    margin-top:0.5em;
    height:100%;
    margin-left: auto;
    margin-right: auto;

    .card {
        background: #27262d;
        border-radius:5px;
    }

    img {
        width:50px;
        height:auto;
        display:block;
        margin-left:auto;
        margin-right:auto;
        margin-top:15px;
    }
}

CSS (for Mobile version) :
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@800&display=swap');

.framework {
    .card-title {
        font-family:'Open Sans',sans-serif;
        font-weight:800;
        font-size:14pt;
        text-align:left;
        text-transform:uppercase;
    }

    .card-text {
        font-family:geomanist,sans-serif;
        color:rgba(255, 255, 255, 0.377);
        font-weight:400;
        font-size:10pt;
        letter-spacing:-0.1px;
        line-height:15px;
        text-align:left;
    }

    @media only screen and (max-width: 600px) {
        .card-title {
            font-size:11pt;
            }
        .card-text {
            font-size:9pt;
        }
    }

}

edit (10/19/2020 | 12:09 [brussels])kind of fixed it by adding class ".mx-md-n5" next to class ".row" in the same div, this aint perfect but it satisfies me

A: Please add pl-0 and pr-0 class for the remove the padding

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

A:

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's content.

A: Please use the predefined Bootstrap classes at first and if you have any custom CSS add it in a new classes.
Is this what you search for:
HTML

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's
          content.

Privacy & Security

Some quick example text to build on the card title and make up the bulk of the card's
          content.

A: this is a demo for what exactly you want I have just remove padding for the full-width box and for the next two box I remove padding-left for left side box and padding-right for the right side box.
this is the code snippet which helps you to understand what I do.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

          Box 1

          Box 2

          Box 3

I hope this answer will help you to solve your problem this time and also help you in future for this type of structure.
Thank you...


Q: Are variables de-allocated when they go out of scope Given this code snippet
def doSomething() = {

    val associations : HashMap[Int, Int] = function_that_create_a_hashmap
    println("something")
}

When doSomething terminates is the variable associations de-allocated? Should I call some destructor on it (maybe .clear, in this case) or is that operation not useful?

A: That is not necessary - if your application has no more references to the HashMap, then it will be garbage collected automatically at some point in the future.
If you really have a huge hash map that you want to get rid off to avoid its memory consumption trigger GC cycles after doSomething completes, you can call System.gc(), but this is in general neither needed nor a recommended practice.

A: Calling .clear on a HashMap doesn't remove it from memory; it simply clears it of preexisting mappings and so the object will still exist in memory.
Since Scala runs on the JVM, I would imagine that it will get collected by the garbage collector at some point in the future (assuming that there are no existing-references to associations). The JVM manages its own memory, thus freeing the programmer of the burden of manually-managing memory.

A: The binding associations ceases to exist when the scope in which it was created ceases to exist (when a given call to doSomething returns). That removes one reference to the HashMap and once there are none left, the value is garbage and subject to reclamation at an unspecified time in the future (possibly never / not before the JVM exits).


Q: Facebook SDK Graphrequest returns null Using Facebook SDK 4.4 in Xamarin.Android project. I have the following method :
protected override void OnCreate(Bundle savedInstanceState)
{
 LoginButton button = FindViewById<LoginButton>(Resource.Id.FbLoginBtn);
 button.SetReadPermissions(new List<string>{ "public_profile", "email" });
 mCallBackManager = CallbackManagerFactory.Create();
 button.RegisterCallback(mCallBackManager, this);
 button.Click += (o, e)=>
  {
    GraphRequest request = GraphRequest.NewMeRequest(AccessToken.CurrentAccessToken, this);
    Bundle paramenters = new Bundle();
    paramenters.PutString("fields", "id,name,email,first_name,last_name");
    request.Parameters = paramenters;
    request.ExecuteAsync();
  };
}

public void OnCompleted(JSONObject @object, GraphResponse response)
{
  if (@object != null)
  {
   userEmail.Text = @object.ToString();
  }
 }

The problem with the above code is that, in the OnCompleted method, the JSONObject always return null when i log in to my facebook account from the app. But when i click the button again to Log Out, i get the proper json with all fields that i specified.
My question is, why is the GraphRequest returning null upon log-in but successfully returns the JSON upon log out?


Q: Why there is no Server Name under integration services in SSMS? I cant connect to Integration Services in SSMS there is no Server Name under it when I browse , if I type manually the server name based on how other services have it says class not registered

A: If someone else has the same problem the reason was because I had installed SSIS 2017 but was using SSMS 18.x , if you have SSIS 2017 use SSMS 17.x and such with other versions


Q: Mystery gaps in CSS Grid In the snippet below, there are gaps above and beneath 'main' area which suppose to be an empty cells with the same height as the grid cells. Also there is an empty space at the very bottom.
I've tried setting grid-auto-flow to different values, but there is no effect except for the very bottom gap when it set to column.
What causes that? and how to fix it?

.header {
    grid-area: hd;
}
.footer {
    grid-area: ft;
}
.content {
    grid-area: main;
}
.sidebar {
    grid-area: sd;
}
* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    max-width: 940px;
    margin: 0 auto;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
}
.wrapper {
    display: grid;

    grid-auto-rows: minmax(auto, auto);
    grid-template-areas:
      "hd hd ft"
      "sd . ft"
      "sd main ft"
      "sd . ft";
}

Header

Sidebar

Content

Footer

A: **I tested the code on Chrome and Firefox and the result was **

Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect.

.header {
    grid-area: hd;
}
.footer {
    grid-area: ft;
}
.content {
    grid-area: main;
}
.sidebar {
    grid-area: sd;
}
* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    max-width: 940px;
    margin: 0 auto;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
}
.wrapper {
    display: grid;

    grid-auto-rows: minmax(auto, auto);
    grid-template-areas:
      "hd hd ft"
      "sd . ft"
      "sd main ft"
      "sd . ft";
}
<!DOCTYPE html>

Header

Sidebar

Content

Footer

A: Here's what's happening:
First, let's see the gaps (they don't appear in many cases):

.wrapper {
  display: grid;
  grid-auto-rows: minmax(auto, auto);
  grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft";
}

.header {
  grid-area: hd;
}

.footer {
  grid-area: ft;
}

.content {
  grid-area: main;
}

.sidebar {
  grid-area: sd;
}

* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

Header

Sidebar

Content

Footer

What you're seeing is the rendering of   (non-breaking space) characters in the HTML code.

As white space characters, they're invisible, which makes them hard to detect. But once you remove them, the layout works as expected.

.wrapper {
  display: grid;
  grid-auto-rows: minmax(auto, auto);
  grid-template-areas: "hd hd ft" "sd . ft" "sd main ft" "sd . ft";
}

.header {
  grid-area: hd;
}

.footer {
  grid-area: ft;
}

.content {
  grid-area: main;
}

.sidebar {
  grid-area: sd;
}

* {
  box-sizing: border-box;
}

.wrapper {
  border: 2px solid #f76707;
  border-radius: 5px;
  background-color: #fff4e6;
  max-width: 940px;
  margin: 0 auto;
}

.wrapper > div {
  border: 2px solid #ffa94d;
  border-radius: 5px;
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}

Header

Sidebar

Content

Footer

Lastly, why doesn't the faulty layout display in many cases?
When you copy HTML code as rendered on a web page (e.g., copy the code directly from the question), the   characters, being HTML code, have already been rendered. So only plain (collapsible) white space gets copied and the layout will appear to be working fine.
Also, if you copy the HTML code from some code editors in some browsers (e.g., the Stack Snippet editor on Edge), the   characters don't get copied, either. I needed to copy the code from the jsFiddle editor in Chrome to finally see the problem.
Also, if you hit the "Tidy" button in the editor using the original code, spaces will be added between the lines.

A: The empty cells have to be inserted, you'll not get it by default, just adding the HTML and body tag fixed the bottom gap issue:

.header {
    grid-area: hd;
}
.footer {
    grid-area: ft;
}
.content {
    grid-area: main;
}
.sidebar {
    grid-area: sd;
}
.empty-cell1 {
    grid-area: ec1;
}
.empty-cell2 {
    grid-area: ec2;
}
* {box-sizing: border-box;}

.wrapper {
    border: 2px solid #f76707;
    border-radius: 5px;
    background-color: #fff4e6;
    max-width: 940px;
    margin: 0 auto;
}

.wrapper > div {
    border: 2px solid #ffa94d;
    border-radius: 5px;
    background-color: #ffd8a8;
    padding: 1em;
    color: #d9480f;
}
.wrapper {
    display: grid;
    grid-template-areas:
      "hd hd ft"
      "sd ec1 ft"
      "sd main ft"
      "sd ec2 ft";
}
<!DOCTYPE html>

Header

Sidebar

Content

Footer


Q: Is setting my webserver to https, also securize my ajax call? Imagine I have a small webpage I browse in https with a signed certificate that load data with an ajax call like this:
$.ajax(
    {
type:"POST",
url:"ressource/js/load_footer.php",
data:"page="+variable,
success:
    alert("poney");
    }
)

Can I assume that this ajax call is secure by https ? or does it communicate by http ?

A: As mentionned in the comment of my question:

Since it is a relative URL, it will use the protocol of the page it is executed in. But instead of asking, you could also have found this out easily yourself by just looking at the request in the net panel of your browser’s developer tools … –  CBroe 4 mins ago


Q: How to use mechanize to fill search form and get results back? i am trying to use mechanize with python to search for a keyword using a a search form.
this is the form code :
<form id="searchform" action="http://www.example.com/" method="get">
<input id="s" type="text" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}" name="s" value="Search">
<input type="image" style="border:0; vertical-align: top;" src="http://www.example.com/wp-content/themes/SimpleColor/images/search.gif">
</form>

i want to be able to submit and get the results back so i can extract the info from the results.
Thanks in advance.

A: From the official page, you create a browser object by br = mechanize.Browser() and follow a link with the object - br.open("http://www.example.com/"), and then you select a form by br.select_form(name="searchform") and you can pass an input by br["s"] = #something and submit it resp = br.submit() use the resp object like you wish.


Q: T5Tokenizer and T5EncoderModel are used to encode sentences then nn.TransformerDecoder to decode to a 2-label tensor. It gives error Used T5Tokenizer to tokenize a sentence then T5EncoderModel to encode. Finally, used the pytorch nn.TransformerDecoder to decode it. The target vector is a torch.tensor [y1, y2] where y1 and y2 have binary value. But it returns an error RuntimeError: DataLoader worker (pid(s) 723820) exited unexpectedly. The dataset class is given below.
tokenizer=T5TokenizerFast.from_pretrained('t5-base')
MAX_LEN = tokenizer(balanced_sentences[max_idx]).input_ids
class MyDataset(Dataset):
    def __init__(self, sentences, labels):
        self.labels = labels
        self.sentences = sentences
        self.tokenizer = tokenizer
    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        sentence = self.sentences[idx]
        label = self.labels[idx]
        tokenized = tokenizer(self.sentences[idx],
                             max_length=MAX_LEN,
                             padding='max_length',
                             truncation=True,
                             add_special_tokens=True,
                             return_tensors="pt")
        sample = {"input_id": tokenized['input_ids'].flatten(),
                  "attention_mask":tokenized['attention_mask'].flatten(),
                  "label": label}
        return sample

The model is created in the following way
class MyModel(pl.LightningModule):
    def __init__(self):
        super().__init__()
        self.encoder = T5EncoderModel.from_pretrained("t5-base", return_dict = True)
        dec_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8, batch_first=True)
        self.decoder = nn.TransformerDecoder(dec_layer, num_layers=6)
        self.loss_fc = nn.BCELoss()

    def forward(self, input_id, attention_mask, label=None):
        encoded_sentence = self.encoder(input_id, attention_mask)#.last_hidden_state.mean(dim=1)
        loss, output = self.decoder(label, encoded_sentence)
        return loss, output

    def training_step(self, batch, batch_idx):
        input_id = batch['input_id']
        attention_mask = batch['attention_mask']
        label = batch['label']
        loss, output = self(input_id = input_id,
                            attention_mask=attention_mask,
                             label = label)
        self.log('train_loss', loss, prog_bar = True, logger = True)
        return loss

    def validation_step(self, batch, batch_idx):
        input_id = batch['input_id']
        attention_mask = batch['attention_mask']
        label = batch['label']
        loss, output = self(input_id = input_id,
                            attention_mask=attention_mask,
                             label = label)
        self.log('train_loss', loss, prog_bar = True, logger = True)
        return loss

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=0.001)

trainer = pl.Trainer(logger = logger,
                     num_sanity_val_steps=0,
                     max_epochs = N_EPOCHS,
                     gpus = 1,
                     progress_bar_refresh_rate = 20)

trainer.fit(model, data_module)

A: If you're use VSCode it sounds like the data loader has multiple workers and it can't create more threads. Set the number of workers to 0.
See: VSCode bug with PyTorch DataLoader?


Q: What is the correct way to encapsulate factory methods from derived classes when implementing factory in base class? I am trying to create simple class with ability to register derived classes for creation from base class. However I cannot find a good way to encapsulate this functionality from descendants.
Class variables looks for me a bad idea because they available everywhere in inheritance chain. So I try do something with class instance variables. Perfectly it will be that all class methods will be inaccessible except register_as
class A
  @registered = {}
  class << self
    def register_as(name)
      A.registered[name] = self
    end

    def known
      A.registered
    end

    protected
    attr_accessor :registered
  end

  def helpful_method
  end

end

class B < A
  class << self
    def reg_trash
      A.registered[:trash] = :trash
    end
  end
  B.register_as :b
end

B.reg_trash
p A.known

However registered is still accessible from B class.
Currently looks like the only one possible option is to split A class to dedicated Factory class and A class will hold only helpful instance methods.
Maybe it is possible to do something via .inherited and .undef_method, isn't it?

A:
Maybe it is possible to do something via .inherited and .undef_method, isn't it?

Yes, it is possible. But the idea smells, as for me - you're going to break substitutability.
If you don't want the "derived" classes to inherit the behavior of the parent, why do you use inheritance at all? Try composition instead and mix in only the behavior you need. For example, something like this could work (very dirty example, but I hope you got the idea):
class A
  module Registry
    def register_as(name)
      A.register_as(name, self)
    end
  end

  @registered = {}

  def self.register_as(name, klass)
    @registered[name] = klass
  end

  def self.known
    @registered
  end
end

class B
  extend A::Registry
  register_as :b
end

class C
  extend A::Registry
  register_as :c
end

A.known # => {:b => B, :c => C}


Q: Clarity on Docker Container IP addresses for API requests I want to be able to connect to a third-party .NET API I am running as a docker image within a container. When I connect to the ip address and port on my browser it works though when I try and run a get request in python it does not. I am not sure what I am doing wrong.
The Django python application is an image within the container using 0.0.0.0:8000.
This is the docker-compose.yml file for a .NET image I am running from within a container:
mt4rest:
    image: mt4rest:latest
    ports:
      - "0.0.0.0:5000:80"

Here are the ports as per docker inspect
  "Ports": {
                "443/tcp": null,
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "5000"
                    }
                ]
            },

When I run
http://0.0.0.0:5000/Ping

or
http://127.0.0.1:5000/Ping

in my browser, I get OK though when I run the same endpoints in Python:
response = requests.get('http://0.0.0.0:5000/Ping')

or
response = requests.get('http://127.0.0.1:5000/Ping')

I receive the following error:
requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=5000):
Max retries exceeded with url: /Ping (Caused by
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe7aa5af640>:
Failed to establish a new connection: [Errno 111] Connection refused'))

or
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=5000):
Max retries exceeded with url: /Ping (Caused by
NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f6322e2b640>:
Failed to establish a new connection: [Errno 111] Connection refused'))

I understand this to mean that the address for the request is not found.
I am not sure what I am doing wrong.

A: Lets call your host as HOST_BASE.
You are having two containers, one is exposing 5000 on host. Its HOST_BASE:5000.
Other is your python-app container.
Now, you are running another python-app in container on host HOST_BASE. And try to hit: http://0.0.0.0:5000, which is not accessible. Note: its 0.0.0.0 is localhost of the container itself.
You want to connect to HOST_BASE:5000, which is not localhost or 0.0.0.0
You need to configure networking between your two containers. Or, for simplicity, use --network host while running both of your container.
Hope that helps.

A: There is an acceptable answer for this question on stackoverflow which solves the problem:
Python requests in Docker Compose containers