Q: Validation Summary for Collections EDIT: upgraded this question to MVC 2.0
With asp.net MVC 2.0 is there an existing method of creating Validation Summary that makes sense for models containing collections? If not I can create my own validation summary
Example Model:
public class GroupDetailsViewModel
{
    public string GroupName { get; set; }
    public int NumberOfPeople { get; set; }
    public List<Person> People{ get; set; }
}

public class Person
{
    [Required(ErrorMessage = "Please enter your Email Address")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid Email Address")]
    public string EmailAddress { get; set; }

    [Required(ErrorMessage = "Please enter your Phone Number")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Please enter your First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter your Last Name")]
    public string LastName { get; set; }
}

The existing summary <%=Html.ValidationSummary %> if nothing is entered looks like this.

The following error(s) must be corrected before proceeding to the next step
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name

The design calls for headings to be inserted like this:

The following error(s) must be corrected before proceeding to the next step
  Person 1
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name
  Person 2
  * Please enter your Email Address
  * Please enter your Phone Number
  * Please enter your First Name
  * Please enter your Last Name

Answer  Based on Pharcyde's answer.
public static MvcHtmlString NestedValidationSummary(this HtmlHelper helper)
{
    if (helper.ViewData.ModelState.IsValid)
        return MvcHtmlString.Empty;

    // create datastructure to group error messages under a given key (blank key is for general errors)
    var errors = new Dictionary<string,List<string>>();
    foreach (KeyValuePair<string, ModelState> keyPair in helper.ViewData.ModelState)
    {
        foreach (ModelError error in keyPair.Value.Errors)
        {
            //determine the 'key' for the group in which this error belongs
            var key = keyPair.Key.Split(']')[0];
            if (key.Contains("People["))
                key = "Person " + key.Split('[')[1];
            else
                key = string.Empty;

            if(!errors.ContainsKey(key))
                errors.Add(key,new List<string>());
            //now add message using error.ErrorMessage property
            errors[key].Add(error.ErrorMessage);
        }
    }

    // generate the HTML
    var ul = new TagBuilder("ul");
    foreach (KeyValuePair<string, List<string>> errorPair in errors.OrderBy(p=>p.Key))
    {
        var li = new TagBuilder("li");
        if(!string.IsNullOrEmpty(errorPair.Key))
            li.InnerHtml += string.Format("
{0}
",errorPair.Key);
        var innerUl = new TagBuilder("ul");
        foreach (var message in errorPair.Value)
        {
            var innerLi = new TagBuilder("li");
            innerLi.InnerHtml = message;
            innerUl.InnerHtml += innerLi.ToString(TagRenderMode.Normal);
        }
        li.InnerHtml += innerUl.ToString(TagRenderMode.Normal);
        ul.InnerHtml += li.ToString(TagRenderMode.Normal);
    }

    return MvcHtmlString.Create(ul.ToString(TagRenderMode.Normal));
}

A: You are going to have to extend the HtmlHelper methods and roll your own.  Heres the bit of code that is important for your situation where you need a group by:
//HtmlHelper being extended
if(helper.ViewData.ModelState.IsValid)
{
    foreach(KeyValuePair<string,ModelState> keyPair in helper.ViewData.ModelState)
    {
        //add division for group by here using keyPair.Key property (would be named "Person" in your case).

        foreach(ModelError error in keyPair.Value.Errors)
        {
            //now add message using error.ErrorMessage property
        }
    }
}


Q: Salesforce to SAP connection inside Azure I am trying to connect Salesforce to SAP inside Azure. So far I've come across three ideas to do so.

*

*Generating IDOC messages in SAP using logic Apps? Is it possible, if so what configs do we need here?

*Using FTP/SFTP

*Using APIs/Web Services?

If you have tried to do this and you have some advice you think it might help me please, let me know. I will appreciate it a lot.

A: Yes, you can actually use Logic Apps in this case. You can connect to Salesforce to SAP. Configuration depends on the requirements that you have.

You can even use the web Services by Exposing SAP functionality to the cloud with Azure App Services which will use a combination of API Apps to create a Logic App that exposes BAPI functionality to an external website.

A: I would not recommend an Salesforce to SAP integration from scratch. This is too much effort and you need to take care of things like error handling, delta load and security. Instead I would propose to use a tool that was made for such scenarios.
In case you only need data replication, you can go with something like SAP CPI or Mulesoft. They even offer templates, that make your life easier. You should be aware that these options can be expensive in regards to their licenses/subscriptions.
Another way would be a solution like Vigience Overcast, that offers data replication as well, but also real time access to SAP from within Salesforce. Overcast goes beyond exchanging data between the two systems, but also allows you to create the user interface. They even have pre-defined, ready-to-use apps for the most common use cases.


Q: Issue Writing/Reading Dates when using MS Excel VBA to MS ACCESS Database I'm developing an app in MS Excel (2019) in which I'm trying to write/read a date to MS Access (2019, same suite) via MS Excel VBA code, then retrieve it.  But no matter how I enter and format the date, all I get back from MS Access is gibberish.
Cannot figure this one out.  Everything I've found online has missed the point in providing a simple explanation as to what the problem is. I did realize that there is a total disconnect between the two applications and I am by far not the only dismayed person.
I think it's fair to expect get out get the same data that you put in. I mean, really, why is this even remotely difficult to do?
The code provided is completely stripped down to the elements required to get at the heart of it all.
Any help would be greatly appreciated.
Robert.
Option Explicit

Public Conn                 As New ADODB.connection
Public rs                   As New ADODB.Recordset
Public sconnect             As String
Public Const DATABASE_LOC   As String = "C:\Users\Robert\Documents\ASAP\db1"
Public Const DATABASE_NAME  As String = "Database1.accdb"

'MS Access datatable "TheDate" is a ShortDate
'My system date format is 'standard U.S. -  mm/dd/yyyy
'The cell from which result is read is in Date format
'
'Tried:
'ADate = CDate("12/29/2022")
'ADate = #12/29/2022#
'ADate = 'Format("12/29/2022", "mm/dd/yy")
'
'ALL result in: Result IN:  ? Date IN: 12/29/2022    - Access table field: 12:00:18 AM
'Result Out: ? Date OUT: 12:00:18 AM  - Cell "B1" (Date format) cell value: 1/0/1900  12:00:18 AM

Sub TestDateInAndOut()
     TestDateIntoDB
     TestDateOutOfDB
End Sub

Sub TestDateIntoDB()

    Dim SQLString As StringDim ADate As Date

   'option 1
   ADate = CDate("12/29/2022")

   'option 2
   ADate = #12/29/2022#

   'option 3
   ADate = Format("12/29/2022", "mm/dd/yy")

    SQLString = "INSERT INTO Table1 (TheDate) Values(" & ADate & ")"    '

    OpenSQLConnection ' open connectionrs.Open SQLString, Conn ' &
recordsetCloseSQLConnections

   Debug.Print "Date IN: " & CStr(ADate)
End Sub

Sub TestDateOutOfDB()
    Dim sSQLSting   As String

    OpenSQLConnection

   sSQLSting = "SELECT * From [Table1]"    ' get all data from Table1

    rs.Open sSQLSting, Conn

    'write the table to worksheetWorksheets("Sheet1").Range("A1").CopyFromRecordset rs

    'this will have the record just added to DB (first & only record)
    Debug.Print "Date OUT: " & Worksheets("Sheet1").Range("B1")

    CloseSQLConnections
End Sub

'Open Access DB connection
Sub OpenSQLConnection()
    sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DATABASE_LOC & DATABASE_NAME & ";Persist Security Info=False;"
    Conn.Open sconnect
End Sub

'Close any DB Connection
Sub CloseSQLConnections()
    On Error Resume Next
    rs.CloseSet rs = Nothing
    Conn.Close
    Set Conn = Nothing
End Sub

A: Consider the best practice of SQL parameterization which is supported with ADO library. This approach which is not limited to VBA or MS Access but any programming language connecting to any backend database allows for binding of values to a prepared SQL query to safely bind literal values and properly align data types:
...
Public cmd As ADODB.Command ' AVOID DECLARING OBJECT WITH New
...

Sub TestDateIntoDB()

    Dim SQLString As String
    Dim ADate As Date
    Const adDate = 7, adParamInput = 1

    'option 1
    ADate = CDate("12/29/2022")

    ' PREPARED STATEMENT WITH QMARK PLACEHOLDER
    SQLString = "INSERT INTO Table1 (TheDate) Values(?)"

    ' CONFIGURE ADO COMMAND
    Set cmd = New ADODB.Command
    With cmd
        .ActiveConnection = Conn
        .CommandText = SQLString
        .CommandType = adCmdText

        ' BIND VALUES
        .Parameters.Append .CreateParameter("paramDate", adDate, adParamInput, , ADate)
    End With

    ' EXECUTE ACTION QUERY
    cmd.Execute

    Set cmd = Nothing
    Debug.Print "Date IN: " & CStr(ADate)
End Sub

A: Force a format of the string expression for the date value:
Sub TestDateIntoDB()

    Dim SQLString As String
    Dim ADate     As Date

    ' Option 0.
    ADate = DateSerial(2022, 12, 29)

    SQLString = _
        "INSERT INTO Table1 (TheDate) " & _
        "VALUES (#" & Format(ADate, "yyyy\/mm\/dd") & "#)"

    ' <snip>

End Sub


Q: Example of using scoped try_shared_lock and upgrade lock in boost I have a thread pool that is using shared mutexes from the boost library.
While the answers to my other question were helpful,
Example of how to use boost upgradeable mutexes
What I have realised that what I actually need is not to block if a shared lock or upgrade lock could not be obtained.  Unfortunately, the boost docs are lacking any examples of those in use.
Could someone please point me to or provide an example of specifically the shared_lock being used in this way.
i.e.
boost:shared_mutex mutex;

void thread()
{
    // try to obtain a scoped shared lock
    // How do I do that?
}

void thread2()
{
   // try to obtain a scoped upgrade lock
   // and then a scoped unique lock
}

A: The answer seems to be that you can provide boost:try_to_lock as a parameter to several of these scoped locks.
e.g.
boost::shared_mutex mutex;

// The reader version
boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock);
if (lock){
  // We have obtained a shared lock
}

// Writer version
boost::upgrade_lock<boost::shared_mutex> write_lock(mutex, boost::try_to_lock);
if (write_lock){
  boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
  // exclusive access now obtained.
}

EDIT:
I also found by experimentation that upgrade_to_unique_lock will fail if you don't have the upgrade lock.  You can also do this:
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
if (unique_lock){
  // we are the only thread in here... safe to do stuff to our shared resource
}

// If you need to downgrade then you can also call
unique_lock.release();

// And if you want to release the upgrade lock as well (since only one thread can have upgraded status at a time)
write_lock.unlock().

Note: You have to call release followed by unlock or you'll get an locking exception thrown.
You can of course just let unique_lock and write_lock go out of scope thereby releasing the locks, although I've found that sometimes you want to release it earlier and you should spend minimal time in that state.


Q: PHP OOP: Parenting objects/functions? How is parenting functions in PHP done properly according to the following example?
Can I make sure that my array isn't overwritten and the previous values inside array lost, on each addArray call?
function arraybase() {
    $this->array = new ArrayObject();

    return $this;
}

function addArray($value) {
     parent::$this->arraybase();

    $this->array->append($value);
    return $this;

}

$this->addArray('1')->addArray('2')->addArray('3');

// outputs:
Array
(
    [0] => 3
)

A: In function addArray you keep recreating the array with the line:
parent::$this->arraybase();

Remove this line and call arraybase when you want to create it.

A: Well, first off, you don't need to parent::$this->arraybase().  Just do $this->arraybase().  In fact, I'm not even sure your way is even valid syntax.  But I digress.
As for your specific problem, you can either:

*

*Add a constructor (and remove the ->arraybase() call from addArray()):
public function __construct() {
    $this->array = new ArrayObject();
}

*Add an if check around the call to ->arraybase():
public function addArray($value) {
    if (!isset($this->array) || !is_object($this->array)) {
        $this->arraybase();
    }
    ...
}

Personally, I'd do #1.  It's going to be more reliable, faster, and more in keeping with OOP paradigms.
EDIT: Adding Constructor Info
So, if your base class has this constructor:
public function __construct($some, $vars) {
    ......
}

You would do this in your extending class:
public function __construct($some, $vars) {
    parent::__construct($some, $vars);
    $this->array = new ArrayObject();
}

NOTE:  Don't call parent::__construct() unless one of the parents has a __construct method...

A: Why do you want to set a wrapper around ArrayObject? If it's for adding the possibility of chaining method calls, then you'd better extend ArrayObject:
<?php
class MyArrayObject extends ArrayObject {

    public function append($value)
    {
        parent::append($value);
        return $this;
    }
}

$ao = new MyArrayObject();
$ao->append('a')->append('b')->append('c');
var_dump($ao->getArrayCopy());
/*
array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}
*/


Q: How to restart SoapUI's JVM? I am currently testing some changes to SoapUI JRE's settings on 'Preferences -> SSL' tab and to apply changes I close and then open again a SoapUI instance.
(Windows 10; SoapUI 5.3.0)
Is there a better (smarter) way of restarting SoapUI's JVM?
Preferably the one without closing the instance.

A: This comment answers the question:

You have to close the GUI instance and start it again.


Q: jQuery Templates {{each}} - How to address the underlying objects individually? I got the data collection:
var messages = {
    0: {who:'aaa', age: 33, id: 2},
    1: {who:'bbb', age: 44, id: 3},
    // ...
};

I got the template:

Now I am rendering it and put the result to #container:
$('#chat-message-template').tmpl(messages).appendTo('#container');

And It works fine, BUT how do I get a single element (single 'p' element) of the rendered template to be able to update it?
$('#oneOfParagraphsId').tmplItem(); OR $.tmplItem('#oneOfParagraphsId')
return all the collection of added paragraphs.
Yeah, I could walk through the collection and find the one I want, BUT, can I just somehow get a single item, not all the collection?
Even if I put a click event on each
 and in handler do something like $(this).tmplItem() it still gives me all the p's of the template!


Q: How does one get Properties using Reflection, while ignoring the inherited properties? To get the properties is not big deal, but I don´t want to get the properties inherited from another class. The bindingFlags option doesn´t have any option of this kind.
Is that possible ?
cheers

A: Use BindingFlags.DeclaredOnly with your Type.GetProperties call in order to specify to just get the properties from the specified type.
For example, to get all non-static properties on a type without looking up it's hierarchy, you could do:
var properties = theType.GetProperties(
                          BindingFlags.Public |
                          BindingFlags.NonPublic |
                          BindingFlags.Instance |
                          BindingFlags.DeclaredOnly);


Q: Validation for form on Button Click I have a form where I have many textboxes which are getting validated through Required field validator, But there is a captcha control also which is not getting validated. However I can validate it through javascript.
Here alert gets displayed when I click on 'OK' of alert message box.
But I want this message to be displayed on button click simultaneously with other validations.
Please help.
Thanks in Advance.

A: I think you want to display the "Please enter captcha text." as part of the ValidationSummary control.
To do this, you just need to let the server-side know the captcha text. Do this:

*

*Add another textbox, but keep it hidden with display:none:
<asp:textbox id="txtCaptcha" runat="server" style="display:none;">

*Modify your Javascript to copy the captcha value into the txtCaptcha textbox:
<script type="text/javascript">
   $(document).ready(function () {
       $('#' +'<%=btnSend.ClientID %>').on('click', function (e) {
           var captcha = $("input[name$=CaptchaControl1]").val();
           $('#' + '<%=txtCaptcha.ClientID %>').val(captcha);
       })
   });
</script>

*Create a RequiredValidator for txtCaptcha textbox:
<asp:RequiredFieldValidator ID="RequiredFieldValidatorForCaptcha" runat="server" ErrorMessage="Please enter captcha text." ControlToValidate="txtCaptcha" Display="None" ValidationGroup="VG"></asp:RequiredFieldValidator>


Q: Access denied exception using C# / UWP The execute() function is linked to a button press.
The first time it is pressed - everything runs the way it should/
The second time is is pressed (within the same execution of the app; if I close and re-open it works fine) - on the DeleteAsync line I get this exception:

An exception of type 'System.UnauthorizedAccessException' occurred in
  mscorlib.ni.dll but was not handled in user code
Additional information: Access is denied. (Exception from HRESULT:
  0x80070005 (E_ACCESSDENIED))

I think something is staying open longer than it should, hence the error. But I'm not sure what is causing it exactly. If anyone can see from the code below what could be happening I would be most grateful:
private async void execute(string url)
{
    StorageFolder filesFolder = null;
    StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

    if (await localFolder.TryGetItemAsync(DIRECTORY_NAME) != null)
    {
        filesFolder = await localFolder.GetFolderAsync(DIRECTORY_NAME);
        await filesFolder.DeleteAsync(StorageDeleteOption.PermanentDelete); // << THIS IS THE EXCEPTION LINE
    }

    if (await localFolder.TryGetItemAsync(DIRECTORY_NAME) == null)
    {
        await Task.Run(() => {
                repository.Clone(url, DIRECTORY_NAME);
            });
    }

    // This won't be called until task above finished running
    filesFolder = await localFolder.GetFolderAsync(DIRECTORY_NAME);
    IEnumerable<StorageFile> files = await filesFolder.GetFilesAsync();
    addFiles(files);
}

Clone function:
void Repository::Clone(Platform::String^ url, Platform::String^ path)
{
    OutputDebugString(L"Clone ");
    OutputDebugString(url->Data());
    OutputDebugString(L" into ");
    char temp[1024];
    GetLocalPath(path, temp, 1024);
    OutputDebugStringA(temp);
    OutputDebugString(L"\n");

    char urlt[1024];
    wcstombs(urlt, url->Data(), 1024);

    git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT;
    git_checkout_options checkout_opts = GIT_CHECKOUT_OPTIONS_INIT;

    // Set up options
    checkout_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
    checkout_opts.progress_cb = on_checkout_progress;
    clone_opts.checkout_opts = checkout_opts;
    clone_opts.fetch_opts.callbacks.sideband_progress = on_sideband_progress;
    clone_opts.fetch_opts.callbacks.transfer_progress = on_fetch_transfer_progress;
    clone_opts.fetch_opts.callbacks.credentials = on_credentials_required;
    clone_opts.fetch_opts.callbacks.payload = this->native;

    // Start the cloning
    report_error(git_clone(&repo, urlt, temp, &clone_opts));
}


Q: Qt: how to dynamic change the position of other widget? Let's say I have a GUI:

When I click the left button, I expect the object would locate at left just like:
layout.addWidget(object)
layout.addStretch()

How can I dynamically change the position?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Widget(QWidget):

    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.btnPos = QPushButton('left')
        self.btnPos.clicked.connect(self.btnClick)

        self.btnLayout = QHBoxLayout()

        self.btn = QPushButton('object')
        self.btnLayout.addStretch()
        self.btnLayout.addWidget(self.btn)
        self.btnLayout.addStretch()
        layout.addWidget(self.btnPos)
        layout.addLayout(self.btnLayout)

    def btnClick(self, check=False):
        print('click')
        pass

if __name__ == '__main__':

    app = QApplication(sys.argv)
    win = Widget()
    win.show()
    app.exec_()

A: In your btnClick function, you can set the Stretch parameter for each item in self.btnLayout. In this case you want to set the Stretch for the spacer on the left to 0 and the right spacer to 1:
def btnClick(self, check=False):
    print('click')
    # align button left
    self.btnLayout.setStretch(0,0)
    self.btnLayout.setStretch(1,1)
    self.btnLayout.setStretch(2,1)
    pass

For centering the button, set left and right spacers stretch to 1:
# button is centered
self.btnLayout.setStretch(0,1)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,1)

And to align button on right, set left spacer to 1, right spacer to zero:
# align button right
self.btnLayout.setStretch(0,1)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,0)


Q: Stretch an iframe with width and height of parent I've got a module in my Nextjs app that shows events that are currently being live-streamed. Within this module I've got an image preview with a play button that, when clicked, takes you to the live event.

What I'd like to do, however, is have this preview be the Vimeo video for the event, so it shows a video preview. That's easy enough to do, I can get the embed code for the Vimeo video from the events API, but I'm having trouble getting it to stretch into the full width and height of this rectangle. This is how it's looking right now:

Essentially, I can't figure out the correct styles to get it to stretch to this ratio, similarly to the image. I'm not concerned with what is being cut off or not, I just want to use the video as a background.
Here's what I've got so far (I'm using Nextjs and SASS modules):
The HTML in the component:
<div className={s.liveStream__player}>
  <Link href={`/events/${live.event_id}`} title="Play" className={s.liveStream__play}>
    <PlayButton />
  </Link>
  <iframe
    src={`https://player.vimeo.com/video/${vimeoId[1]}?background=1`}
    className={s.liveStream__preview}/>
</div>

And the SASS:
.liveStream {
  &__play {
    position: relative;
    z-index: 10;
  }

  &__player {
    display: flex;
    height: 100%;
    width: 100%;
    flex-grow: 1;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
  }

  &__preview {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    pointer-events: none;
  }
}

Is there an easy way to accomplish this and get the iframe to stretch to the full width and height of the parent?

A: You have missed one property to stretch iframe (height):
    .liveStream {
      &__play {
        position: relative;
        z-index: 10;
      }

      &__player {
        display: flex;
        height: 100%;
        width: 100%;
        flex-grow: 1;
        align-items: center;
        justify-content: center;
        position: relative;
        overflow: hidden;

        // make sure wrapper has necessary sizes
        // min-height: 100vh;
        // just for example purposes:
        height: 300px;
        width: 300px;
      }

      &__preview {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        pointer-events: none;

        // add height prop to stretch iframe to parent height
        height: 100%;
      }
    }

Also make sure wrapper has necessary sizes.
You can check codes in Codepen.io example.


Q: What's the difference between `raw.githubusercontent` and raw in the URL itself When I see URLs like https://github.com/hasura/graphql-engine/raw/stable/cli/get.sh, it contains "raw" in the URL itself.  However when you actually go to that URL, it redirects to "raw.githubusercontent", same as when you went to that file on GitHub and clicked "raw" on the UI.
I assume instinctively it's perhaps because of some legacy thing, perhaps GitHub is redirecting all previous URLs to the new "raw.githubusercontent" URL?
Or is there another reason, is there some difference or something specific that happens when it's specifically "raw" in the URL?
This is made even more confusing when I see there's a difference between new and old URLs on GitHub.  The above example is using https://github.com/<org>/<repo>/raw/<branch>/<dir>/<file>.  However when you use that on a new repository it looks like https://github.com/<org>/<repo>/blob/<branch>/<dir>/<file> and that then gets converted to raw.githubusercontent.  It seems like old repositories didn't use "tree" or "blob" at all in the URLs.
So what exactly is the most up to date and correct way to use it and if I wanted to retrieve the raw content of a file, which URL should I use?

A: The links you see on github.com are routes that are designed to be used on the website in web browsers.  The domain githubusercontent.com is designed to be separate to prevent any malicious user content from trying to steal cookies for github.com.
In general, if you're just using a web browser, click on the link or the button, and it will automatically redirect you to the right place.  Otherwise, you should use the REST API to either get the raw file contents directly or fetch the download URL.  Using the API will always give you the correct location and contents.
If you just want to use curl with the API and don't want to fetch the download_url key manually, you can run this: curl -H'Accept: application/vnd.github.v3.raw' https://api.github.com/repos/hasura/graphql-engine/contents/cli/get.sh.
Note also that none of these ways are designed for high-speed automated access; for that, you should host your repository on your own server with a CDN in front.


Q: css with background image without repeating the image I have a column (lets assume the width is 40px) and there I have some rows. The height of the rows depends on the length of text (if the text is long then there is a break line and therefore the height increases).
Now I want to display an icon in each row next to the text to show the user for example that he has already completed something in that tab. So I was trying to solve this by using only css. So if the user completes a tab then I change the css of that row. However, I'm not able to add to that row an image without that the image is being repeated.
I'm using this css code:
padding: 0 8px;
padding-top: 8px;
padding-right: 8px;
padding-bottom: 8px;
padding-left: 8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background-color: white;
background-image: url('images/checked.gif');
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

Does anyone know how to do that?

A: Instead of
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use
background-repeat: no-repeat;

A: Try this
padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;

This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need...

A: This is all you need:
background-repeat: no-repeat;

A: body {
    background: url(images/image_name.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here is a good solution to get your image to cover the full area of the web app
perfectly


Q: How do I use axios in vue3 I created a project in vue2 and now I'm migrating to vue3.
I had an api service which looked like this:
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import JwtService from "@/common/jwt.service";
import { API_URL } from "@/common/config";

const ApiService = {
    init() {
        Vue.use(VueAxios, axios);
        Vue.axios.defaults.baseURL = API_URL;
    },

    setHeader() {
        Vue.axios.defaults.headers.common[
            "Authorization"
        ] = `Bearer ${JwtService.getToken()}`;
    },

    query(resource, params) {
        return Vue.axios.get(resource, params).catch(error => {
            throw new Error(`[RWV] ApiService ${error}`);
        });
    },
    ...

How do I change this to vue3. I'm not supposed to use vue.axios anymore. In the documentation it says that should use app or this. But am I then supposed to export the app from main? I can't find any examples for this


Q: How to do Form Customization for Unhiding Fields I am new to Ax,I am doing an customization on form.When I click on show more fields I want to show three more fields on form which are hiding(FieldC,FieldD,FieldF).Please tell me how to achieve this Functionality.

A: You can check an example in form VendTable > Design > MainTab > TabPageDetails > Tab > TabGeneral > HideShowGroup.
It contains two elements: a combobox (HideShowComboBox) and a button (HideShowButton).
By default, the button has following properties:

*

*AutoDeclaration = Yes

*Text = Show more fields

*HelpText = Show/hide fields.

*SaveRecord = No

*Border = None

*BackgroundColor = Dyn Background white

*ImageLocation = EmbeddedResource

*NormalImage = 7886

*ButtonDisplay = Text & Image left

The button also has method clicked responsible for hiding/showing the fields that need to be hidden/displayed and for changing its own look (Text, HelpText, NormalImage = 7882, etc.)
Please note that this logic is managed in class DirPartyFormHandler - you can set breakpoints there and debug the process to understand this functionality better.


Q: masm x86 Assembly Is it possible to check if an address is allocated or not? In masm, you can statically allocate memory using the .DATA, and .DATA? directives, and that is great, but what if I needed to allocate a block of memory dynamically? Lets say that I wanted to create a DWORD with the value 10 in dynamically allocated memory. One theory is that I could run through a range of addresses, check if they are allocated or not, and if not then allocate the address and use it to store the DWORD in. But there is only one problem; I do not know how to check if an address is allocated or not. :(
Make_Dword PROC
PUSH EBP
MOV EBP, ESP
PUSH ESI
PUSH EDI
PUSH EBX
MOV EBX, [EBP - 08h] ;EBP - 08h is the dword value
;Iterate through memory addresses and check if one is unallocated, if so
; use it to store the dword value in, finally return the newly allocated
; address of the dword in memory.
MOV EAX, [the newly allocated address of the dword]
POP EBX
POP EDI
POP ESI
MOV ESP, EBP
POP EBP
Make_Dword ENDP

PUSH DWORD PTR 0Ah
CALL Make_Dword

A: I am editing my response to see if maybe I can clarify.  If you have a data directive, can you just allocate a static size block of memory with it? e.g.
.DATA
    poolOfDwords DWORD 1000
Then, just initialize them to values that you know you cannot get (-1 maybe?).  Then, when you need to "allocate" a DWORD, you can just iterate through the list for the first entry that is -1 (unallocated) and use it.  You can return the offset to that location if you need to use it.
Hopefully that helps clarify my idea.


Q: jQuery Tools overlay draggable I have an overlay with the apple effect from jQuery Tools. I want to make it so the overlay is draggable, but when I use $( ".overlay" ).draggable(); the background image does not drag with it. I tried appendTo but it destroyed the apple effect. Also the image for the overlay is rendering outside of the .overlay div.
here is a jsfiddle http://jsfiddle.net/ZqNgy/
I am kind of new to jQuery and javascript and would really appreciate any help.
Thanks

A: if you do not need 'apple'effect, you can drag background image.
just effect set to 'default'.
and you may be need to change overlay style.
example(".overlay").overlay({
    top: 50,
    left: 50,
    closeOnClick: false,
    load: false,
    effect: 'default',
    speed: 1000,
    oneInstance: false,
    fixed: false,
});

.overlay {
    display:none;
    background-image:url(white.png);
    background-size:cover;
    width:160px;
    padding:20px;
}


Q: OMNet ++, SUMO and Veins with or without INET I just successfully accomplished the Veins (with OMNet++ and SUMO) tutorial (http://veins.car2x.org/tutorial/), but noticed that it did not use INET.  Other YouTube tutorials on Veins use INET with Veins, almost as if it is a given.  What is the benefit of incorporating INET into a Veins simulation?  What do you gain?
My experience is limited to the tutorial, and an expectation of eventually learning/incorporating Plexe.


Q: D3 data processing choice I have a question about which kind of data I should send to client for visualization:
I have an web that needs to display both processed data and database-like data(Processed one is from database-like)
So now I have 2 choices:

*

*Send to client Database-like data and process the logic there to get the processed data

*Send both processed data and database-like data. Redundant but ease of use

I would like to hear about your opinions n regard of these 2 approaches. And they are also in context of using d3


Q: How to print value of a hashmap? When I execute the below code:
map.forEach((key, value) -> System.out.println(key + ":" + value));

I get 15234:[com.org.myprj.Dashboard@18a6be14] as sysout.
How to I get object value in hashmap? Here object is a row inserted in arraylist.

A: implement overridden toString method in object
example
class Dashboard{
    private double re, im;

    public Dashboard(double re, double im) {
        this.re = re;
        this.im = im;
    }

    @Override
    public String toString() {
        return String.format(re + " + i" + im);
    }
}


Q: How to Add External CSS in Laravel 5.4 I am new in Laravel...
web.php
<?php

Route::get('/', function () {
    return view('method1.home');
});

home.blade.php
@extends('dashboard')

dashboard.blade.php
<!DOCTYPE html>
<html class="no-js">
<head>
    @include('includes.head')
</head>

<body>
do something...
</body>

head.blade.php
<link rel="stylesheet" href="{{ URL::asset('front_view/css/main.css') }}">
<link rel="stylesheet" href="{{ URL::asset('front_view/css/shop.css') }}">
<script src="{{ asset('front_view/js/vendor/modernizr-2.6.2.min.js') }}"></script>

The path and folder name is correct.
But the CSS is not working.

A: open or create file if not exist constants.php inside config folder and then add this line inside that file
define('SITE_PATH', 'http://localhost:8000/'); // write here you site url

and then use like this in view
<link rel="stylesheet" type="text/css" href="<?php echo SITE_PATH; ?>css/custom.css">

it will search for custom.css inside public/css folder so create css folder inside public folder and the create your custom.css or create directly inside you public folder


Q: Ruby find where before updated_at I am trying to search for results where the updated_at on one result is after the created at of another this is my code in a short and sweet version
i am getting a syntax error
PG::SyntaxError: ERROR:  syntax error at or near "13"
LINE 1: ...ERE ((group_id = 14 and created_at >=  2016-08-04 13:39:35 U...
                                                             ^
: SELECT "chats".* FROM "chats" WHERE ((group_id = 14 and created_at >=  2016-08-04 13:39:35 UTC))  ORDER BY created_at DESC

but i do not understand why is it something to do with the time?
@grouparchived = @groupread.updated_at

filter1 = "(group_id = "+@arandomthing.to_s + " and created_at >= "+@grouparchived.to_s+")"

@chats1 = Chat.where(@filter1).order('created_at DESC')

A: Chat.where(group_id: @arandomthing).where('created_at >= ?', @groupread.updated_at).order('created_at DESC')

Concating strings like you're doing is a recipe for disaster, much better to use the tools Rails gives you.


Q: Dicom data training failed by pytorch I've got a problem about training the Pytorch models. I'm trying to train my Pytorch model using dicom data and nifti GT However, the size of the weight file is ridiculously small because model training is not performed normally.
I used network model Unet++
I think there is a problem with the data loader. But I can't fixe it...
I'd appreciate it if you could help me.
Raw image file format is dicom and GT image format is nifti
in my dataloder
def __getitem__(self, index):
    image_path = self.image_paths[index]
    image_GT_path = image_path[:8]+'_'+image_path[8:12]+'.nii'
    GT_path = self.GT_paths + image_GT_path

    ds = dcmread(self.root+image_path)
    image = ds.pixel_array.astype(np.float32)
    image = torch.from_numpy(image.transpose(0,1)/255)
    image = image.unsqueeze(0)

    GT = nib.load(GT_path)
    GT = GT.get_fdata(dtype=np.float32)
    print(GT.shape)
    GT = torch.from_numpy(GT.transpose(0,1))
    GT = GT.unsqueeze(0)

    return image, GT, image_path

and Train Code is
for epoch in range(self.num_epochs):

            self.unet.train(True)
            epoch_loss = 0
            for i, (images, GT,empty) in enumerate(tqdm(self.train_loader)):
                # GT : Ground Truth

                images = images.to(self.device)
                GT = GT.to(self.device)

                # SR : Segmentation Result
                SR = self.unet(images)
                SR_probs = torch.sigmoid(SR)

                SR_flat = SR_probs.view(SR_probs.size(0),-1)

                GT_flat = GT.view(GT.size(0),-1)
                loss =self.criterion(SR_flat,GT_flat)

                # self.criterion=DiceLoss() #BCE not use
                # loss = self.criterion(GT,SR_probs)
                epoch_loss += loss.item()
                train_losses.append(loss.item())
                # Backprop + optimize
                self.reset_grad()
                loss.backward()
                self.optimizer.step()

A: Depending on what modality your images are, this might possibly be due to not converting the image data into the correct, clinically relevent, machine/vendor independent, units prior to any ML training 0-1 normalization.
Typically in dicom files, the actual raw data values aren't that - they need processing...
For instance, if you're trying to train on CT data, then the units you should be trying to train your model on are Houndsfield's (HU) numbers.  (Do a google on that, CT and dicom to get some background).
However raw CT dicom data could be little or big endian, likely needs a slope/intercept correction applied and also could need to have look up tables applied to convert it into HU numbers.  ...ie can get complicated and messy.  (again do a bit of googling ...you at least should have a bit of background on this if you're trying to do anything with medical image formats).
I'm not sure how to process nifti data, however luckily for dicom files using pydicom this conversion can be done for you by the library, using (typically) a call to pydicom.pixel_data_handlers.util.apply_modality_lut:

dcm = pydicom.dcmread(my_ct_dicom_file)
data_in_HU = pydicom.pixel_data_handlers.util.apply_voi_lut(
    dcm.pixel_array,
    dcm
)


Q: PHP: How to get timezone value (ex: Eastern Standard Time) from timezone name (ex: America/New_York)? Is there a PHP function anywhere which converts between the timezone name (such as those found here: http://php.net/manual/en/timezones.america.php) and the "value" such as Eastern Standard Time, or Pacific Daylight Time?
Not looking to convert between zones, just get the EST, PDT, etc. names given the America/New_York (or other) name.  The only similar question I found is for a different language.

A: If you  you install the PHP Internationalization Package, you can do the following:
IntlTimeZone::createTimeZone('America/New_York')->getDisplayName()

This will return the CLDR English standard-long form by default, which is "Eastern Standard Time" in this case.  You can find the other options available here.  For example:
IntlTimeZone::createTimeZone('Europe/Paris')->getDisplayName(true, IntlTimeZone::DISPLAY_LONG, 'fr_FR')

The above will return "heure avancée d’Europe centrale" which is French for Central European Summer Time.
Be careful to pass the first parameter as true if DST is in effect for the date and time in question, or false otherwise.  This is illustrated by the following technique:
$tz = 'America/New_York';
$dt = new DateTime('2016-01-01 00:00:00', new DateTimeZone($tz));
$dst = $dt->format('I');
$text = IntlTimeZone::createTimeZone($tz)->getDisplayName($dst);
echo($text); // "Eastern Standard Time"

Working PHP Fiddle Here
Please note that these strings are intended for display to an end user.  If your intent is to use them for some programmatically purpose, such as calling into another API, then they are not appropriate - even if the English versions of some of the strings happen to align.  For example, if you are sending the time zone to a Windows or .NET API, or to a Ruby on Rails API, these strings will not work.

A: If you know the value from your list at (http://php.net/manual/en/timezones.america.php) you can do something like.
<?php

$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone('America/New_York'));
echo $dateTime->format('T');

?>


Q: Unity: How to represent grid map data in ECS I have been trying to work with Unity's pure ECS approach to make a basic nxn grid of tiles.
Before using ECS I would just use a 2d array Tiles[,] grid where I can simply index (x,y) to find the tile I want.
Now moving into ECS, I want to create an entity for each tile using an IComponentData struct like so:
public struct Tile : IComponentData
{
    public int xIndex;
    public int yIndex;

    public int isValid;
}

Somewhere during the start of my game I create the tile entities
    for (int i = 0; i < tilesInMap; i++)
    {
        Entity tileEntity = entityManager.CreateEntity(tileArchetype);

        int xIndex = i % terrainSize;
        int yIndex = i / terrainSize;

        entityManager.SetComponentData(tileEntity, new Position { Value = new float3(xIndex , 0, yIndex) });

        Tile newTile;
        newTile.xIndex = xIndex;
        newTIle.yIndex = yIndex;
        newTile.isValid = 1;

        entityManager.SetComponentData(tileEntity, newTile);
    }

Now somewhere else in my code I have a ComponentSystem that pulls in the tiles using a group struct
public struct TileGroup
{
    public readonly int Length;
    public EntityArray entity;
    public ComponentDataArray<Tile> tile;
}

[Inject] TileGroup m_tileGroup;

As far as I'm aware, as long as I don't change the archetype of any of those entities in the TileGroup (for instance by calling AddComponent or RemoveComponent), the ordering of that injected array will be preserved (I'm not even sure of that!)
So say in my OnUpdate method I want to "get the tile at grid coordinate (23, 43)". I can calculate this (assuming a 1d array of tiles with the order preserved) by
int arrayIndex = yIndex * tilesPerMapWidth + xIndex;

But this only works as long as the injected array order of tiles is preserved which I doubt it will be eventually.
So a few questions:
1. Should I ever rely on the order of an injected array for behaviour logic?
2. Are there any better methods in achieving what I want using ECS?

A: From the Unity forums, "Order of Entities":

*

*ComponentDataArray<> / ComponentGroup makes zero gurantees on the actual ordering of your entities except for that its deterministic. But generally the indices are not stable. (E.g. Adding a component to an entity, will change the index in ComponentDataArray of that entity and likely of another one) The only stable id is the "Entity" ID.

To answer your questions:

So a few questions: 1. Should I ever rely on the order of an injected array for behaviour logic?

Based on "...makes zero guarantees on the actual ordering of your entities..." I would say no.

*Are there any better methods in achieving what I want using ECS?

You don't need arrayIndex to access entities in your tile group. You can iterate through the entities and access x and y for each to perform the required behavior. Depending on your actual functionality you may want to use the job system as well.
for (int i = 0; i < m_tileGroup.Length; i++) {
    int x = m_tileGroup.tile[i].xIndex;
    int y = m_tileGroup.tile[i].yIndex;
    // do something with x and y
}


Q: Add T-SQL in maintenance plan in SQL Server How can I set a T-SQL statement as a part of a maintenance plan in SQL Server?
Since I can see options of backup etc but not the possibility of adding T-SQL

A: I am not sure why you are looking to set up a maintenance plan.But, the alternate approach would be to set up a SQL server agent job to execute your T-SQL statements (which can be put together as procedures) and schedule it accordingly.
At the same time, you can execute SQL jobs through maintenance plans as well. This page will also help you : https://learn.microsoft.com/en-us/sql/relational-databases/maintenance-plans/use-the-maintenance-plan-wizard?view=sql-server-2017

A: First I connected to my SQL server using SQL Server Management Studio.
I went to the node Management, right-clicked the subnode Maintenance Plans and created a new maintenance plan called Test. My maintenance plan automatically got a subplan called Subplan_1. I just kept it and saved the maintenance plan.
Next, I went to the node SQL Server Agent, opened the subnode Jobs and double-clicked node Test.Subplan_1. It had a job step called Subplan_1. Double-clicking that job step opened the job step's properties. There I could choose the type Transact-SQL script (T-SQL) and enter my SQL code.
I did not encounter any problems. I used SQL Server 2017, but I am pretty sure it works about the same way in earlier versions of SQL Server...
Edit:
Like sabhari karthik commented and answered, it is very well possible to just create a new job with SQL Server Agent and schedule that job. So perhaps you do not need a maintenance plan at all. But if you do use maintenance plans (or are required to use and/or edit existing maintenance plans), it might be just the case that a maintenance plan's subplan automatically gets a related SQL Server Agent job. But I am not sure. I have never configured and used any maintenance plans before. I'm just a software developer, not a DBA.
Edit 2:
I see in the Maintenance Plan Wizard that there is an option to execute a SQL Server Agent Job as a maintenance task as well. But it seems you need to create that SQL Server Agent Job first.


Q: position:sticky does not leave parent How can make an element sticky, so it stays at the top of the viewport? I want the element to remain sticky even if it leaves it's container.
I tried this
HTML

i want to be sticky, even when I'm outside my parent.

CSS
.child-sticky {
  position:sticky;
  top:20px;
}

.page {
  height: 3000px;
}

Here's a pen to illustrate the problem. Scroll down to see what I mean.
https://codepen.io/pwkip/pen/OxeMao

A: This is how position: sticky is intended to work. If you need it to also work outside the parent than you have to change the HTML structure.
See also the official definition: https://www.w3.org/TR/css-position-3/#sticky-pos

A: There is a little trick you can try.
In some cases it will break your layout and in others it won't. In my case, I have a header with some buttons but when I scroll down, I want to have access to some action buttons which are inside that one-line header. The only change is to set the display property of your parent to be inline.
.parent {
  display: inline;
}

A: Sticky works that way, it will remain sticky relative to its parent. You need to use fixed.
Check this codepen

A: Already 7 months ago, but I found a CSS only solution if the element you want to be sticky is the last one of its parent, its very simple: Just give the parent element position: sticky; and also give it top: -xx;, depending on the height of the elements before the last one.

#parent {
  position: -webkit-sticky;
  position: sticky;
  top: -3em;
}

#some_content {
  height: 3em;
}

#sticky {
  background-color: red;
}

#space {
  height: 200vh;
}

Some Content

Sticky div

Scroll here

A: Based on https://stackoverflow.com/a/46913147/2603230 and https://stackoverflow.com/a/37797978/2603230's code, here's an combined solution that does not require hard-coded height.

$(document).ready(function() {
    // Get the current top location of the nav bar.
    var stickyNavTop = $('nav').offset().top;

    // Set the header's height to its current height in CSS
    // If we don't do this, the content will jump suddenly when passing through stickyNavTop.
    $('header').height($('header').height());

    $(window).scroll(function(){
        if ($(window).scrollTop() >= stickyNavTop) {
            $('nav').addClass('fixed-header');
        } else {
            $('nav').removeClass('fixed-header');
        }
    });
});
body { margin: 0px; padding: 0px; }

nav {
    width: 100%;
    background-color: red;
}

.fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 10;
}

    Hello World!

    A nav bar here!

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: Like mentioned, sticky works that way. However there is a CSS hack that you can play around with.
Disclaimer
This is an ugly hack and will probably create a lot of problems with the following content. So I would not recommend it for most usecases. Having that said...
Negative margin hack
There is a hack you could play around with including negative margin. If you extend the height of the container and then give it some negative bottom margin, it could at least "visually leave" the container.
I altered your code and created a JSFiddle for demonstration.
HTML

...
...
...
...
...

i want to be sticky, even when I'm outside my parent.

...
...
...
...
...

...
...
...
...
...

CSS
.child-sticky {
  height: 200px;
  background: #333366;
  position:sticky;
  top:20px;
  color:#ffffff;
}

.parent {
  height: 1250px;
  background: #555599;
  margin-bottom: -500px;
}
.following-content {
  background: red;
  height:500px;
}

.child {
  background-color: #8888bb;
}

.page {
  height: 3000px;
  background: #999999;
  width: 500px;
  margin: 0 auto;
}

div {
  padding: 20px;
}

https://jsfiddle.net/74pkgd9h/


Q: Draw Hexagonal Shapes using jQuery Is it possible to draw hexagonal shapes using jQuery, HTML and CSS?
If yes how can we do that?

A: jQuery doesn't draw things. You could do this using CSS + HTML only. Here is a cool tutorial showing one way it could be done:
http://jtauber.github.com/articles/css-hexagon.html
Note: HTML / CSS may not be ideal for all situations. It might be better to look at using SVG instead.

A: My best recommendation would to be use either SVG or canvas.
One example of a good SVG library is raphaeljs, check it out:
http://raphaeljs.com/
http://raphaeljs.com/animation.html
For canvas its quite simple to make shapes
https://developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Drawing_shapes


Q: how to Compile Consumer-Producer-ApI in Linux I want to ./waf consumer-producer-api but it show some error CXXFLAGS error
and onChanged() error.
 please help me...
I use linux-mint and set up complete ndn-cxx and openssl
 $./waf configure
 Setting top to                           : /home/ndn/ntorrent/Consumer-
 Producer-API
 Setting out to                           : /home/ndn/ntorrent/Consumer-
 Producer-API/build
 Checking for 'gcc' (C compiler)          : /usr/bin/gcc
 Checking for 'g++' (C++ compiler)        : /usr/bin/g++
 Checking for program 'doxygen'           : /usr/bin/doxygen
 Checking for program 'tar'               : /bin/tar
 Checking for program 'sphinx-build'      : /usr/bin/sphinx-build
 **Checking supported CXXFLAGS              : -std=c++0x -std=c++11 -Wall -
 Wno-long-long -Wno-nested-anon-types -O2 -g**
 Checking supported LINKFLAGS             :
 Checking for program 'pkg-config'        : /usr/bin/pkg-config
 Checking for 'libndn-cxx'                : yes
 Checking boost includes                  : 1.58.0
 Checking boost libs                      : ok
 Checking for boost linkage               : ok
'configure' finished successfully (4.485s)

$./waf
Waf: Entering directory `/home/ndn/ntorrent/build'
[ 1/12] Compiling src/file-manifest.cpp
../src/file-manifest.cpp: In member function ‘void
ndn::ntorrent::FileManifest::encodeContent()’:
../src/file-manifest.cpp:240:13: error: ‘onChanged’ was not declared in this
scope
   onChanged();
             ^
At global scope:
cc1plus: warning: unrecognized command line option ‘-Wno-nested-anon-types’


Q: React: Absolute Position In Child Components Introduction: I have a React component structure that looks like this.
-- ParentComponent.tsx --

Some Content Here

<ChildComponent/>

    Some Other Content -- should be covered when the absolutely positioned content
    inside of ChildComponent renders on the screen!

-- ChildComponent.tsx --

/* at the top of my render method */

const [booleanCondition, setBooleanCondition] = useState(false);
const toggleBooleanCondition = () => { setBooleanCondition(!booleanCondition); };

...
/* much later, in the return value of render method */

    Some Content Here, capable of calling toggleBooleanCondition()
    { booleanCondition ?

            Some Content Here. Should definitely cover the bottom
 in parent!

      : <></>

The toggle logic definitely works. The problem is, I would expect the div in ChildComponent.tsx to sit cleanly on top of the div in ParentComponent.tsx, which has a smaller z-index. However, this is not the case: the screenshot below shows that elements are being rendered in a random sort of order.

I feel like the issue may be due to different components assigning different meanings to their own z-indexes. No matter how I played with position: relative, and z-index: , nothing seemed to change. Does anybody know of a reliable solution to this problem??

A: My CSS background wasn't white. Lol.


Q: nstimer count down not working as expected I am using nstimer to show count down timer in a label. I am able to start the timer and show the count down in the label but the timer jumps to next second rather than showing every second. If the count down timer is set to 10 sec then it shows only 9,7,5,3,1 in the count down timer label.
Below is my code.
 NSTimer *tktTimer;
 int secondsLeft;

- (void)startTimer {
   secondsLeft = 10;
        tktTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];

    if (--secondsLeft == 0) {
        [tktTimer invalidate];
        countDownlabel.text = @"Completed";
    }

}

Any help will be really appreciated.

A: --secondsLeft updates the variable. To check if the next decrement will be 0, use if (secondsLeft - 1 == 0)
Each tick is decrementing the variable twice.
Additionally, this will trigger the "Completed" text on 1, not 0. Below is a better way to handle this:
-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    if (secondsLeft == 0) {
        [tktTimer invalidate];
        countDownlabel.text = @"Completed";
        return;
    }
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}

A: //sweet and simple way to perform timer with easy and understandable code
DECLARE
 int seconds;
 NSTimer *timer;

//in viewDidLoad method
seconds=12;
     timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GameOver) userInfo:nil repeats:YES ];

-(void)GameOver
{
     seconds-=1;
     lblUpTimer.text=[NSString stringWithFormat:@"%d",seconds];//shows counter in label

if(seconds==0)
[timer invalidate];
}

THANK YOU


Q: Discord.py bot events formatted exactly the same yet one runs and one won't run I've recently been experimenting with discord bots and the discord API, but I have come to a problem with bot events.  When made two events using the discord.py module, only one would work while the other one did not, yet both were formatted exactly the same.  Why is this happening and how can I fix this problem?  Here is my code:
@bot.event
async def on_message(message):
    message = await bot.wait_for_message(author=message.author)
    if message.content.startswith('!genlifetime password'):
        global amount
        amount = message.content[len('!genlifetime password'):].strip()
        num = int(amount)
        chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
        for x in range(0, num):
            authkey1 = ''
            authkey2 = ''
            authkey3 = ''
            authkey4 = ''
            for i in range(0,4):
                authkey1 = authkey1 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey2 = authkey2 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey3 = authkey3 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey4 = authkey4 + chars[random.randrange(0,35)]
            authkey = authkey1 + '-' + authkey2 + '-' + authkey3 + '-' + authkey4
            print(authkey)
            with open(keyfile, 'a') as f:
                f.write(authkey + ' LIFETIME \n')

@bot.event
async def authorize(message):
    message = await bot.wait_for_message(author=message.author)
    if message.content.startswith('!activate'):
        global key
        key = message.content[len('!activate'):].strip()
        print(key)

bot.run("NTM3Mzk1NDQzNzAxNjQ1MzEz.DykoDA.x5PrEwxZ0hlY2TeCtKVlg1QsbfQ")

When I run my bot and type in !genlifetime password 10, the bot will generate 10 keys like it is supposed to, print them in the shell, and put them in keys.txt.  However, the authorize event does not work at all.  If I type in !authorize key nothing happens in the shell.  The key is not printed at all.  I even tried putting a print before the message = await bot.wait_for_message(author=message.author) but that print would not print out either.  Both events are formatted the same way, so why does one work while the other does not?

A: I am thinking that the code should maybe look like this:
@bot.event
async def on_message(message):
    message = await bot.wait_for_message(author=message.author)
    if message.content.startswith('!activate'):
        global key
        key = message.content[len('!activate'):].strip()
        print(key)
    if message.content.startswith('!genlifetime password'):
        global amount
        amount = message.content[len('!genlifetime password'):].strip()
        num = int(amount)
        chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
        for x in range(0, num):
            authkey1 = ''
            authkey2 = ''
            authkey3 = ''
            authkey4 = ''
            for i in range(0,4):
                authkey1 = authkey1 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey2 = authkey2 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey3 = authkey3 + chars[random.randrange(0,35)]
            for i in range(0,4):
                authkey4 = authkey4 + chars[random.randrange(0,35)]
            authkey = authkey1 + '-' + authkey2 + '-' + authkey3 + '-' + authkey4
            print(authkey)
            with open(keyfile, 'a') as f:
                f.write(authkey + ' LIFETIME \n')

Although, I haven't tested this.

A: The wait_for_message calls seem superfluous: according to the docs, the message argument passed into the callbacks is the message you want. If you were to remove the calls to wait_for_message and just use the message passed in directly, it would probably work as expected.


Q: New Relic Plugin with Custom Page Since New Relic is a kind of “heart” of the operation of our IT Infrastructure, I would like to add static pages that has links to our Knowledge Base system, javascript based live debugging, etc.
I imagined something like to a Plugin that, instead of having graphs, it is HTML section to be show inside New Relic.
Is it possible?
Regards,
Vitor

A: Unfortunately, it is not possible to do this at this time with the New Relic User Interface. We always appreciate insight into the needs of our customers so we have submitted a feature request on your behalf and should such functionality become available you will be notified.
Thanks!
Dana
New Relic - Tech Support

A: If you only need it to support users within your company, a firefox/chrome extension that injects the relevant content into the page could work.


Q: Making a dynamic grid with jquery I'm trying to create a dynamic grid using jquery where it will eventually change with user input (i.e. 16x16, 32x32, etc). My logic is to create 16 rows and then 16 squares within each row, but I'm having trouble getting the squares to append the correct amount.
$(document).ready(function () {
    for (var i = 0; i < 16; i++) {
        $('.grid').append("

");
      //$('.row').width(($('.square').width().val() * i);
      //for (var i = 0; i < 16; i++) {
           $('.row').append("

");
    // }
    }
});

Here is a link to what it looks like: https://lettda.github.io/EtchAsketch/

A: .row selects all the elements which have the class row which means that you're not appending the .square divs to only the last created row, you're appending them to all the previously created ones as well.
To prevent that, you can do something like this.
for (var i = 0; i < 16; i++) {
    var row = $("

");
    for (var j = 0; j < 16; j++) {
        var square = $("

");
        row.append(square);
    }
    $('.grid').append(row);
}

OR
for (var i = 0; i < 16; i++) {
  $('.grid').append("

");
  for (var j = 0; j < 16; j++) {
      $('#row'+i).append("

");
  }
}

A: Moving your inner for loop outside of the outer for loop should create the proper amount of squares, as such:
for (var i = 0; i < 16; i++) {
    $('.grid').append("

"); // Each grid gets 16 rows
}

for (var i = 0; i < 16; i++) {
    $('.row').append("

"); // Each row gets 16 squares
}

Explicitly setting the width of the row is not necessary, as it will automatically be 16 times the width of your square plus any padding/margin you add. Note that all your squares would need display: inline-block; in the CSS to ensure that they are side by side. Also, the rows would wrap if there are too many squares in each row or the squares are too wide.


Q: Not sure how to add image variance to php/sql population of HTML table Situation
I am currently populating an HTML table using PHP, which is working just fine using this code:
<?php
while ($row = mysqli_fetch_array($result)) {

    $lineID             = $row['lineID'];
    $ediShipDate        = $row['ediShipDate'];
    $resolution         = $row['resolution'];
    $resolutionComments = $row['resolutionComments'];

?>

Issue
I am trying to make it so with each individual line, if ediShipDate equals one thing, I place one image there (instead of the text inside that variable), and if it equals another thing, to place a different image.  I'm trying using this code in the middle here:

          <?= $cost?>
          <value="<?= $cost?>">

          <?php
            if ($row['ediShipDate'] = "Before Debit Exp"){
              print("");
              print("one") ;
            }
            else if  ($row['ediShipDate'] = "AFTER DEBIT EXP!"){
              print("");
              print("two") ;
            }
            else {
            print $row['ediShipDate'] ;
            print("three") ;
            }
          ?>
          <value="<?= $ediShipDate ?>">

              <?= $cost?>
              <value="<?= $cost?>">

With my test data, I have 4 rows.  The first three's value is "Before Debit Exp" while the fourth's value is "AFTER DEBIT EXP!", however, in the debug code I have here print("one") etc..., all four rows are evaluating to the first statement, regardless of their value, and printing out check-yes.png  I've tried changing all of them to have the actual value of "AFTER DEBIT EXP!" to no avail.
Why is this?  There is nothing in the logs or the console.

A: In your IF statement you're assigning the value not comparing.
= vs == or ===
You need to switch them to == at the very least, but it would be better to use ===.
          <?php
            if ($row['ediShipDate'] === "Before Debit Exp"){
              print("");
              print("one") ;
            }
            else if  ($row['ediShipDate'] === "AFTER DEBIT EXP!"){
              print("");
              print("two") ;
            }
            else {
            print $row['ediShipDate'] ;
            print("three") ;
            }
          ?>
          <value="<?= $ediShipDate ?>">


Q: Disable CheckedListBox Autoscroll on item checked? Situation: I have a CheckedListBox with a horizontal scroll bar enabled with CheckOnClick set to true. The size of the CheckListBox is such that two column of items is shown.
Issue: When the user clicks on an item in the second column to check it on or off, the horizontal scroll bar automatically shifts the entire row such that it's in the first column.
Question: How do I disable the CheckedListBox from automatically shifting? I took a look at the properties but I can't seem to find one that would disable it, does the answer lie in inheriting the CheckedListBox and overriding methods?
Thanks for the help!

A: if you always want to go back to the top-left item (scroll back all the way to the left), just select item[0] programmatically on SelectedIndexChanged... this will still fire off the "check" and actually DO the "check on check off", but will return to the first item in the list...
like this:
private void lst_Servers_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lst_Servers.SelectedIndex = 0;
    }

A: The problem was: when you size your table you have to do it very carefully, ensure that the rightmost column is entirely within the visible area, otherwise if you edit a cell in that column the table would scroll left...


Q: Comparing columns in a list I have done splitting on the csv file(link given below) and my data output is given below. I need little help in comparing country column and return only the movie names that are made in the USA only. How do I do that?
data = open("movie_metadata.csv", "r").read().split("\\n")
movie_data = [i.split(",") for i in data]
print(movie_data[1:4])

output:
[['movie_title','director_name','color','duration','actor_1_name','language',
  'country','title_year'],
['Avatar','James Cameron','Color','178','CCH Pounder','English','USA',
 '2009'],
["Pirates of the Caribbean: At World's End",'Gore Verbinski','Color',
 '169','Johnny Depp','English','USA','2007'],
['Spectre','Sam Mendes','Color','148','Christoph Waltz','English','UK',
 '2015']]

CSV File

A: You want to filter the list based on the country column.
us_movies = [movie for movie in movies if movie[6] == 'USA']

You can also transform the line into just the title if you like.
us_movie_titles = [movie[0] for movie in movies if movie[6] == 'USA']

If you want a corresponding list of match predicate results, this will work:
is_match = [movie[6] == 'USA' for movie in movies]

Note, the size of the first two lists may be smaller than the original list, but is_match will have the same size and ordering as your original list.
To add the booleans to your full dataset:
movies_with_usa = [m[0] + [m[1]] for m in zip(movies, is_match)]

But what you really have is named data, so it's probably more appropriate in a dictionary or object. Also, if you're reading a csv file, a csv reader is part of the standard library. So for something a little more robust
import csv

def read_data(filename):
    with open(filename) as f:
        reader = csv.DictReader(f)
        return [row for row in reader]

def match(record, field, value):
    return record[field] == value

data = read_data("movie_metadata.csv")
us_movies = [record for record in data if match(record, 'country', 'USA')]

A: You want to use a pandas dataframe and then you can filter very easily based on the columns.
import pandas as pd
df = pd.DataFrame(movie_data[1:],columns = movie_data[0])
                                movie_title   director_name  color duration     actor_1_name language country title_year
0                                    Avatar   James Cameron  Color      178      CCH Pounder  English     USA       2009
1  Pirates of the Caribbean: At World\'s End  Gore Verbinski  Color      169      Johnny Depp  English     USA       2007
2                                   Spectre      Sam Mendes  Color      148  Christoph Waltz  English      UK       2015

df[df.country == "USA"]
                                movie_title   director_name  color duration actor_1_name language country title_year
0                                    Avatar   James Cameron  Color      178  CCH Pounder  English     USA       2009
1  Pirates of the Caribbean: At World\'s End  Gore Verbinski  Color      169  Johnny Depp  English     USA       2007

A: Just iterate over all movies and compare the 7th column:
 made_usa = []

 for l in movie_data:
        if l[6] == 'USA':
          made_usa.append(l)

 print (made_usa)

To add only the movie name, it is just to do this:
     made_usa = []

     for l in movie_data:
            if l[6] == 'USA':
              made_usa.append(l[0])

      print (made_usa)

To save if there is a match or not, you can use a dictionary like this:
     made_usa = {}

     for l in movie_data:
            if l[6] == 'USA':
              made_usa.update({l[0]: 'True'})
            else:
              made_usa.update({l[0]: 'False'})
     print (made_usa)

After that, if you want to look if a certain move was made in USA or not. All you need to do is, for example:
print(made_usa['Avatar'])

Output:
'True'

A: Probably you are looking for a generic solution without any third party libraries (i.e. only standard library). Here we go:
def filter_by(csv_data, column_name, column_value):
    indices = [i for i, name in enumerate(data[0]) if name == column_name]
    if not indices:
        return
    index = indices[0]
    for row in data[1:]:
        if row[index] == column_value:
            yield row

And this is how you use it:
print(list(filter_by(movie_data, "country", "USA")))

This shall output (I formatted it a bit for clarity):
[
    ['Avatar', 'James Cameron', 'Color', '178', 'CCH Pounder', 'English', 'USA', '2009'],
    ["Pirates of the Caribbean: At World's End", 'Gore Verbinski', 'Color', '169', 'Johnny Depp', 'English', 'USA', '2007']
]


Q: Download table generated independetly in renderTable output in R shiny I am trying to generate a table using the renderTable function in R shiny and then use the downloadHandler function to download that table/data.frame as a csv file. Somehow I keep getting the following error:

An error occured during download:
  Error downloading http://127:0:0.1:3001/session/
  0303bd426fce88837ae277aa3b406dd/download/downloadData?w= - server
  replied: Internal Server Error

Below is an example code where I generate a simple data frame and try to download it using downloadHander:
library(shiny)
 # Define UI for data download app ----
ui <- fluidPage(

    # App title ----
    titlePanel("Downloading Data"),

    # Sidebar layout with input and output definitions ----
    sidebarLayout(

        # Sidebar panel for inputs ----
        sidebarPanel(
            # Button
            downloadButton("downloadData", "Download")

        ),

        # Main panel for displaying outputs ----
        mainPanel(

            tableOutput("table")

        )

    )
)
# Define server logic to display and download selected file ----
server <- function(input, output) {

    # Table of selected dataset ----
    output$table <- renderTable({
        data.frame(a =c(1,2,3),b=c("q","s","f"))
    })

    # Downloadable csv of selected dataset ----
    output$downloadData <- downloadHandler(
        filename = function() {
            paste("test.csv")
        },
        content = function(file) {
            write.csv(output$table, file, row.names = FALSE)
        }
    )

}
shinyApp(ui,server)

A: There are a few things that need to be done here:

*

*If your app is going to render data dynamically, then your data should be assigned to some reactive expression.

*Now the downloading of the data becomes easy, as you just call the reactive expression written in (1).

*

*Points (1) and (2) above will ensure that the user is downloading the same data that is seen on the screen.

Try the following:
library(shiny)

ui <- fluidPage(
  titlePanel("Downloading Data"),
  sidebarLayout(
    sidebarPanel(downloadButton("downloadData", "Download")),
    mainPanel(tableOutput("table"))
  )
)

server <- function(input, output) {

  data <- shiny::reactive(data.frame(a = c(1, 2, 3), b = c("q", "s", "f")))
  output$table <- renderTable(data())

  output$downloadData <- downloadHandler(
    filename = function() {
      paste("test.csv")
    },
    content = function(file) {
      write.csv(data(), file, row.names = FALSE)
    }
  )

}
shinyApp(ui,server)

A: You cannot export a renderTable{} as this puts many of the elements into HTML,
 you need to previously save the data going into the table and export it
 seperately.
dataTable<-data.frame(a =c(1,2,3),b=c("q","s","f"))

output$downloadData <- downloadHandler(

  filename = function() {
    ('test.csv')
  },

  content = function(con) {
    write.table(dataTable,row.names = FALSE,col.names=T, sep=",",con)
  },
  contentType="csv"
)


Q: gitlab-ci reference environmental variables in ssh command I have the following command in my gitlab-ci.yml file: - rsync -v -e ssh /builds/Sustersic/untitled-combat-game/build username@1.1.1.1:/var/www/html

I tried re-writing this command with environemntal varibales:
- rsync -v -e ssh /builds/Sustersic/untitled-combat-game/build "$HOST_USERNAME"@"$HOST_IP":/var/www/html
But the environment variables are not getting read correctly. What am I doing wrong?


Q: Creating a symlink in WAMP server on Windows I am working on a downloaded version of an application and am getting multiple errors due to:
( ! ) Warning: include(/home/USERNAME/public_html/dir/includes/functions.php): failed to open stream: No such file or directory in C:\wamp\www\dir\includes\db_connection.php on line 6

I understand what the error is but I don't want to have to manually change all these includes in the code mainly as doing so means when I update my ive site they will then be wrong.
Is there a way using either WAMP or Windows of creating something like a symlink to tell WAMP that anything in /home/USERNAME/public_html/dir should be served from C:\wamp\www\dir?
I found an option in WAMP for creating an alias but I am not sure if this is the right thing to use?

A: There is an answer on SO here.
This link https://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html would serve well too (from the answer above).
Basically you have to use mklink Windows command from command prompt (the latter must be run as administrator).
Now. Assume you have WAMP installed and virtual host named mysite.local is created and pointinig to the physical d:\mysite folder. You want now the files in the folder f:\otherfolder\realfolder to be accessible via mysite.local/otherfolder/somefile.ext kind of URL.
For this you have to create the symbolic link named otherfolder in d:\mysite that will point to f:\otherfolder\realfolder. You have to execute:
mklink /D d:\myfolder\otherfolder f:\otherfolder\realfolder
from Windows command prompt. The link otherfolder is created in d:\myfolder and you can access files via an URL as mentioned above.


Q: Getting web.config error when publishing my ASP.Net website I'm trying to publish my first ASP.Net website, but I'm getting this error when I try to visit the homepage.

Unrecognized attribute 'targetFramework'. Note that attribute names
  are case-sensitive.

Here's the section of the web.config file it is referencing:
  <system.web>
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>

And here's the website itself if you want to see the full error page:
http://connellchamberofcommerce.com/
Is the ASP.Net version (4.5.2) supposed to match the .Net version my host uses or something? As I said, this is my first ASP.Net website and I'm pretty confused by this error.

A: The version information at the bottom of http://connellchamberofcommerce.com/ indicates that the .net version of app pool is 2.0.50727.5491, where as in your web.config file its 4.5.2. So change the app pool to use 4.0.

A: Your web.config looks fine to me. My guess would be that you have set the wrong .NET version in the AppPool under which your site is running.
Go to your IIS -> Select your desired AppPool -> Click Basic settings and change the .Net version accordingly.


Q: Use of Local_policy.jar and US_export_policy.jar and What is the use of these jars:
Local_policy.jar
US_export_policy.jar

I have seen other SO questions where they are asking how to upgrade. My question is what's the use of these jars. It seems they come as a violation in open source.

A: THEY ARE OBSOLETE (at least as separate added files)
They were used in an optional, and (nominally) geographically restricted, patch to versions of Sun-then-Oracle Java before late 2017, to enable (symmetric) ciphers with strength of more than 128 bits, which were disabled in the basic distribution packages in a lingering after-effect of conformity to US export regulations from the 1990s. No such patch was ever needed for OpenJDK, once that was released (which only started after the 'crypto thaw'), but in its early years it wasn't widely supported and sometimes not consistently available, so many people continued using the Oracle/Sun versions -- and many Stack Overflow questions and/or answers (both Stack Overflow and others like security.SX and Super User and Server Fault) were written for that case. Since Stack Overflow doesn't automatically delete or even deprecate old content, it remains available.
For the official details (of the versions that still have any support, even paid) see https://www.oracle.com/java/technologies/javase-jce-all-downloads.html .
IBM has long had its own implementation of Java, especially the cryptographic parts, and had a similar (but not the same) set of policy jars; I don't know if they still do, since I no longer have IBM systems running Java. In any case, Stack Overflow questions and answers for IBM Java are rare.
The 'openness' of the original Sun-centered model for Java was somewhat controversial for years, until finally settled by the establishment of OpenJDK. If you want to discuss that, it probably belongs on https://opensource.stackexchange.com/ .


Q: Rails atttr_accesible not working as documented In rails 3.2.1, I have a model:
class Player < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :email, :password
  attr_accessible :email, :password, :confirmed, :as => :admin
end

I keep getting a ActiveModel::MassAssignmentSecurity::Error for the following:
params[:player]
#=> {:email => "some@email.com", :password => "12345", :confirmed => true)
player = Player.new(params[:player])

Why is this happening when all I want it to do is ignore the :confirmed attribute and move on with it's business. The documentation makes it seem like I should be able to do that, but I keep getting this exception and it's really getting to me because either I am doing it wrong or the docs are wrong.
I'd love any help with this.

A: You can configure what you want to happen when a mass assignment happens by setting Player.mass_assignment_sanitizer (or set it on ActiveRecord::Base for it to apply to all AR models)
You can also set it in your configuration files via config.active_record.mass_assignment_sanitizer
Our of the box you can set it to either :logger, which just logs when these things happen or :strict which raises exceptions. You can also provide your own custom sanitizer.  The current application template sets it to strict, although that used not to be the case

A: Comment out this line in development.rb:
config.active_record.mass_assignment_sanitizer = :strict
The strict setting will raise an error and the default setting will just log a warning.


Q: Does bootsfaces work with jsp servlets? I am trying to migrate a project which has been working   of JSF1.2 to JSF2.1 and have succeeded in doing so ,now we want to use bootsfaces1.0.2 in the project to enhance look and feel of the application.
Our codebase is pretty old and we want to stick to JSP to avoid complexity and time needed to migrate to facelets
When I checked bootsfaces-b.taglib.xml file under META-INF of bootsfaces-1.0.2.jar, it basically uses facelets tag library
http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd"
We include the bootsfaces tag lib <%@ taglib uri="http://bootsfaces.net/ui" prefix="b" %> and it was failing , so I manually created a tld file which points to jsp tag library and changed the tag structure to be compliant with jsp 2.1 tag library , here is the stacktrace of exception I get
PWC6197: An error occurred at line: 28 in the jsp file: /jsp/login/login2.jsp
PWC6199: Generated servlet error:
method get in class org.apache.jasper.runtime.TagHandlerPool cannot be applied to given types;
  required: java.lang.Class
  found: java.lang.Class
  reason: inferred type does not conform to upper bound(s)
    inferred: net.bootsfaces.component.inputText.InputText
    upper bound(s): javax.servlet.jsp.tagext.JspTag
PWC6197: An error occurred at line: 28 in the jsp file: /jsp/login/login2.jsp
PWC6199: Generated servlet error:
cannot find symbol
  symbol:   method setPageContext(javax.servlet.jsp.PageContext)
  location: variable _jspx_th_b_inputText_0 of type net.bootsfaces.component.inputText.InputText
It seems the tag library is expecting a servlet , but bootfaces would supply a facelet component instead,
Has anyone tried to run bootsfaces on jsf2.1/Jsp ,can you provide me any suggestions on this.
Thanks,
Santosh


Q: Why can't update my form even though my session is working php So i want a very simple update page like this example:
<?php
            $sql_article = "SELECT* FROM articles WHERE article_unique_id = '".  $_SESSION['article_unique_id']."' ";
            $result_article = $conn->query($sql_article);
            if ($result_article->num_rows > 0) {
              while($row = $result_article->fetch_assoc())
{?>
         <form action="trry15.php" method="post">
           <input type="text" name="title" value="<?php echo $row['title'] ?>">
         <input type="submit" name="submitUpdate" value="Submit"></form> <?php }}?>

and to this point code works fine session works and ect.
but when I write my update code
if (isset($_POST['submitUpdate'])) {
    $update_title=$_POST['title'];

    $sql_update_title = "UPDATE `articles` SET title='$update_title' WHERE article_unique_id = '".  $_SESSION['article_unique_id']."'";
    $result_update_title=$conn->query($sql_update_title);

}

This dosent work.
But if change article_unique_id = '".  $_SESSION['article_unique_id']."'"; to
article_unique_id = '12'";

The code works. And I don't what is happening. I have session start function and  $_SESSION['article_unique_id']=$_GET['article_id'];


Q: How to add known_hosts for passwordless ssh within docker container in docker-compse.yml? I want to have passwordless ssh within two docker containers. How to add known_hosts entry for that using docker-compose.yml file
I want to implement ansible on docker env. To deploy and run rpm on deployment node, I need passwordless ssh from container1 to container2. For that I have to add known_hosts key of container1 in container2 node.
How to do this ???

A: I don't know any solution using docker-compose.yml. The solution I propose implies create a Dockerfile and execute (creating a shellscript as CMD):
ssh-keyscan -t rsa whateverdomain >> ~/.ssh/known_hosts

Maybe you can scan /ect/hosts or pass a variable as ENV.

A: try to mount it from host to container. .
--volume local/path/to/known_hosts:/etc/ssh/ssh_known_hosts
in case it didnt work, take a look at some similar case related to ssh key in docker like : this
and this


Q: Is it a good practice to use alternate exchange in RabbitMQ as dead letter exchange? I know that RabbitMQ has alternative and dead letter exchange types.
Since we don't have mapped queues for some message, from my perspective it is some kind of problem when we don't know what the message is. In this case we use alternative exchange to rout the message to another exchange by default (that can solve our routing problem).
Is it a good practise to use alternative exchange as dead letter exchange simultaneously?


Q: Where do I merge or add the drop down menu script on the header. Jsfiddle I'm trying to merge 2 codes. I found the two codes I'm looking for. I'm really new @ this so please under stand.
This is the header footer & background:
http://jsfiddle.net/F6dez/
This is the drop down menu:
http://jsfiddle.net/Mrdel/Wxs5n/2/
This is my attempt to merge the two:
I tried to leave a link but it won't let me leave more then 2 links :/
Heres the code for the menu:
HTML:

    Music

New Tracks

Old Tunes

Downloads

Upcoming

And the css:
ul { list-style: none; padding: 0; margin: 0;}

/* Style */

a {
  color: #000;
 display: block;
 font-size: 14px;
 text-decoration: none;
 font-family: 'Open Sans', serif;
 }
 nav {
 width: 100%;
 height: 45px;
 }
 #nav ul li:hover,
 #nav > li:hover {
 background: #2e98d5;
 }
 #nav ul > li:hover > a,
#nav > li:hover > a {
 color: #fff;
 }
 #nav > li {
 float: left;
  position: relative;
  }
  #nav > li > a {
  padding: 13px 30px;
   height: 20px;
  }

#nav > li:hover ul {
visibility: visible;
-webkit-transition-delay: 0s;
-moz-transition-delay: 0s;
-o-transition-delay: 0s;
transition-delay: 0s;
}
#nav ul {
 top: 46px;
width: 170px;
position: absolute;
background-color: #eee;
z-index: 1;
visibility: hidden;
-webkit-transition-property: visibility;
 -moz-transition-property: visibility;
 -o-transition-property: visibility;
 transition-property: visibility;

 -webkit-transition-duration: 0s;
 -moz-transition-duration: 0s;
 -o-transition-duration: .0s;
 transition-duration: 0s;

 -webkit-transition-delay: .25s;
 -moz-transition-delay: .25s;
 -o-transition-delay: .25s;
 transition-delay: .25s;
 }

/* The slide */
#nav li li a {
height: 0px;
padding: 0px 30px;
opacity: 0;
-webkit-transition-property: height, padding, opacity;
-moz-transition-property: height, padding, opacity;
-o-transition-property: height, padding, opacity;
transition-property: height, padding, opacity;

-webkit-transition-duration: .25s, .25s, .08s;
-moz-transition-duration: .25s, .25s, .08s;
-o-transition-duration: .25s, .25s, .08s;
 transition-duration: .25s, .25s, .08s;

-webkit-transition-delay: 0s, 0s, .05s;
 -moz-transition-delay: 0s, 0s, .05s;
 -o-transition-delay: 0s, 0s, .05s;
 transition-delay: 0s, 0s, .05s;
 }
 #nav li:hover li a {
 height: 20px;
  padding: 13px 30px;
 opacity: 1;
 }

Heres the code for the background:
HTML:
<!Doctype html>

    <link rel="stylesheet" type="text/css" href="css/style.css"/>

            This is header

First line...............

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Long content goes here...

Last line................

            This is footer

And the css:
 html {
 height:100%;
 max-height:100%;
 padding:0;
 margin:0;
 border:0;
 overflow: hidden;
 }
 body {
 height:100%;
 max-height:100%;
 overflow:hidden;
 padding:0;
 margin:0;
 border:0
 font: 12px Verdana, Helvetica, sans-serif;
 color: #F3F3F3;
 }
 .container {
 width : 100%;
 height: 100%;
 max-height:100%;
 }
 .header {
 position:absolute;
 margin:0;
 top:0;
 display:block;
 width:100%;
 height:80px;
 z-index:5;
 background-color: #656565;
 text-align : center;
 right:18px;
 line-height: 80px;
 font-size:2em;
   }
 .footer {
 position:absolute;
 margin:0;
 bottom:-1px;
 display:block;
 width:100%;
 z-index:4;
 height : 80px;
 background-color: #656565;
 text-align : center;
 right:18px;
 line-height: 80px;
 font-size:2em;
 }
 .content {
 display:block;
 height:100%;
 max-height:100%;
 overflow:auto;
 position:relative;
 z-index:3;
 background-color: #909090;
 text-align : center;
 }
 .gap {height : 80px;}

A: I'm not entirely sure I understand what you're looking for here, since it should be as easy as copying the menu code:

    Music

New Tracks

Old Tunes

Downloads

Upcoming

and pasting it into the head container:
http://jsfiddle.net/LH5TC/


Q: Server to Server communication with IBM SBT I would  like to use the IBM SBT for server to server communication instead of displaying data from , for instance, connections at the user. In this particular usecase I would like to have data updated in Connections whenever a user saves or edits data.
Because we are not using oAuth we would like to use Basic authentication without prompting the user for authentication. Are there any examples how to do is?

A: yes there are some examples of using Pure Java, no J2EE.
http://bastide.org/2014/01/28/how-to-develop-a-simple-java-integration-with-the-ibm-social-business-toolkit-sdk/
and
https://github.com/OpenNTF/SocialSDK/blob/master/samples/java/sbt.sample.app/src/com/ibm/sbt/sample/app/BlogServiceApp.java
Essentially, you'll need the dependent jar files.
once, you have the jar files you need to configure your class so you can get an Endpoint
once you have the endpoint you can use the endpoint in one of the top level services such
as ForumsService
then you can use the ForumsService to call back to Connections


Q: JS - function take a double result I got problem with this script:

<button onclick="clearInterval(stop)">stop!</button>

On marks! Start!

The script counts down from 400 to 0, with a variable interval = 40. When the script runs it subtracts 80 instead of 40. The result is double and I don't know why.
Can you help me?

A: You're calling counter() twice, subtracting 40 each time, call it just once
var start = 400;
var interval = 40;

function counter() {
    return start -= interval;
}

var stop = setInterval(function() {
    var count = counter();
    if (count > 0) {
        document.getElementById("test").innerHTML = count;
    } else {
        clearInterval(stop);
    }
}, 1000);


Q: Does Git merge to master delete unchanged files? I have a two branch first one "master" second one "newFeature"
In the master branch, I add some file and change some functions it does not exist in newFeature branch and the same in newFeature have added some new files/code AND Change file it exists in two branches and I want to apply when merged
Now when I want to merge newFeature to master,
Should I lose something in the master or other branch?

A: Git's merge operation considers exactly three points when doing a merge: the two heads (usually branches) that you want to merge, and the merge base, which is usually the point at which one was forked from the other.
When a merge occurs, Git considers the changes computed between each head and the merge base.  It then produces a result exactly like the merge base, but with both sets of changes added.  In other words:

*

*If you made a change on one side and not the other, Git will include the change.  A change in this case includes the addition, removal, or modification of a file or part of it.

*If you made a change to the same location on both sides, Git will produce a conflict.

*If you made no changes to a file or part of it, Git will include those portions unchanged.

So in your case, you've only added and modified things, so the merge result will include only additions and modifications, not removals.  It is possible you'll see a conflict, though.