text:
Q: Split list of value into list of dictionary I have dictionary with key value like this :
[{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}]

I would like to get something like this:
[ {key1 : '1', key2 : 'john'}, {key1 : '2', key2 : 'marvel'}, {key1 : '150', key2 : 'gandalf'}, {key1 : '120', key2 : 'sam'}]

I am stuck, I think to embedded loops but I don't know how.

A: You could use a list comprehension:
data = [{"key1": ['1', '2'], "key2": ['john', 'marvel']}, {"key1": ['150', '120'], "key2": ['gandalf', 'sam']}]

keys = ['key1', 'key2']
result = [dict(zip(keys, items)) for d in data for items in zip(*(d[k] for k in keys))]

print(result)

Output
[{'key2': 'john', 'key1': '1'}, {'key2': 'marvel', 'key1': '2'}, {'key2': 'gandalf', 'key1': '150'}, {'key2': 'sam', 'key1': '120'}]

The above list comprehension is equivalent to the following for loop:
result = []
for d in data:
    for items in zip(*(d[k] for k in keys)):
        result.append(dict(zip(keys, items)))

A: If you literally always have just "key1" and "key2", then:
In [1]: data = [{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['
   ...: 150', '120'], "key2" : ['gandalf', 'sam']}]
   ...:

In [2]: [{"key1":v1, "key2":v2} for d in data for (v1, v2) in zip(d['key1'], d['key2'])]
Out[2]:
[{'key1': '1', 'key2': 'john'},
 {'key1': '2', 'key2': 'marvel'},
 {'key1': '150', 'key2': 'gandalf'},
 {'key1': '120', 'key2': 'sam'}]

would do
A more general approach would be something like:
In [5]: [dict(zip(d, vs)) for d in data for vs in zip(*d.values())]
Out[5]:
[{'key1': '1', 'key2': 'john'},
 {'key1': '2', 'key2': 'marvel'},
 {'key1': '150', 'key2': 'gandalf'},
 {'key1': '120', 'key2': 'sam'}]

A: result = [{}]
for item in data:
    key, val = item.split(":", 1)
    if key in result[-1]:
        result.append({})
    result[-1][key] = val

A: The most easiest way with 2 loops in list comprehension
no hardcoded lists and no new variables
lst = [{"key1" : ['1', '2'], "key2" : ['john', 'marvel']}, {"key1" : ['150', '120'], "key2" : ['gandalf', 'sam']}]

[dict(zip(el.keys(), v)) for el in lst for k,v in el.items()]

[{'key1': '1', 'key2': '2'},
 {'key1': 'john', 'key2': 'marvel'},
 {'key1': '150', 'key2': '120'},
 {'key1': 'gandalf', 'key2': 'sam'}]

A: list1 = [ {'key1' : '1', 'key2' : 'john'}, {'key1' : '2', 'key2' : 'marvel'}, {'key1' : '150', 'key2' : 'gandalf'}, {'key1' : '120', 'key2' : 'sam'}]
list2 = [{'key1':i['key1'][0], 'key2':i['key2'][0]} for i in list1] + [{'key1':i['key1'][1], 'key2':i['key2'][1]} for i in list1]
list2
[{'key1': '1', 'key2': 'john'},
 {'key1': '150', 'key2': 'gandalf'},
 {'key1': '2', 'key2': 'marvel'},
 {'key1': '120', 'key2': 'sam'}]


text:
Q: Unable to find a link while running Selenium Test case I am using Selenium webdriver. I can log in to the application, but while logging out it gets stuck, reason it cannot find logout link. I tried to find it byLink and byId. I have also tried using thread.sleep() but nothing seems to be working.
Logout link is present in all the pages.
HTML code:

#{loginView.loggedInUser}>

<h:link value="Administration" outcome="Administration.xhtml" />

<h:commandLink value="Logout" actionListener="#{loginView.logout}">
      <f:param id="userName" value="#{loginView.username}" />
    </h:commandLink>

SELENIUM code:
Thread.sleep(5000);

WebElement logOut = findElementByLinkText("Logout");

logOut.click();

assertEquals("Please sign in: ", findElementBySelector("h3.loginTitle.centerAlign").getText());

A: Use this code check how many links are present on page if it contains your logout link then you can click on it by using locator "linktext".
public void Link(){

        driver.get(baseUrl);
        HtmlTagFinder links = LinkFinder.links();
        List<WebElement> allLinks = (List<WebElement>) links.findFrom(driver);
        System.out.println(allLinks.size());
        int i = 1;
        for(WebElement link : allLinks){
            System.out.println(i);
            System.out.println(link.getText());
            i++;
        }

        driver.close();
        driver.quit();
    }

A: driver.findElement(By.xpath("@value='Logout'")).click();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to give newly opened tab in Internet Explorer as reference to the Document Variable in Excel VBA I want to fetch a detail from webpage using Excel Macro. When I click a button in the web page, It opens a new tab, there I will have the detail to be fetched. But my macro is clicking the button in the current web page but it is not going to next newly opened tab.
Option Explicit

Sub connectToClarity()

    Dim ie As New SHDocVw.InternetExplorer
    Dim webDoc As MSHTML.HTMLDocument
    Dim webElement As MSHTML.IHTMLElement
    Dim webElements As MSHTML.IHTMLElementCollection

    ie.Visible = True
    ie.Navigate "https://intranet.zzzzzzz.com.au/wbg/tools-and-resources/systems/clarity"

    Do Until ie.ReadyState = READYSTATE_COMPLETE

    Loop

    Set webDoc = ie.Document
    Set webElement = webDoc.getElementById("input-keyword")
    webElement.Value = "Clarity"

    Set webElements = webDoc.getElementsByTagName("a")

    For Each webElement In webElements
        If webElement.getAttribute("className") = "btn btn-primary hidden-xs" Then
            webElement.Click
            Exit For
        End If

    Next webElement

    Do Until ie.ReadyState = READYSTATE_COMPLETE

    Loop

    Set webDoc = ie.Document
    Set webElements = webDoc.getElementsByTagName("a")

    Debug.Print webElements.Length
    For Each webElement In webElements
    Debug.Print webElement.innerText

    If webElement.getAttribute("id") = "timeadmin.editTimesheet" Then
        webElement.Click
        Exit For
    End If

    Next webElement

End Sub


text:
Q: How to prevent nginx reverse proxy recompress the upstream compressed response? I have nginx reverse proxy that receives brotli compressed response from upstream (Varnish cache). But, the reverse proxy serves brotli compressed response to browser only if I setup "brotli on;" within the reverse proxy server block.
My goal is to have the nginx reverse proxy not handle compression at all. To achieve this, I have following questions:

*

*Is the reverse proxy block expected to un-compress the received response and handle it on it's own? Can't it directly pass the upstream response back to client?

*Is there a way to dump proxy response or it's size to nginx logs? This shall help debug the issue better.

A: I have resolved this so posting this for anyone who may encounter similar issue:

*

*Varnish changed my 'Accept-Encoding' request header to 'gzip'. According to Varnish documentation, this is as designed (see here).

*However, the upstream nginx server (behind varnish) responded with non-compressed content because the default for gzip_http_version is 1.0 while the default for proxy_http_version is 1.1. (see here)

Resolution was achieved by:
a. setting Varnish to not worry about compression by passing -p http_gzip_support=off to varnishd.
b. setting gzip_http_version to 1.1 on the upstream Nginx server.
Deciphering the above behavior became possible because I logged the following on my upstream nginx server (the one behind varnish):
log_format bytes_sent '$bytes_sent' - '$http_accept_encoding' - '$request';


text:
Q: Visual Basic - Selecting values from a string and defining them as something I have a log file in txt, inside are strings of information. one string looks like this:
49000 120614 12334480 12 32 2 90 90 90 321 384 2 345 873 890
each value between the spaces represents something in specific, (e.g the second line "120614" is the date "12 June 2014") I am writing a program where I load the txt file into it, and then when i click a certain button it will take this string and put all the values into a specific text box, for instance, "Date = 12 06 2014". I have been researching how to find a certain line and declare that line with its contents as something, but I have not found the answer!! I  am using Visual Basic to write it, and I really need help with what direction to take, will stramreader be able to do this?? What function am I looking for?
Here is my code for loading the file.. Just incase.
  Public Class Form1

  Private Sub browsebtn1_Click(sender As Object, e As EventArgs) Handles browsebtn1.Click
    Dim filedialog As New OpenFileDialog 'openfiledialog1 is now filedialog'
    filedialog.Filter = "Text Document|*.txt" 'filter the openfiledialogs file extension to txt only'
    filedialog.Title = "Select Bosvark Log File.." 'openfiledialog title'
    If filedialog.ShowDialog = Windows.Forms.DialogResult.OK Then 'if the file is chosen then..'
        filepath1.Text = filedialog.FileName 'filepath1 text is file path of selected file'
        RichTextBox1.LoadFile(filepath1.Text, RichTextBoxStreamType.PlainText) 'richtextbox1 retrieves the file path and displays the document'
    End If
    End Sub

    Private Sub convertbtn_Click(sender As Object, e As EventArgs) Handles convertbtn.Click
    If RichTextBox1.Text = "" Then
        MessageBox.Show("Please load a file first!") 'If user doesnt load a file, give them an error message.'
    End If
     End Sub

    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles     RichTextBox1.TextChanged
    If RichTextBox1.Text = "" Then
        RichTextBox1.Visible = False 'If there is no file loaded, The textbox will not appear.'
        Else
            RichTextBox1.Visible = True 'if the file is loaded, textbox will appear.'
        End If
    End Sub
End Class

A: you can load the contents of the file to a string variable (if the file isnt too large)
Dim intFile As Integer
Dim strFile As String
Dim strData As String
intFile = FreeFile
strFile = "c:\temp\file.txt"
Open strFile For Input As #intFile
  strData = Input(LOF(intFile), #intFile)
Close #intFile

you can split all the data into an array per line
Dim strLine() As String
strLine = Split(strData)

you can loop over all lines to perform some action on all lines
Dim lngLine As Long
For lngLine = 0 To UBound(strLine)
  'do action
Next lngLine

or just perform an action on one specific line:
dim strField() as String
'split line into array separated per spaces
strField = Split(strLine(lngLine), " ")


text:
Q: I'm combining fields in an access query and I need the last number to show a certain number of digits Current code is:
[Plant] & "" & [CurrentYear] & "" & [CurrentMonth] & "" & [ID]

This gives me LO14A2, where [Plant]=LO, [CurrentYear]=14, [CurrentMonth]=A, [ID]=2 but [ID] is supposed to be 00002. What should I have the format as?

A: Try
Right("00000" & [ID],5)

So:
[Plant] & [CurrentYear] & [CurrentMonth] & Right("00000" & [ID],5)


text:
Q: Why does modsecurity require Content-Length in POST requests? I have a RESTful web service that accepts a POST request to a resource without an entity body, e.g. an empty POST request. The default modsecurity configuration requires that all POST requests have a Content-Length:
# Require Content-Length to be provided with every POST request
SecFilterSelective REQUEST_METHOD "^POST$" chain
SecFilterSelective HTTP_Content-Length "^$"

The modsecurity console reports this as a PROTOCOL_VIOLATION/EVASION. However I don't see this as true in my reading of the HTTP/1.1 RFC. A server is allowed to require Content-Length (returning either 400 or 411), but I see nothing that says a server must (or a recommendation that it should) behave in this way.
This possibly varies by browser, but Flash clients making POST requests without entity bodies don't send a request header. Neither does curl when you do 'curl -XPOST ...'. For these reasons, and because I believe the modsecurity rule to be a misinterpretation of the HTTP spec, I'm considering lifting the requirement for a Content-Length header on POST requests in our config.
Does anyone know if there was a specific exploit this rule was created to address? Numerous google searches and I've only found references to this being part of the stock modsecurity configuration.

A: First of all, you should know that you are running an obsolete version of ModSecurity (branch 1.x). If you are running Apache 2.0.x you should upgrade to ModSecurity 2.x. If you are still running Apache 1.3.x then I am afraid that you don't have a choice since ModSecurity 2.x won't work with it. ModSecurity 1.x itself is not known to be vulnerable, but its rule engine is too inflexible for today's demands.
If I recall correctly, ModSecurity 1.x required POST requests to specify content length purely because it didn't support chunked request bodies (the alternative way of submitting request bodies, in which the total length is not known until the end). Chunked request bodies were incredibly rare then (we're talking years 2003, 2004) and are still rare (although some mobile devices are using them).
There are no such restrictions in ModSecurity 2.x.
If you remove that rule you will create a big hole through which someone could sneak in an attack undetected. On the other hand, I can argue that, with you running ModSecurity 1.x, there are other ways to do the same. Alternatively, tweak the rule to refuse requests that have the Transfer-Encoding request header set. You should be safe with that.
Disclosure: I wrote ModSecurity.

A: I believe that requirement is part of the xml-rpc spec, rather than the http spec.  If you're not after xml-rpc, I would think it would be an OK thing to omit.
I don't know much about the reasons for its general inclusion in mod_security, unless it was originally there to prevent some kind of esoteric buffer overflow.


text:
Q: How to get variables object out of bracket, or is there any way to globally declare variables var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);
oModel.read('/', null, null, true, function(oData, oResponse)
{
        var dataget = JSON.stringify(oData);
        var count = oData.results[0].Ort01;
        var Name1 = oData.results[0].Name1;
        var Kunnr = oData.results[0].Kunnr;
        alert(count + "  " +Name1 + "  " +Kunnr);
});

here as you see I can get the variables inside parenthesis({ }); How to get the same variable objects outside the parenthesis something like this..
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);
    oModel.read('/', null, null, true, function(oData, oResponse)
    {
    });
var dataget = JSON.stringify(oData);
var count = oData.results[0].Ort01;
var Name1 = oData.results[0].Name1;
var Kunnr = oData.results[0].Kunnr;
alert(count + "  " +Name1 + "  " +Kunnr);

Can someone help me. Thank You

A: I'm not sure what you are trying to accomplish but the function you have declared seems to be callback function. It means that it will be executed asynchronously and therefore you cannot simply add that code just after the oModel.read line.
You, however, can declare those variable before the method call and use them in the callback method but you must realize that you cannot know when the callback function will be executed and therefore you cannot be sure when those variables will have any data.
var count;
var Name1;
var Kunnr;
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);
oModel.read('/', null, null, true, function(oData, oResponse)
{
    var dataget = JSON.stringify(oData);
    count = oData.results[0].Ort01;
    Name1 = oData.results[0].Name1;
    Kunnr = oData.results[0].Kunnr;
    alert(count + "  " +Name1 + "  " +Kunnr);
});

// Here you can reference to count those variables but you need to make sure
// that callback function is executed already

Above example shows how you can do it but it is not good way to do it anyway. I think you should revise the whole execution flow because of the asynchronous execution. I mean that you should understand that the execution flow will continue inside the callback function not outside of it:
var variableDefinedBeforeCallback = .....;
...
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);
oModel.read('/', null, null, true, function(oData, oResponse)
{
    var dataget = JSON.stringify(oData);
    var count = oData.results[0].Ort01;
    var Name1 = oData.results[0].Name1;
    var Kunnr = oData.results[0].Kunnr;
    alert(count + "  " +Name1 + "  " +Kunnr);

    // If you want to do something with those variables you can call any function
    // here and pass variables defined also before this callback
    anyFunction(variableDefinedBeforeCallback, count, Name1, Kunnr, ...);
});

A: var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);

var successCallBack = function(oData,oResponse) {
     var dataget = JSON.stringify(oData);
     var count = oData.results[0].Ort01;
     var Name1 = oData.results[0].Name1;
     var Kunnr = oData.results[0].Kunnr;
     alert(count + "  " +Name1 + "  " +Kunnr);
};

oModel.read('/', null, null, true, successCallBack);

A: Just switch your mParameters.async in the read method from true to false. That will change asynchronous request to synchronous and it will work.


text:
Q: Zip/repeat join? Let's say I have a simple table of documents with a type column:
Documents
Id  Type
1   A
2   A
3   B
4   C
5   C
6   A
7   A
8   A
9   B
10  C

Users have permissions to access different types of documents:
Permissions
Type    User
A       John
A       Jane
B       Sarah
C       Peter
C       John
C       Mark

And I need to distribute those documents among the users as tasks:
Tasks
Id  T DocId UserId
1   A   1   John
2   A   2   Jane
3   B   3   Sarah
4   C   4   Peter
5   C   5   John
6   A   6   John
7   A   7   Jane
8   A   8   John
9   B   9   Sarah
10  C   10  Mark

How do I do that? How do I get the Tasks?

A: You can enumerate the rows and then use modulo arithmetic for the matching:
with d as (
      select d.*,
             row_number() over (partition by type order by newid()) as seqnum,
             count(*) over (partition by type) as cnt
      from documents d
     ),
      u as (
       select u.*,
              row_number() over (partition by type order by newid()) as seqnum,
              count(*) over (partition by type) as cnt
       from users u
      )
select d.*
from d join
     u
     on d.type = u.type and
        u.seqnum = (d.seqnum % u.cnt) + 1

A: Great question.

*

*This solution returns all possible distributions, ordered by priority which is determined by information such as number of user involved, minimum documents per user, standard deviation of tasks per user etc.

*I'm not counting on document.id to be a sequence of numbers starting with 1, therfore the use of dense_rank.

*The core of the solutions is the iterative CTE which generates the record sets of all possible distributions.

*Execution time on my laptop is around 20 seconds, (the iterative part takes 5 seconds)

with        doc_user    as
            (
                select          d."id"                                          as docid
                               ,p."user"                                        as userid
                               ,dense_rank  ()  over (order by      d."id")     as doc_seq

                from                documents       d

                        left join   permissions     p

                        on          p.type = d.type
            )

           ,it_cte  as
            (
                select      docid
                           ,userid
                           ,doc_seq
                           ,cast (coalesce(userid,'') as varchar(max))  as path
                           ,'A'                                         as cte_part

                from        doc_user

                where       doc_seq = 1

                union all

                select      r.docid
                           ,r.userid
                           ,du.doc_seq
                           ,r.path + ',' + coalesce (du.userid,'')
                           ,'B'

                from                    it_cte      as r

                            cross join  doc_user    as du

                where       du.doc_seq = r.doc_seq + 1

                union all

                select      du.docid
                           ,du.userid
                           ,du.doc_seq
                           ,r.path + ',' + coalesce (du.userid,'')
                           ,'C'

                from                    it_cte      as r

                            cross join  doc_user    as du

                where       du.doc_seq = r.doc_seq + 1
                        and r.cte_part in ('A','C')
            )

           ,result_sets as
            (
                select      dense_rank  () over (order by path) as set_id
                           ,docid
                           ,userid

                from        it_cte

                where       doc_seq = (select count(*) from documents)
            )

           ,result_sets_stat as
            (
                select      set_id
                           ,count   (distinct userid)   as users_involved

                from        result_sets

                group by    set_id
            )

           ,result_sets_users_stat as
            (
                select      set_id
                           ,min     (doc)   min_doc_per_user
                           ,stdevp  (doc)   stdevp_doc_per_user

                from       (select      set_id
                                       ,userid
                                       ,count   (*) as doc

                            from        result_sets

                            group by    set_id
                                       ,userid
                            ) t

                group by    set_id
            )

select      s.set_priority
           ,r.docid
           ,r.userid
           ,s.users_involved
           ,s.min_doc_per_user
           ,s.stdevp_doc_per_user

from                    (select     s.set_id
                                   ,s.users_involved
                                   ,u.min_doc_per_user
                                   ,u.stdevp_doc_per_user

                                   ,row_number () over
                                    (
                                        order by    s.users_involved        desc
                                                   ,u.min_doc_per_user      desc
                                                   ,u.stdevp_doc_per_user
                                                   ,s.set_id

                                    )   as set_priority

                        from                    result_sets_stat        as s

                                    join        result_sets_users_stat  as u

                                    on          u.set_id    =
                                                s.set_id
                        ) s

            join        result_sets as r

            on          r.set_id    =
                        s.set_id

order by    s.set_priority
           ,r.docid

option      (merge join)
;


text:
Q: Deploying express node.js project to azure 500 server error Seem to have tried every available solution even though some claim that Azure have fixed this issue internally, but I cannot get it to work, production deployment gives me a 500 error every time. Deploying locally works. Here's my app.js which is basically "out of the box" with express 4.12.2
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.set('port', process.env.PORT || 1337);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

app.listen(app.get('port'), function(){
           console.log('Express server listening on port ' + app.get('port'));
           });

A: I suspect you might be getting this error in the logs.
Error: ENOENT, open 'D:\home\site\wwwroot\bin\views\layouts\main.handlebars'
    at Error (native)
Enable the error logs
Note the path to the views folder.
You could try remove the www file. Check the last couple of paragraphs in the Express docs on how.
Also I found that adding app.use(express.static('public')); is needed if you have resources like images and fonts – it would fail silently otherwise.

A: Make sure that your entry point is in the root folder.
In my case, my entry point was './bin/www', I had to manually move this file to root and update the  and  sections in the Web.config to get it working.
Deploy again after making these changes.

A: there were a couple solutions provided in the following question
Azure NodeJS Error: ENOENT, open 'D:\home\site\wwwroot\bin\views\'
for now I simply used the following near the top of app.js
process.chdir(__dirname);

A: I know it is very tricky to handle such scenarios.

*

*Try to understand/google what versions of nodejs azure portal supports. It supports only specific versions. Note those versions and try to use any version you need or try using latest version only from that list.

*In azure portal -> go to your app service -> you should see console in appservice details -> Type node -v.

*This should give you node version may be like 0.10.4 or so. This may be the main main and main culprit.

*Go to your app settings under configuration for your app service. Add node version there like WEBSITE_NODE_DEFAULT_VERSION as your node version ex: 8.9.4

*Go to your package.json and add node version same as you used in azure portal  appsettings. ex:  "engines": {
"node": "8.9.4"
}

*Restart app service -> check console -> node -v.
if this shows same version then deploy application and it should work with out any issues.

How to check real errors instead of 500

*

*In azure portal for your app service enable diagnostic logs

*Select log stream

*Refresh your site. Now you should see real error message in log stream.

Good luck.


text:
Q: Getting command line options I want to parse the command line options having specific format for getting the values. The function is as follows
char* getCmdOption(char** begin,
                    char** end,
                    const std::string& option)
{
   char** itr = std::find(begin, end, option);

  if (itr != end && ++itr != end)
  {
        return *itr;
  }
  return (char*)"";
}

The arguments passed are getCmdOption(argv, argv+argc, "--optionName")
The code works fine for all the options and gives proper output but if I want to give values such as Application.exe --optionName surname="O Kief" the code should return me surname="O Kief" but instead it returns "surname=O Keif"
The format for input is Application.exe --optionName optionValue and expected output is "optionValue"
What is possibly wrong with the logic ? And how can i handle the case I have mentioned ?

A: ""is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument. Sadly, however, not only are the enclosing double-quotes retained (as usual) but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument.
Application.exe --optionName option="name" removes the enclosing double-quotes then converts the doubled double-quotes to single ones.
Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.
Although a precise solution is given below but you can visit this for in-depth solution of the problem (Not exactly a problem)
If the optionValue does not contain white spaces keep the format as
Application.exe --optionName "optionValue"

If the option Value contains white space wrap the thing in quote as
 Application.exe --optionName '"option Value"'


text:
Q: auto-deleting element in doubly link list After certain number of steps, the loaded (particular)element should be get (auto) deleted by itself on execution/run time..I want to pre define it so it can perform auto-deletion in doubly linked list
void del_begin()
{
  struct node *temp;

 if(start==NULL)
      return;
    else
    { temp=start;
        start=start->next;
                start->prev=NULL;
        printf("Unloaded Wagon =%s ",temp->num);
        free(temp);
    }

A: The following code implements a doubly linked list where each element can be assigned a lifetime value. Each call to insert will decrease the lifetime by 1. If a node has a lifetime of 0 it is being removed from the list. Nodes with a negative lifetime value are ignored and hence never removed from the list.
#include <stdio.h>
#include <stdlib.h>

struct dll{
    struct node* head;
};

struct node {
    struct node* next;
    struct node* prev;
    int value;
    int lifetime;

};

void insert(struct dll*, int, int); // insert a new node
void step(struct dll*); // decrease the lifetime by one and remove "dead" nodes
void print(struct dll*); // print the nodes and their lifetime

int main(void) {
    struct dll* dll = malloc(sizeof(struct dll));
    dll->head = NULL;
    insert(dll, 1, -1);
    insert(dll, 2, 5);
    insert(dll, 3, 3);
    insert(dll, 4, 0);
    insert(dll, 5, 1);
    print(dll);
}

void insert(struct dll* dll, int value, int lifetime) {
    print(dll);
    step(dll);
    struct node* n = malloc(sizeof(struct node));
    n->value = value;
    n->lifetime = lifetime;
    if(dll->head == NULL) {
        dll->head = n;
        n->prev = dll->head;
        n->next = dll->head;
    } else {
        n->prev = dll->head->prev;
        dll->head->prev->next = n;
        dll->head->prev = n;
        n->next = dll->head;
    }
}

void step(struct dll* dll) {
    if(dll->head != NULL) {
        struct node* n = dll->head;
        do{
            if(n->lifetime == 0) {
                // remove the node
                struct node* next = n->next;
                n->prev->next = n->next;
                n->next->prev = n->prev;
                free(n);
                n = next;
            } else if(n->lifetime > 0){
                // decrease lifetime by one
                n->lifetime = n->lifetime - 1;
                n = n->next;
            } else {
                n = n->next;
            }
        } while(n != dll->head);
    }
}

void print(struct dll* dll) {
    if(dll->head != NULL) {
        struct node* n = dll->head;
        do{
            printf("%d(%d) ", n->value, n->lifetime);
            n = n->next;
        } while(n != dll->head);
    }
    printf("\n");
}

The following is being printed out upon executing the code:
1(-1)
1(-1) 2(5)
1(-1) 2(4) 3(3)
1(-1) 2(3) 3(2) 4(0)
1(-1) 2(2) 3(1) 5(1)


text:
Q: My code's not working I'm beginning javascript and i do some exercise to train my self, but i've a
problem.
My code had to ask the time to the user and give the time one seconde after
the time entered.
And my code shows my always "temps erroné" (that mean ~wrong time).
Here's my code :

That ask to user the time

var hour = Number(prompt("heure actuelle?"));
var minute = Number(prompt("minute actuelle?"));
var seconde = Number(prompt("seconde actuelle?"));

//this function is like a control, if the time entered is wrong the function
  is false

 function isTimeValid(hour, minute, seconde){
  if((hour >= 24) || (hour < 0)) {
  return false
  }
  if((minute < 0) || (minute >= 60)) {
   return false
  }
  if((seconde >= 60) || (seconde < 0)) {
  return false

  }
  else {
    return true
  }
}

This function modify the time

function displayNextHour(hour, minute, seconde){
if((seconde >= 0) && (seconde < 59)) {
  seconde++;
} else if(seconde === 59) {
  seconde = 0
  minute++
  }
if(minute === 60) {
  minute = 0
  hour++
  }
if(hour === 24) {
  hour = 0
  }
 var time = "Il est " + hour + "h " + minute + "m " + seconde + "s";
 return time
}

The last part lunch function

if(isTimeValid()){
 console.log(displayNextHour(hour, minute, seconde))
}else{
  console.log("temps erroné")
}

So if you can help me that will be very helpful for me in my javascript learning :D

A: You didn't pass arguments to the function
Replace
if(isTimeValid())

with
if(isTimeValid(hour, minute, seconde))

A: You didn't pass arguments like Mike said and there is another mistake in your code.
You control the hours (=24) and minutes (=60) in "isTimeValid" but the next
function has errors in control this parameters. The code below fix it.
function displayNextHour(hour, minute, seconde){
 if((seconde >= 0) && (seconde < 59)) {
  seconde++;
} else if(seconde === 59) {
  seconde = 0
  minute++
  }
if(minute === 59) {
  minute = 0
  hour++
  }
if(hour === 23) {
  hour = 0
  }
 var time = "Il est " + hour + "h " + minute + "m " + seconde + "s";
 return time
}


text:
Q: Structuring a MEAN app so Express can find all the Jade files I am building out a MEAN app right now that is getting big. I really need to start modularizing the app but right now my Express server is configured to look for Jade views in one folder
app.set('views', path.join(__dirname, '/app/views'));
app.set('view engine', 'jade');

The authors of these posts show the view files scattered about the app in the different module directories.

*

*https://blog.safaribooksonline.com/2014/03/27/13-step-guide-angularjs-modularization/

*http://www.johnpapa.net/angular-app-structuring-guidelines/
If I try to do this now, my Express server will not be able to see them. How can I make it so Express will be able to find all the Jade views?

A: Two solutions :

*

*You can use a base folder named views and create subfolders inside views.
For example, views/menu/, views/header/. To use this, you have to
declare a basedir in Express so Jade will know where to look your
views, by doing app.locals.basedir = __dirname + "/views";. Then,
in your Jade file, use include /header/a.jade, include
/menu/item1.jade etc...

*Use Express App submounting feature. This allows you to modularize
your main app into small apps, which all have their own routes, views
etc... You can watch this nice video tutorial by TJ
Holowaychuk to learn more about this.

Does that help you ?

A: I just start using module prefixes in my render calls and set my views base directory to be the parent directory of my modules. So if I started with:
app/views/page1.jade
app/views/page2.jade

and was doing res.render("page1"), I reorganize to:
app/module1/page1.jade
app/module2/page2.jade

and I do app.set("views", "app") then render with res.render("module1/page1").


text:
Q: can we use two sockets for different different HTTP requests can we use two sockets for different different HTTP requests in tcp?
for example one socket I want to use for requesting the files from the server and the other one for fetching and downloading the file.
is it possible !
how many sockets we can use in one tcp connection!

A:
how many sockets we can use in one tcp connection!

One. That's how sockets work.

can we use two sockets for different different HTTP requests in tcp? for example one socket I want to use for requesting the files from the server and the other one for fetching and downloading the file. is it possible !

Yes, it is actually pretty common to have multiple sockets in HTTP/1 to request different resources from the same server in parallel. But these will be different TCP connections to the same server.


text:
Q: Recursively building up cons lists I'm writing a program that uses classical cons pairs a la Common Lisp, Scheme, et al.
(deftype Cons [car cdr]
  clojure.lang.ISeq
    (first [c] (.car c))
    (more [c] (.cdr c))

I create lists by chaining cons cells, e.g. (Cons. a (Cons. b nil)) for the list containing a and b. I wrote a function to convert a Clojure collection into a cons list:
(defn conslist [xs]
  (if (empty? xs)
      nil
      (Cons. (first xs) (conslist (rest xs)))))

This works but will overflow if xs is too big. recur doesn't work because the recursive call isn't in a tail position. Using loop with an accumulator wouldn't work, because cons only puts stuff at the front, when each recurse gives you the next item, and I can't use conj.
What can I do?
Edit: In the end, it turns out if you get this working, Clojure fundamentally isn't designed to support cons pairs (you can't set the tail to a non-seq). I ended up just creating a custom data structure and car/cdr functions.

A: as usual, i would propose the simplest loop/recur:
(defn conslist [xs]
  (loop [xs (reverse xs) res nil]
    (if (empty? xs)
      res
      (recur (rest xs) (Cons. (first xs) res)))))

A: lazy-seq is your friend here. It takes a body that evaluates to an ISeq, but the body will not be evaluated until the result of lazy-seq is invoked.
(defn conslist [xs]
  (if (empty? xs)
      nil
      (lazy-seq (Cons. (first xs) (conslist (rest xs))))))


text:
Q: Symlinks on /dev/ttyUSB* via udev So I built a nice little GSM-Gateway with a PC-Engines ALIX.2D13, a Huawei E220 umts modem, Debian Wheezy and gammu-smsd.
I need a fixed device name für gammu-smsd to survive reboots. I tried to make following udev rules, but i can't find out why it doesn't work.
SUBSYSTEM=="tty", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003", ATTRS{bInterfaceNumber}=="00", SYMLINK+="gsm0"
SUBSYSTEM=="tty", ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003", ATTRS{bInterfaceNumber}=="01", SYMLINK+="gsm1"

My udevadm output is the following:
root@ko-smsgw-01:~# udevadm info -a -n /dev/ttyUSB0

Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.

  looking at device '/devices/pci0000:00/0000:00:0f.4/usb2/2-1/2-1:1.0/ttyUSB0/tty/ttyUSB0':
    KERNEL=="ttyUSB0"
    SUBSYSTEM=="tty"
    DRIVER==""

  looking at parent device '/devices/pci0000:00/0000:00:0f.4/usb2/2-1/2-1:1.0/ttyUSB0':
    KERNELS=="ttyUSB0"
    SUBSYSTEMS=="usb-serial"
    DRIVERS=="option1"
    ATTRS{port_number}=="0"

  looking at parent device '/devices/pci0000:00/0000:00:0f.4/usb2/2-1/2-1:1.0':
    KERNELS=="2-1:1.0"
    SUBSYSTEMS=="usb"
    DRIVERS=="option"
    ATTRS{bInterfaceNumber}=="00"
    ATTRS{bAlternateSetting}==" 0"
    ATTRS{bNumEndpoints}=="03"
    ATTRS{bInterfaceClass}=="ff"
    ATTRS{bInterfaceSubClass}=="ff"
    ATTRS{bInterfaceProtocol}=="ff"
    ATTRS{supports_autosuspend}=="1"
    ATTRS{interface}=="Data Interface"

  looking at parent device '/devices/pci0000:00/0000:00:0f.4/usb2/2-1':
    KERNELS=="2-1"
    SUBSYSTEMS=="usb"
    DRIVERS=="usb"
    ATTRS{configuration}==""
    ATTRS{bNumInterfaces}==" 3"
    ATTRS{bConfigurationValue}=="1"
    ATTRS{bmAttributes}=="a0"
    ATTRS{bMaxPower}=="500mA"
    ATTRS{urbnum}=="1126"
    ATTRS{idVendor}=="12d1"
    ATTRS{idProduct}=="1003"
    ATTRS{bcdDevice}=="0000"
    ATTRS{bDeviceClass}=="00"
    ATTRS{bDeviceSubClass}=="00"
    ATTRS{bDeviceProtocol}=="00"
    ATTRS{bNumConfigurations}=="1"
    ATTRS{bMaxPacketSize0}=="64"
    ATTRS{speed}=="12"
    ATTRS{busnum}=="2"
    ATTRS{devnum}=="7"
    ATTRS{devpath}=="1"
    ATTRS{version}==" 1.10"
    ATTRS{maxchild}=="0"
    ATTRS{quirks}=="0x0"
    ATTRS{avoid_reset_quirk}=="0"
    ATTRS{authorized}=="1"
    ATTRS{manufacturer}=="HUAWEI Technologies"
    ATTRS{product}=="HUAWEI Mobile"

  looking at parent device '/devices/pci0000:00/0000:00:0f.4/usb2':
    KERNELS=="usb2"
    SUBSYSTEMS=="usb"
    DRIVERS=="usb"
    ATTRS{configuration}==""
    ATTRS{bNumInterfaces}==" 1"
    ATTRS{bConfigurationValue}=="1"
    ATTRS{bmAttributes}=="e0"
    ATTRS{bMaxPower}=="  0mA"
    ATTRS{urbnum}=="180"
    ATTRS{idVendor}=="1d6b"
    ATTRS{idProduct}=="0001"
    ATTRS{bcdDevice}=="0302"
    ATTRS{bDeviceClass}=="09"
    ATTRS{bDeviceSubClass}=="00"
    ATTRS{bDeviceProtocol}=="00"
    ATTRS{bNumConfigurations}=="1"
    ATTRS{bMaxPacketSize0}=="64"
    ATTRS{speed}=="12"
    ATTRS{busnum}=="2"
    ATTRS{devnum}=="1"
    ATTRS{devpath}=="0"
    ATTRS{version}==" 1.10"
    ATTRS{maxchild}=="4"
    ATTRS{quirks}=="0x0"
    ATTRS{avoid_reset_quirk}=="0"
    ATTRS{authorized}=="1"
    ATTRS{manufacturer}=="Linux 3.2.0-4-486 ohci_hcd"
    ATTRS{product}=="OHCI Host Controller"
    ATTRS{serial}=="0000:00:0f.4"
    ATTRS{authorized_default}=="1"

  looking at parent device '/devices/pci0000:00/0000:00:0f.4':
    KERNELS=="0000:00:0f.4"
    SUBSYSTEMS=="pci"
    DRIVERS=="ohci_hcd"
    ATTRS{vendor}=="0x1022"
    ATTRS{device}=="0x2094"
    ATTRS{subsystem_vendor}=="0x1022"
    ATTRS{subsystem_device}=="0x2094"
    ATTRS{class}=="0x0c0310"
    ATTRS{irq}=="12"
    ATTRS{local_cpus}=="1"
    ATTRS{local_cpulist}=="0"
    ATTRS{dma_mask_bits}=="32"
    ATTRS{consistent_dma_mask_bits}=="32"
    ATTRS{enable}=="1"
    ATTRS{broken_parity_status}=="0"
    ATTRS{msi_bus}==""

  looking at parent device '/devices/pci0000:00':
    KERNELS=="pci0000:00"
    SUBSYSTEMS==""
    DRIVERS==""

A: Check this out, http://reactivated.net/writing_udev_rules.html#udevinfo

while it is legal to combine the attributes from the device in question and a single parent device, you cannot mix-and-match attributes from multiple parent devices - your rule will not work

Based from your example, you're referencing 2 parent devices in each rule which is wrong.

*

*ATTRS{bInterfaceNumber}=="00"

*ATTRS{idVendor}=="12d1", ATTRS{idProduct}=="1003"


text:
Q: How to pass the exception in the loop? I'm crawling some financial statement from 'naver'. In my code list(kospi_list),
an incorrect code exists. So, I made an exception to avoid it. However it doesn't work well.
Once the program notice the incorrect code, it process the program as an exception until the end. I just want to continue the loop.
Could you help me?
Thanks in advance.
def connect(self):
    for code in self.kospi_list:
        url = "https://companyinfo.stock.naver.com/v1/company/c1010001.aspx?cmp_cd=%s&cn=" % code

        try:
            self.driver.get(url)
            html = self.driver.page_source
            self.soup = BeautifulSoup(html, 'html.parser')

        except:
            pass
        else:
            name = self.get_name()
            result = self.loop()
            if result is not None:
                self.save_sql(result, name)

            print(result)

    self.driver.close()


text:
Q: Java swing Header & Footer background color Is there any way to set Header and Footer in Java Swing?
Actually I am using theme in my application and I have set fixed background color for all panels. But now the work is to set different background color of Header and Footer panel. Can you give me any suggestion?
Thanks in advance..

A: Header and Footer are probably just JPanels, so you can do setBackground(Color.YELLOW) or such. As you probably have several header and footes (seeing those tabs), you could make a single class:
public class HeaderOrFooter extends JPanel {
    private static final Color bg = new Color(0xFFFF66);
    public HeaderOrFooter() {
       setBackground(bg);
    }
}

You can even use a http://docs.oracle.com/javase/6/docs/api/java/awt/SystemColor.html (for theming), like SystemColor.info.


text:
Q: How to get the text value out of a radio button list So I have two group boxes, what I am wanting is to get the selected radio button value from both of them.
If it was just a text box you can go:
thisValue = textbox1.text

But I have no idea how to do it for a radio button

A: To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:
bool isChecked = radioButton1.Checked;

There is no code-based relation between the radio buttons in a GroupBox (other than the radio buttons behaving in a manner so that only one of the radio buttons within the same container is checked at a time); your code will need to keep track of which one that is checked.
The simplest way to do this is perhaps to make the radio buttons within a group box all trigger the same event listener for the CheckedChanged event. In the event you can examine the sender argument to keep track of which one that is currently selected.
Example:
private enum SearchMode
{
    TitleOnly,
    TitleAndBody,
    SomeOtherWay
}
private SearchMode _selectedSearchMode;
private void SearchModeRadioButtons_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    if (rb.Checked)
    {
        if (rb == _radioButtonTitleOnly)
        {
            _selectedSearchMode = SearchMode.TitleOnly;
        }
        else if (rb == _radioButtonTitleAndBody)
        {
            _selectedSearchMode = SearchMode.TitleAndBody;
        }
        else
        {
            // and so on
        }
    }
}

A: this is WindowsForms Linq example
if it doesn't work exactly you'd get the idea
RadioButton rb = null;
RadioButton checkedRB = groupBox1.Controls.FirstOrDefault(
c => (rb = c as RadioButton) != null && rb.Checked) as RadioButton;

if (checkedRB != null)

{
this.Text = checkedRB.Text;
}

A: Reference to same click event trigger
private void rb_Click(object sender, EventArgs e) {
    thisValue = ((RadioButton)sender).Text;
}


text:
Q: How to fix extension problem in Pillow after resizing image? another newcomer here.
Just started learning python, this is my first task I gave to myself.
Image resize with keeping aspect ratio.
Can't figure out how to keep extension when saving new file and how to add '_resized' to name.
This is what I fugured out so far:
'''
  from PIL import Image
  import numpy as np
  import os

  img = Image.open("unsplash_3.jpg")
  img_name = (img.filename).split('.')[0]

  w = img.size[0]
  h = img.size[1]

  aspect = w/h

  #horizontal image
  if aspect > 1:
     new_w = 1000
     new_h = np.round(new_w / aspect).astype(int)

  #vertical image
  elif aspect < 1:
      new_h = 1000
      new_w = np.round(new_h*aspect).astype(int)

  img = img.resize((new_w, new_h), Image.Resampling.LANCZOS)

  img.save(img_name, 'jpeg', )

  print (img_name)
'''

Using latest Python 3 and Pillow library.
Big thnx


text:
Q: Rails 2 ":defaults" js conflict w/ jQuery When I use a javascript_include_tag for both jQuery and Rails' :defaults, the latter one seems to override the first.
For instance, when I put elements in this order:
<%= javascript_include_tag "jquery-1.4.min.js" %>
<%= javascript_include_tag :defaults %>

...I can execute an AJAX update with Rails but can do nothing with jQuery.
When I reverse the order of the javascript_include_tags, I can access jQuery but cannot run an AJAX request with Rails.
I prefer to do my AJAX Rails (as it entails less code on my part), but I wish also to make use of other jQuery features.  Any idea what to do or where the conflict lies?
Rails 2.3.5,
jQuery 1.4

A: There are two easy solutions here. Use the jrails plugin. It will walk you through what you need to do.
Or use jQuery instead of $ in your jQuery code.
For example:
$('li').fadeOut();
// should be
jQuery('li').fadeOut();

They will do the same thing but Rails uses Prototype which also maps the $ and therefore conflicts with jQuery.

A: You can try this and use $j instead of $ for jQuery.
<script>
   var $j = jQuery.noConflict();
</script>

A: Remember to add defaults first and then jquery. The conflict is between prototype.js file and jquery-1.4.2.min file
<%= javascript_include_tag  :defaults %>
<%= javascript_include_tag 'jquery-1.4.2.min' %>
<script>var $j = jQuery.noConflict();</script>

use $j instead of $ like.
$j(document).ready(function() {
.............
});


text:
Q: PHP - Unable to use data from database & Internal server error I'm trying to create a website (similar to pastebin) that allows a user to submit text on the homepage, which then takes them to a randomly generated url (domain.com/ABCXYZ) that is running run.php, which will then display the original content they submitted.
Once a user submits the form their input userentry is added to the database (column userinput). The randomly generated url code idgen (so a random code like KmdpV) is added to the randomurl column in the database.
This much is working without issue (successfully takes users to a randomly generated URL and the adds the userentry and idgen to the database.
However, two issues are popping up that I can't seem to solve:-

*

*I keep getting a 500 internal server error (seems to be caused by something within the else if (isset...) statement in the run.php code below. The error it keeps giving is GET http://example.com/WsnNp 500 (Internal Server Error) (where WsnNp is any randomly generate code) Failed to load resource: the server responded with a status of 500 (Internal Server Error).

*For some reason, I can't seem to access the userentry data at all. Once the form is submitted, it is succesfully added to the database and succesfully takes me to a random url running run.php, but it won't display anything if I write <?php echo $_GET['userentry'] ?> (nor using POST, nor using SELECT ... FROM database etc.).

Being able to access the userentry on the randomly generated page is key for the entire site. The userinput needs to be permenantly available on that randomly generated URL, so for example, if I have the database row:
ID | userinput   | randurl |
102 | Hello world |  GdksQ  |
Then I'm trying to make it so that if a user visits example.com/GdksQ then it would display Hello world
I've already attempted grabbing the data from the database etc., but all my attempts seem to lead back to the 500 internal server error.
<?php $endurl = $_POST['idgen']; ?>
<?php
if (isset($_POST['userentry'])) {
    // servername, username, password, dbname here
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO mydatabasename (userinput,randurl)
    VALUES ('$_POST[userentry]','$_POST[idgen]')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    $conn->close();
    header('Location: http://example.com/'.$endurl);
}

The if part of this statement (above) seems to be working, because as mentioned, it does insert the values into the database, and it does take you to a random url after you submit the form (but I still can't display userentry nor idgen, even if I write it outside of this statement.
else if (isset($_GET['idgen'])) {
    // servername, username, password, dbname here
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT userinput FROM mydatabasename WHERE randurl = '".$_GET[idgen]."'";

    $result = $db->query($sql);
    if ($result) {
            if ($row = $result->fetch_object()) {
            echo($row['userinput']); }
        $result->close() ; }
  $conn->close(); } ?>

As far as I've been able to narrow it down, it's the above else if statement that's causing the 500 internal server error. Although I'm not sure if this is also what's preventing me from displaying / using the userinput?
<form action="/run.php" method="POST">
    <input type="hidden" name="idgen" value="<?php echo $randomGen ?>">
    <input type="text" name="userentry">
    <input type="submit">
</form>

($randomGen is just a function that generates a random 5 letter id for use in the url)
RewriteRule ^([0-9a-zA-Z]+)$ run.php?idgen=$1 [L]

This is the RewriteRule that allows me to use random urls and still run run.php on those pages.
EDIT:
Having checked the error logs, it seems the issue is stemming from this line:
$result = $db->query($sql); as it says PHP Fatal error:  Call to a member function query() on null in /home/mycpanelname/public_html/run.php on line 46.
There's also some PHP Notices, but mainly seem to be undefined variables etc.


text:
Q: Is the extension $ \mathbb{Q}(\sqrt{2}, \sqrt{3}) $ simple? Intuitively, it is not.
Can anyone give a proof?

A: It actually is, and the same can be said of any finite extension of $\mathbb{Q}$ per the primitive element theorem, which is indeed unintuitive and surprising.  In other words, there does exist a $\beta \in \mathbb{Q}(\sqrt{2}, \sqrt{3})$ such that $\mathbb{Q}(\beta) = \mathbb{Q}(\sqrt{2}, \sqrt{3})$.  To find such a $\beta$, we can take advantage of the following lemma:

Lemma: If $K/F$ is a Galois extension, then the minimal polynomial for any $a \in K$ has as its roots the elements in the orbit of $a$ under the action of $\text{Gal}(K/F)$.  That is, if $S = \{ \phi(a) \ | \ \phi \in \text{Gal}(K/F) \}$, then $\displaystyle \min_a(x) = \prod_{u_k \in S} (x-u_k)$.
Proof: This is a consequence of the fact that a polynomial is irreducible $\iff$ its Galois group acts transitively on its roots.  For a proof of this fact, see Theorem 2.9(b) here.  Notice that $\displaystyle \min_a(x)$ will be an irreducible polynomial (by definition), and its Galois group will be a subgroup of $\text{Gal}(K/F)$.  This latter fact is because, if $L \subseteq K$ is the splitting field of $\displaystyle \min_a(x)$, every $F$-automorphism of $L$ extends to an $F$-automorphism of $K$. $\qquad \blacksquare$

For a candidate $\beta$ that we choose, we already have the inclusion $\mathbb{Q}(\beta) \subset \mathbb{Q}(\sqrt{2}, \sqrt{3})$.  Therefore, we just need to guarantee that $\mathbb{Q}(\beta)$ is a degree-$4$ extension of the rationals, or equivalently, that the minimal polynomial of $\beta$ is of degree $4$ -- this will imply that the two fields are equal.  To do this, first determine the Galois group of $\mathbb{Q}(\sqrt{2}, \sqrt{3})$.  Then, taking advantage of the above lemma, use some creativity to find an element that yields four distinct Galois conjugates when acted upon by this group.


text:
Q: Sphinx, set exact matches for each record? So I've been using Sphinx with a rails project lately, I want to provide a list of 'would be' exact matches that would match 100% with a give term. For example something like:
+==================+==========================================================+
|  ingredient      |  exact matches                                           |
+==================+==========================================================+
|  cheese, cream   |  'cream cheese','philadephia cream cheese','cream chese',|
|                  |  'creamed cheese'                                        |
+------------------+----------------------------------------------------------+
|  Cheese, gruyere |  'gruyere','gruyer cheese','gruyeres cheese'             |
|                  |  'gruyere chese'                                         |
+------------------+----------------------------------------------------------+
|  Cheese, blue    |  'blue cheese','blu cheese'                              |
+------------------+----------------------------------------------------------+

So basically the functionality I'm looking for would be that Sphinx would try to do its typical matching on all the records, but if the search term matches exactly with one of the strings in an array in that record that result would have a much higher weight. (like 100x, so it would then be the best match)
Is this possible? It seems like other people would have had this problem before... no?

Update
I suppose the best answer might be to just index the exact matches column and provide a really high weight to the terms.
I'm not sure how I can break up the "array" and see if the search term matches exactly though...

A: Your should try to play with sphinx search modes. Look at match phrase and match extended2.


text:
Q: Triggers / procedures help create table  student
(spnr   VARCHAR(5)  PRIMARY KEY,
sname   VARCHAR(10),
saddress    VARCHAR(10),
stel    VARCHAR(10) )

create table course
    (ccode  VARCHAR(5)  PRIMARY KEY,
    cname   VARCHAR(10),
    caddress    VARCHAR(10),
    points  int )

create table studies
    (id     int     PRIMARY KEY,
     spnr   VARCHAR(5)  NOT NULL,
     ccode  VARCHAR(5)  NOT NULL,
     result int,
    CONSTRAINT STUDIES_SPNR_FK FOREIGN KEY(spnr) REFERENCES student(spnr),
    CONSTRAINT STUDIES_CCODE_FK FOREIGN KEY(ccode) REFERENCES course(ccode) )

create trigger t1  on  course
after update,insert
as
    print 'inside trigger';
    select i.ccode from inserted i, deleted d
    where i. ccode = d. ccode

create procedure what (@tableName varchar(10))
as
begin

    declare @name varchar(20);

    declare c cursor for
    select column_name
    from information_schema.columns
    where table_name = @tableName;
    open c;
    fetch c into @name;
    while @@fetch_status = 0 begin
        print 'name:' + @name;
        fetch c into @name;
    end

    close c;
    deallocate c;
end;

When running:
begin transaction
insert into course values('K1','data1','lund',5);
update course
set cname ='informatik';
commit

The following message is displayed:
   inside trigger

(0 row(s) affected)

(1 row(s) affected)
inside trigger

(1 row(s) affected)

(1 row(s) affected)

In the end, why does 1 row affected show 2 times in the end?? When it only changes cname to "informatic" at one position?

A: One "1 row affected" results from the UPDATE and one from the SELECT within the trigger. Try removing the SELECT from the trigger and you should only see one "1 row affected."


text:
Q: python integral calculation without using for loop I want to implement a python program, which can calculate this integral

I know how to make it using For Loop and it will look something like this
import numpy as np;

def numint(f,alpha,beta,N,b,c):
    s = np.size(b);
    x = np.linspace(alpha,beta,N);
    h = x[1]-x[0];
    result = 0;
    result1 = 0;
    for j in range(1,N+1):
        for i in range(1,s+1):
           result1+=b[i]*f(x[j-1]+h*c[i]);
        result+=h*result1;
        result1 = 0;
    return result;

Without loop I think it should be something like this:
def numint(f,alpha,beta,N,b,c):
    s = np.size(b);
    x = np.linspace(alpha,beta,N);
    h = np.ones(N,dtype=int)*(x[1] - x[0]);
    result = 0;
    result = np.sum(h[1:N+1] * np.sum(b*(f(x[0:N]+h[0]*c))));
    return result;

But the second part of the result = np.sum ... is wrong and I dont know how to fix it . Any suggestions ?
EDIT :
def numint(f,alpha,beta,N,b,c):
    s = np.size(b);
    x = np.linspace(alpha,beta,N);
    h = np.ones(N,dtype=int)*(x[1] - x[0]);
    functionResult = f(x+h*c);
    dif = np.diff(functionResult);
    result = 0;
    result = np.sum(h[1:N+1] * np.sum(b*dif.sum()));
    return result;

As a tip : vectorize them
but I don't know how to use it

A: What you are looking for is the np.diff function.
Say you are looking for the integral from 0 to 10 for f(x) = x^2 with F(x) = (x^3)/3:
x = np.linspace(0, 10, 1000)
F = lambda x: x**3/3
b = F(x)

dif = np.diff(b)

sum = dif.sum()

print(sum)
333.33333333333326

Actual result is 333.3...
You can replace F by any function you want, but the key is np.diff which decreases the size of your array by one. Then, just sum the differences along your interval and you have your result.
You can improve the precision of your result by simply increasing the number of steps (1000 in my example).


text:
Q: Dart: change line color of stepper I have a stepper that looks like this:

i want that when the button 'testing' is pressed, the lines would change the color to red:

pubsec.yaml dependencies:
status_change: "2.0.0"
StepperWidget.dart:

class StepperWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => _StepperWidgetState();

}

class _StepperWidgetState extends State<StepperWidget>{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Stepper(
          controlsBuilder: (context, _) {
            return Row(
              children: <Widget>[

              ],
            );
          },
          type: StepperType.horizontal,
          steps: const[
            Step(
              title:Text("Step 1"),
              content: Text(""),
            ),
            Step(
              title:Text("Step 2"),
              content: Text("Information step 2"),
            ),
            Step(
              title:Text("Step 3"),
              content: Text("Information step 3"),
            ),
          ],

        )
      )
    );
  }

}

Stepper.dart is a file from flutter's libraries that I modified. Paste the code below instead of the original _buildHorizontal() method:
 Widget _buildHorizontal() {
    final List<Widget> children = <Widget>[
      for (int i = 0; i < widget.steps.length; i += 1) ...<Widget>[
        InkWell(
          //TATA NIk
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 60,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    if (widget.steps[i].label != null) const SizedBox(height: 110.0,),
                    Center(child: _buildIcon(i)),
                    if (widget.steps[i].label != null) SizedBox(height : 110.0, child: _buildLabelText(i),),
                  ],
                ),
              ),
              Container(
                child: _buildHeaderText(i),
              ),
            ],
          ),
        ),
        if (!_isLast(i))
          addLine(Colors.blue),
      ],
    ];

    final List<Widget> stepPanels = <Widget>[];
    for (int i = 0; i < widget.steps.length; i += 1) {
      stepPanels.add(
        Visibility(
          maintainState: true,
          visible: i == widget.currentStep,
          child: widget.steps[i].content,
        ),
      );
    }

    return Column(
      children: <Widget>[
        Material(
          // elevation: widget.elevation ?? 2,
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Row(
              children: children,
            ),
          ),
        ),
        TextButton(onPressed: () {
          changeColor();
        }, child: Text('testing'))

      ],
    );
  }

  getLine(color){
    return Expanded(
      child: Container(
        margin: const EdgeInsets.only(left: 0.0, right: 0.0, bottom: 20.0),
        height: 4.0,
        color: color,
      ),
    );
  }

  changeColor(){
    setState(() {
      var index = 0;
      for(var line in lines){
        lines[index] = getLine(Colors.red);
        index ++;
      }
    });
  }

  Widget addLine(color){
    var line = getLine(color);
    lines.add(line);
    return lines.last;
  }

When I check, the lines colors are changed indeed, but the new color is not shown on the screen. What is going wrong here and what can I do to make the button work?


text:
Q: Stylelint rule to prevent overriding a class from a library One big problem with major version upgrades with breaking changes from CSS/SASS libraries is that if you happened to override the library CSS classes, your CSS overrides become a potential increased risk/scope when upgrading.
So if a CSS library exports a .input class, I'd like to configure a stylelint rule that will prevent me and my team from declaring an .input class on my CSS files.
I do understand this plugin/rule may need to be configured with a list of exported CSS classes by the library, but that's ok, we can probably create it automatically as part of the build process and pass it to the plugin.
Is there such a plugin/rule?


text:
Q: Redis Windows Error: connect ECONNREFUSED 127.0.0.1:6379 but appilcation is working I am having an issue with my nodejs-redis-docker-compose application. The application ran normally for a few times. But later, it started giving me the following error. I am using redis-server v3.2.100 docker 18.09.1 build 4c52b90. I uninstalled docker and redis and re-installed them but I still have the same problem. Here is the error.
REDIS_DB | 1:C 22 Jan 2019 02:24:00.208 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
REDIS_DB | 1:C 22 Jan 2019 02:24:00.208 # Redis version=5.0.3, bits=64, commit=00000000, modified=0, pid=1, just started
REDIS_DB | 1:C 22 Jan 2019 02:24:00.208 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
REDIS_DB | 1:M 22 Jan 2019 02:24:00.210 * Running mode=standalone, port=6379.
REDIS_DB | 1:M 22 Jan 2019 02:24:00.210 # WARNING: The TCP backlog setting of
511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
REDIS_DB | 1:M 22 Jan 2019 02:24:00.210 # Server initialized
REDIS_DB | 1:M 22 Jan 2019 02:24:00.210 # 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.
REDIS_DB | 1:M 22 Jan 2019 02:24:00.211 * DB loaded from disk: 0.001 seconds
REDIS_DB | 1:M 22 Jan 2019 02:24:00.211 * Ready to accept connections
MAIN_API    | [nodemon] starting `node --trace-warnings index.js`
MAIN_API    | Unhandled Rejection at: Promise Promise {
MAIN_API    |   <rejected> { Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    |     errno: 'ECONNREFUSED',
MAIN_API    |     code: 'ECONNREFUSED',
MAIN_API    |     syscall: 'connect',
MAIN_API    |     address: '127.0.0.1',
MAIN_API    |     port: 6379 } } reason: Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    | Unhandled Rejection at: Promise Promise {
MAIN_API    |   <rejected> { Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    |     errno: 'ECONNREFUSED',
MAIN_API    |     code: 'ECONNREFUSED',
MAIN_API    |     syscall: 'connect',
MAIN_API    |     address: '127.0.0.1',
MAIN_API    |     port: 6379 } } reason: Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    | ✓-- Redis client pid=>37 Connected
MAIN_API    | --- Redis server pid=>37 is ready
MAIN_API    | ~~~ Testing local redis storage...
MAIN_API    | ✓-- Redis pid=>37 startup test succeeded
MAIN_API    | ✓-- MongoDB pid=>37 Connected
MAIN_API    | ✓-- Server pid=>48 running at port: 5555
MAIN_API    | Unhandled Rejection at: Promise Promise {
MAIN_API    |   <rejected> { Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    |     errno: 'ECONNREFUSED',
MAIN_API    |     code: 'ECONNREFUSED',
MAIN_API    |     syscall: 'connect',
MAIN_API    |     address: '127.0.0.1',
MAIN_API    |     port: 6379 } } reason: Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    | Unhandled Rejection at: Promise Promise {
MAIN_API    |   <rejected> { Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |       at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    |     errno: 'ECONNREFUSED',
MAIN_API    |     code: 'ECONNREFUSED',
MAIN_API    |     syscall: 'connect',
MAIN_API    |     address: '127.0.0.1',
MAIN_API    |     port: 6379 } } reason: Error: connect ECONNREFUSED 127.0.0.1:6379
MAIN_API    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
MAIN_API    | ✓-- Redis client pid=>48 Connected
MAIN_API    | --- Redis server pid=>48 is ready
MAIN_API    | ~~~ Testing local redis storage...
MAIN_API    | ✓-- Redis pid=>48 startup test succeeded
MAIN_API    | ✓-- MongoDB pid=>48 Connected

The error is thrown when the nodejs application is starting but it get connected to the redis server by the time the application is up and running.
Redis console log
[16308] 21 Jan 18:03:25.425 # Server started, Redis version 3.2.100
[16308] 21 Jan 18:03:25.426 * DB loaded from disk: 0.000 seconds
[16308] 21 Jan 18:03:25.426 * The server is now ready to accept connections on port 6379

I ran netstat -a -n -o on my console and here is the relevant part (I believe).
TCP    0.0.0.0:6379           0.0.0.0:0              LISTENING       16308
TCP    [::]:6379              [::]:0                 LISTENING       16308

The following are my files.
./Dockerfile
FROM node:10.15.0

RUN mkdir -p ./usr/src/MainAPI

WORKDIR /usr/src/MainAPI

COPY ./ ./usr/src/MainAPI

RUN npm install

ARG NODE_VERSION=10.15.0

./docker-compose.yml
version: "3.7"

services:

  # Redis
  redis:
    container_name: REDIS_DB
    image: redis
    ports:
      - "6378:6379"

  # API
  main-api:
    container_name: MAIN_API
    build: ./
    command: ["npm", "start"]
    working_dir: /usr/src/MainAPI
    ports:
      - "5555:5555"
    volumes:
      - ./:/usr/src/MainAPI

./redisClient.js
const Redis = require("ioredis");
//module.exports = require("redis").createClient(...); => same errors with this module as well

module.exports = new Redis('redis://redis:6379/0');

//module.exports = new Redis('redis://127.0.0.1:6379/0'); =>crashes the app
//module.exports = new Redis('redis://redis:6378/0'); =>crashes the app also

./app.js
"use strict";

const express = require("express");
const { red, green, cyan, yellow } = require("kleur");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const cors = require("cors");
const path = require("path");
const helmet = require("helmet");

const redisClient = require("./redisClient");

const { CLIENT_BASE_URL, API_BASE_URL, MONGO_URI } = process.env;

const isProduction = process.env.NODE_ENV === "production";

const server = express();

const whitelist = [CLIENT_BASE_URL, API_BASE_URL];
const corsOptions = {
  origin: function(origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      return callback(null, true);
    } else {
      return callback(new Error("Not allowed by CORS"), false);
    }
  }
};

server.use(helmet());

if (isProduction) {
  server.use(cors(corsOptions));
  server.use(morgan("combined"));
} else {
  server.use(morgan("dev"));
}

server.set("trust proxy", 1);

/**
 * Test redis storage on deploy
 */
redisClient.on("connect", function() {
  console.log(
    green("✓-- ") + "Redis client pid=>" + process.pid + " Connected"
  );
});

redisClient.on("ready", function() {
  console.log(cyan("--- Redis server pid=>" + process.pid + " is ready"));
  console.log(cyan("~~~ Testing local redis storage..."));
  const testKey = "key";
  const testValue = "value";
  redisClient.set(testKey, testValue).then(() => {
    redisClient.get(testKey, (error, result) => {
      if (error) {
        console.log(red("✗-- An error occured while testing redis storage"));
        console.error(error);
        return process.exit(1);
      }
      if (!result || result !== testValue) {
        console.log(
          red(
            "✗-- Redis pid=>" + process.pid + " did not pass the startup test"
          )
        );
        console.error(result);
        return process.exit(1);
      }
      console.log(
        green("✓-- Redis pid=>" + process.pid + " startup test succeeded")
      );
    });
  });
});

redisClient.on("error", function(err) {
  console.log(red("✗-- Something went wrong with redis"));
  console.error(err);
  process.exit(1);
});

redisClient.on("end", function() {
  console.log(
    yellow("--- ") + "Redis client pid=>" + process.pid + " closed connection"
  );
});

mongoose.set("useCreateIndex", true);
mongoose.Promise = global.Promise;
mongoose
  .connect(
    MONGO_URI,
    {
      useNewUrlParser: true
    }
  )
  .then(() => {
    console.log(green("✓-- ") + "MongoDB pid=>" + process.pid + " Connected");
  })
  .catch(err => {
    console.log(red("✗--Database Connection"));
    console.error(err);
    process.exit(1);
  });

server.use(
  bodyParser.urlencoded({
    extended: false
  })
);
server.use(bodyParser.json());

require("./controlers/home")(server);
require("./controlers/user")(server);
require("./controlers/admin")(server);

if (isProduction) {
  server.use(express.static("client/build"));

  server.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

module.exports = server;

I did not call .listen(...) on the server because it is exported to another file (index.js).
Thank you

A: I am responding to my own question. I found what is causing the issue in my code. In fact, I started using npm agenda, which uses MongoDB, for scheduling some tasks in my application. I later switched to npm bull, which is using Redis. I created the queue instance like the following.
const Queue = require("bull");

const emailQueue = new Queue("emails");

while it should be
const Queue = require("bull");

const emailQueue = new Queue("emails", {
  redis: { port: 6379, host: "redis-server" }
});

Because I did not specify the redis settings for the module, it was not able to connect to the server. I totally forgot that I had another module that is using redis. The reason the app seemed to be working is because express get connected to redis while bull did not. I would figure that out if I had tried to use a feature that bull is part of the process. I also simplified my Dockerfile and docker-compose.yml files to include only the necessary steps.
/Dockerfile
FROM node:alpine # create image with NodeJS version alpine included

WORKDIR /usr/app # set working directory of the app to be /usr/app/. create folder /usr/app if it does not exist already. The following operations would then happen inside /usr/app

COPY ./package.json ./ # copy package.json file into current directory, which is /usr/app according to previous step

RUN npm install # install dependencies

COPY ./ ./ # add the rest of the files to /usr/app

CMD ["npm", "start"] # run 'npm start' when the container is starting

/docker-compose.yml
version: "3"

services:
  # Redis
  redis-server: # the name of the redis service becomes the host name in my application
    container_name: REDIS_SERVER
    image: 'redis'

  # API
  main-api:
    container_name: MAIN_API
    build: ./
    ports:
- "5555:5555"

I did not need anything else for the application to work. By simply giving the service name to ioredis in my application, the module will figure out where to find the server. That is said here in links section. In my case, the server name is redis-server so the hostname for ioredis and bull would also be redis-server and the port number 6379. Thank you @DavidMaze @yeaseol, and ...

A: The port is bound to 6378, so you need to access 6378.
And can you use hostname redis? (Did you set it?)
Try this:
module.exports = new Redis('redis://{docker-server-hostname}:6378');
or
The best option is to set a link to docker-compose.
main-api:
    container_name: MAIN_API
    build: ./
    command: ["npm", "start"]
    working_dir: /usr/src/MainAPI
    ports:
      - "5555:5555"
    volumes:
      - ./:/usr/src/MainAPI
    links:
      - {your-redis-container-name}

Try this:
module.exports = new Redis('redis://{your-redis-container-name}:6379');


text:
Q: What are the impacts of running VirusScan on a Linux server? I am asked in a bid for tender to assert that my software will cohabit without a problem with VirusScan (v6.0.3) under Linux.

My software is a web application, running under tomcat.
It can create additional JVMs (to run ETL jobs) and writes reporting files (mostly PDF and HTML) in an application directory.

Are there any specific problem I should be aware of regarding VirusScan running on the server my app will run on ?

A: The impacts of running AV on linux are the same as the impacts of running AV on any other OS. A couple of the main impacts that come to mind are:

*

*Increased IO, CPU, and Memory load

*Possibility of bad things happening due to false positives

Point #1 can be mitigated by scaling hardware properly, and #2 can be mitigated via AV software configuration such as exempting certain critical files, but of course then you run the risk of those exempted files getting infected without detection.


text:
Q: Custom Culture not applying when running an Azure DevOps build pipeline I'm trying to create a function that converts a string that represents a number into a custom currency format. I need to invert the separators (turn commas into dots and dots into commas) and add the $ symbol in front.
Example input format: "70000.50"
Example output required format: "$ 70.000,50"
My function is this
    public static string ToCurrencyFormat(this string str)
    {
        if (!string.IsNullOrEmpty(str))
        {
            str = $"$ {Convert.ToDecimal(str, new CultureInfo("en-US")):N2}";
        }

        return str;
    }

This function works fine on my computer.
The problem is that when i run tests of this function in a build pipeline in Azure DevOps, the tests fail with this error:
Error Message:
Expected member Body[2] to be
"Value: $ 70.000,00", but
"Value: $ 70,000.00" differs near ",00" (index 12).

It seems that a different culture than the one I'm specifying is being used to convert the decimal.
Someone told me that i should change the culture in the server, or in the dockerfile of my application.
My questions are:
Why is the function failing to use "en-US" as culture when running in Azure DevOps?
Why are server/dockerfile culture taking precedence over the one i'm specifying as parameter?

A: Alright, so there's a little to get through here.  First, it isn't clear why your input is a string and not a number.  If it must be a string, let's separate the step of converting that into a number out.  In your example code this is the only stage you're setting the culture specifically.
/// <summary>
/// Note this is really just a wrapper around TryParse (so needless) but perhaps you do other
/// processing at this stage (undocumented)
/// </summary>
/// <param name="stringForm"></param>
/// <returns></returns>
public static bool ParseNumber(string stringForm,out decimal result)
{
   //Allow leading currency, decimal point, thousands separator - in your example the input number
   // ONLY contains a decimal separator, in which case you don't need the other two styles.
   var style = NumberStyles.AllowCurrencySymbol
     | NumberStyles.AllowDecimalPoint
     | NumberStyles.AllowThousands;

   //You don't specify whether the incoming string has a culture.. it might, although - again -
   // in the example you gave it looks like it's really a number and not a string at all.
   // If you know the culture, use `new CultureInfo()` here
   if (!decimal.TryParse(stringForm, style, CultureInfo.InvariantCulture, out result)) return false;

   //Do other things with the number

   return true;
}

Now to format a number as you've requested..  using the C format gets us a currency indicator too.
public static string FormatForCurrency(decimal number)
{
   var format = new NumberFormatInfo
   {
      CurrencySymbol = "$",
      CurrencyDecimalSeparator = ",",
      CurrencyDecimalDigits = 2,
      CurrencyGroupSeparator = "."
   };
   return number.ToString("C", format);//$70.000,50
}

If you must have string based numbers, then to use these together you'd use code like the following:
public static string UseStringNumberAndFormatAsCurrency(string numberAsString)
{
   if (!ParseNumber(numberAsString, out var num))
   {
      //You may want to throw an exception instead, you could also consider `decimal.Parse`
      // instead of `decimal.TryParse` for this
      Console.WriteLine("Invalid string number: ", numberAsString);
      return null;
   }
   return FormatForCurrency(num);
}


text:
Q: Android Studio : Could not download FastInfoset.jar (com.sun.xml.fastinfoset:FastInfoset:1.2.15): No cached version available for offline mode error I am a new user of the android studio. Initially, I faced with problems like the run button being disabled, and the XML display showing nothing.
When I was trying to resolve these problems, I confront with a bunch of error codes.
A problem occurred configuring root project 'Myfirstapp'.
   > Could not resolve all artifacts for configuration ':classpath'.
   > Could not download protobuf-java.jar (com.google.protobuf:protobuf-java:3.4.0): No cached version available for offline mode
   > Could not download bcpkix-jdk15on.jar (org.bouncycastle:bcpkix-jdk15on:1.56): No cached version available for offline mode
   > Could not download bcprov-jdk15on.jar (org.bouncycastle:bcprov-jdk15on:1.56): No cached version available for offline mode
   > Could not download fastutil.jar (it.unimi.dsi:fastutil:7.2.0): No cached version available for offline mode
   > Could not download jimfs.jar (com.google.jimfs:jimfs:1.1): No cached version available for offline mode
   > Could not download guava.jar (com.google.guava:guava:27.1-jre): No cached version available for offline mode
   > Could not download httpclient.jar (org.apache.httpcomponents:httpclient:4.5.6): No cached version available for offline mode
   > Could not download httpcore.jar (org.apache.httpcomponents:httpcore:4.4.10): No cached version available for offline mode
   > Could not download kotlin-reflect.jar (org.jetbrains.kotlin:kotlin-reflect:1.3.71): No cached version available for offline mode
   > Could not download antlr4.jar (org.antlr:antlr4:4.5.3): No cached version available for offline mode
   > Could not download juniversalchardet.jar (com.googlecode.juniversalchardet:juniversalchardet:1.0.3): No cached version available for offline mode
   > Could not download gson.jar (com.google.code.gson:gson:2.8.5): No cached version available for offline mode
   > Could not download kotlin-stdlib.jar (org.jetbrains.kotlin:kotlin-stdlib:1.3.71): No cached version available for offline mode
   > Could not download proguard-base.jar (net.sf.proguard:proguard-base:6.0.3): No cached version available for offline mode
   > Could not download jdom2.jar (org.jdom:jdom2:2.0.6): No cached version available for offline mode
   > Could not download commons-compress.jar (org.apache.commons:commons-compress:1.12): No cached version available for offline mode
   > Could not download trove4j.jar (org.jetbrains.trove4j:trove4j:20160824): No cached version available for offline mode
   > Could not download commons-codec.jar (commons-codec:commons-codec:1.10): No cached version available for offline mode
   > Could not download jaxb-runtime.jar (org.glassfish.jaxb:jaxb-runtime:2.3.1): No cached version available for offline mode
   > Could not download FastInfoset.jar (com.sun.xml.fastinfoset:FastInfoset:1.2.15): No cached version available for offline mode

Here is a screenshot of errors i am facing:

A: Make sure you have a stable internet connection before try to sync your project. an check your proxy settings. Make sure the auto detect option is checked. you can access it in Files > Settings > Appearance and Behavior > System Settings > HTTP proxy for windows though. Am sure for linux its the same path.
and to enable and disable gradle offline mode,, its just easy on android 3.6 an the right pane in the image second right icon under gradle

A: Note on Gradle you are using "Gradle offline" that is why the cache is failing (6th button from the left).
If deactivated the "No cached version available for offline mode" errors would disappear.

A: You're currently using offline mode.
In order to use gradle's offline mode, it must've been connected to the internet at least once to download the required dependencies and cache the modules that are going to be used in your project.
The process to disable it is very simple:

*

*Click on the word gradle in your right side of the screen.

*A panel will appear with some information and tasks, from the top tools bar (The one below the word gradle in your picture) and to the very right, you'll see a button with settings (configuration) icon, to its left, there's a highlighted button with crossed-line icon, click on it to enable online mode.

*You'll need to sync your project (You will need to have access to the internet), by going to Files -> Sync Project with gradle files

*Then Run -> Rebuild, to build the project and have the preview in your designer.

*After the sync finishes, you can repeat the first step to toggle offline mode if you wish to, your project will have cached the modules you need and you'll be able to build your project without internet.

Source: https://developer.android.com/studio/releases#3.6-gradle-offline-ui
Search for: New location to toggle Gradle's offline mode
More about Offline-Mode: https://developer.android.com/studio/build/optimize-your-build#offline_mode
Search for: Enable offline mode

Happy coding!


text:
Q: Dynamically set the cell contents of a DataGridColumn I'm creating a dynamic UI application in WPF MVVM that binds areas of the UI to a collection of my custom UIField class.
UIField contains a number of BindingProperty properties that allow me the specify the property the Control will bind to.
public abstract class UIField : BaseObject
{
    BindingProperty property, isReadonly = new BindingProperty(false, false);
    object dataContext;

    public BindingProperty Property
    {
        get { return property; }
        set { SetProperty(ref property, value, () => Property); }
    }
    public BindingProperty IsReadonly
    {
        get { return isReadonly; }
        set { SetProperty(ref isReadonly, value, () => IsReadonly); }
    }
    public object DataContext
    {
        get { return dataContext; }
        set { SetProperty(ref dataContext, value, () => DataContext); }
    }
}

In a ResourceDictionary I template the derived classes of UIField
<DataTemplate DataType="{x:Type fields:TextBoxField}">
    <TextBox metro:TextBoxHelper.Watermark="{e:IndirectBinding Watermark}"
             metro:TextBoxHelper.UseFloatingWatermark="{e:IndirectBinding UseFloatingWatermark}"
             IsReadOnly="{e:IndirectBinding IsReadonly}"
             Text="{e:IndirectBinding Property}"
              />
</DataTemplate>

And I then create these fields in the view model and add them to a collection. The UI then binds to the collection using an ItemsControl
new TextBoxField()
{
    DataContext = this,
    Property = new BindingProperty(() => ((SalesOrder)Order).SecondSalesReference),
    Watermark = new BindingProperty("Customer Ref. Number", false),
    UseFloatingWatermark = new BindingProperty(true, false)
 }

This is working great for normal fields but I'm running into a problem with DataGrid.
Preferably, I would like to be able to bind a collection of UIFields that have been extended to provide a Header property to the columns of a DataGrid and then template these to DataGridColumns but you can't have a DataGridColumn in a DataTemplate.
Currently, I've created an interface that gives me the header, DataGridColumn type and the contents that should be in each cell:
public interface IDataGridField
{
    string Header { get; set; }

    Type ColumnType { get; }

    UIField CellContents { get; }
}

I then bind these to a DataGrids columns using:
public class DataGridHelper
{
    public static readonly DependencyProperty BindableColumnsProperty = DependencyProperty.RegisterAttached("BindableColumns", typeof(ThreadSafeCollection<IDataGridField>), typeof(DataGridHelper),new UIPropertyMetadata(null, BindableColumnsPropertyChanged));
    static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        var dataGrid = source as DataGrid;
        var columns = e.NewValue as ThreadSafeCollection<IDataGridField>;
        dataGrid.Columns.Clear();
        if (columns == null)
            return;

        foreach (var column in columns)
        {
            var newColumn = Utility.CreateInstance(column.ColumnType) as DataGridColumn;
            newColumn.Header = column.Header;
            dataGrid.Columns.Add(newColumn);
        }
    }
    public static void SetBindableColumns(DependencyObject element, ThreadSafeCollection<IDataGridField> value)
    {
        element.SetValue(BindableColumnsProperty, value);
    }
    public static ThreadSafeCollection<IDataGridField> GetBindableColumns(DependencyObject element)
    {
        return (ThreadSafeCollection<IDataGridField>)element.GetValue(BindableColumnsProperty);
    }
}

This will give me columns with headers but no content in the DataGridCells.
How can I set the contents of each cell in the DataGridColumn created?
EDIT 1 (Progress?):
I realised that the DataGridColumn generated has to be a DataGridTemplateColumn so this opens up a few more properties.
I've modified IDataGridField, changing the UIField property to a Type instead.
Then, when generating the new DataGridColumn I just get the DataTemplate assigned to the selected Type
foreach (var column in columns)
{
    var newColumn = new DataGridTemplateColumn();
    var key = new DataTemplateKey(column.CellContentType);
    var template = Application.Current.FindResource(key) as DataTemplate;
    newColumn.CellTemplate = template;
    newColumn.Header = column.Header;
    dataGrid.Columns.Add(newColumn);
}

I think the only problem now is applying the bindings.

A: It seems you want to reinvent the wheel. The WPF DataGrid handle basic DataTypes like string, bool, int already quite well. But you will have your reasons why.
I think if you want to go for dynamic approach you want to set the CellTemplate or/and CellEditingTemplate instead of creating the "correct" column type. This would also work for more complex datatypes.
This is just XAML but it should show the direction you could go:
<DataGrid ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                        <TextBox metro:TextBoxHelper.Watermark="{e:IndirectBinding Watermark}"
             metro:TextBoxHelper.UseFloatingWatermark="{e:IndirectBinding UseFloatingWatermark}"
             IsReadOnly="{e:IndirectBinding IsReadonly}"
             Text="{e:IndirectBinding Property}"
              />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

You could also use the AutoGeneratingColumn event of the datagrid to override the creation of columns. Maybe you want to derive your CustomDataGrid?
private void DataGrid_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
{
    //check for the type
    if (e.PropertyType == typeof(TextField))
    {
        DataGridTemplateColumn newDataGridTemplateColumn = new DataGridTemplateColumn();
        e.Column = newDataGridTemplateColumn;

        //do some datatemplate voodoo, maybe you want to load it from resources or similar
        StringReader stringReader = new StringReader(
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
    <" + typeof(ComboBox).Name + @" Text=""{Binding " + "Text" + @"}""/>
</DataTemplate>");
        XmlReader xmlReader = XmlReader.Create(stringReader);
        DataTemplate template = XamlReader.Load(xmlReader) as DataTemplate;

        newDataGridTemplateColumn.CellTemplate = template;
    }
}


text:
Q: How to make a variable NULL? I am using JQuery to store some hidden Form element values as variables. Sometimes these hidden fields do not have a value at all.
In the situation where a hidden field does not have a value, the Jquery variable is returning 0 as the value when I actually want null.
Why do I want null? Because it's being passed to a database and storing 0 is incorrect. It should insert null.
So how can I get JQuery to return/store null and not 0?

A: A hidden field always has a value. If you haven't specified one, it's an empty string.
You can't put null as a value of a hidden field, so you need to handle the empty values either in the code that sends the information to the server, or in the code on the server.


text:
Q: Is it possible to share secrets among ECS Container Definitions in Cloud-formation? I have requirement to create 5 Container definitions which have common environmental variables as secrets. But the count of them is around 50. So instead of duplicating these 50 secrets, is there a way I can create all these a single resource and refer them in all container definitions ?

A: You could use AWS Systems Manager Parameter Store. It's intended for this kind of situation, when sharing config values between multiple containers, lambda functions, etc.


text:
Q: fill_between in new version of matplotlib gives an error "where size does not match" As title says, I didn't have any problem running following code in previous matplotlib (3.2.1) but got an error message after installing new version (3.5.1) of matplotlib. I googled possible solutions in vain. Would appreciate any hint to resolve this problem.
Code:
       axs[irow, icol].plot(wavelengths, np.mean(spec_mat[y == i + 1, :], axis=0).T, colors[i], linewidth=lw)
        if is_conf:
            print(f"wavelengths: {wavelengths.shape}")
            print(f"Quantiles: {np.quantile(spec_mat[y == i + 1, :], 0.025, axis=0).shape}")
            axs[irow, icol].fill_between(wavelengths,
                                 np.quantile(spec_mat[y == i + 1, :], 0.025, axis=0).T,
                                 np.quantile(spec_mat[y == i + 1, :], 0.975, axis=0).T,
                                 colors[i], alpha=alpha)

Error
  File "draft\utils.py", line 2487, in draw_average_spectra_preprocessing_per_class
    axs[irow, icol].fill_between(wavelengths,
  File "draft\venv\lib\site-packages\matplotlib\__init__.py", line 1412, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)
  File "draft\venv\lib\site-packages\matplotlib\axes\_axes.py", line 5252, in fill_between
    return self._fill_between_x_or_y(
  File "draft\venv\lib\site-packages\matplotlib\axes\_axes.py", line 5171, in _fill_between_x_or_y
    raise ValueError(f"where size ({where.size}) does not match "
ValueError: where size (1) does not match x size (175)

A: As usual, I found the solution after writing this post. I have to use color keyword in new version. The following line resolved the problem:
            axs[irow, icol].fill_between(wavelengths,
                                 np.quantile(spec_mat[y == i + 1, :], 0.025, axis=0).T,
                                 np.quantile(spec_mat[y == i + 1, :], 0.975, axis=0).T,
                                 color=colors[i], alpha=alpha)


text:
Q: Prevent account deletion for 24 hours after edits or deletions of posts I encountered an interesting abuse of the system today where a user setup an account deletion.  Knowing how long it would take for the deletion to process, immediately before it would become active, they began rapidly truncating and deleting their posts.
When the deletion went through, it severed the log of changes and required a manual review through a very large portion of their overall posts to undo the vandalism.
To prevent this, we should either delay the deletion when edits or post deletions are made to allow time for undoing vandalism or simply apply a block to editing and post deletion after requesting account deletion.  (Alternately a suspension being automatically applied could also work.)

A: Another option, which might be more simple to implement, is such logic: once a user who requested account deletion and has the deletion timer ticking edits or deletes one of their posts, the deletion timer will be aborted. Not extended, no suspension, just aborted.
This must of course be well documented, and message better appear to the user before submitting edit or actually deleting a post, we already have such warnings in place e.g. users who are near a question ban.
But this would prevent any kind of abuse from the kind described in this question, and users who want a legit deletion will either leave their posts alone, or request to delete again after editing or deleting the post.

A: I've had to ask the CMs to speed up an account deletion request before because of a user complaining about having to wait an extended period of time to have their account deleted but I've also had users just request deletion and disappear.
But part of the point of the 24 hour delay is to give them the chance to reflect and reconsider their account deletion before it happens. Suspending them in the normal sense seems like it would be complicated and, in many cases, unnecessary.
I think it'd be more helpful if there were some way to preserve the user's recent activity log on the deletion stub so that moderators can review quickly if the user has been deleting or vandalizing their posts and have easy links at hand to revert those changes if necessary.
I'm hesitant to say that all edits and deletions should be prohibited because there could be legitimate reasons to do these actions - a sort of "getting your knitting in order" before you leave. Not all users remove their accounts because they're disgruntled and wish to wreak havoc on the way out.
But I also think that part of the problem here may have been the deletion process. For users with sufficiently high reputation or votes, this is done manually, not by the system. If this user fell into that category, this seems like a check that should be done before the account is actually deleted.
Perhaps site moderators should be given an alert for any users requesting their account be deleted who would trigger manual deletion and one of them should review the account before the deletion occurs, but not immediately upon the request for deletion, to make sure that none of this is being done. If it is, they can revert and suspend the user manually to prevent additional harm before a CM actually deletes the account.
This takes some of the work off of the CM's laps - a moderator can easily perform these checks and then give the account a "ready for deletion" stamp when the account hits 24 hours.