text:
Q: Open a file based on date, paste data, save as new date and close I need to copy some data every month, paste it into a spreadsheet and then save it as a new file with updated date. I need the macro to look to see if A6 is empty, then select all data from A6 down, which I think is done with the If Not statement.
Once done I need to open a spreadsheet that is saved in the format "Filepath/mmyy Filename.xls"
The sheet I need opening will be last months so I need it to select that month, and then the year in the format yy.
I will also need it to clear the sheet in a certain range and then paste in the data from the first workbook, then Save As with an updated date as mmyy with this months date.
How do I set my code to open the file based on mmyy, and then save as and close? And can this all be done in the IF statement I have opened?
Sub Test()

Dim wksht As Worksheet
Dim rng As Range

Set wksht = Sheets("Birse CH")
Set rng = wksht.Range("A5")
If Not IsEmpty(rng.Offset(1, 0)) Then
    Set rng = Range(rng.End(xlDown).Offset(0, 14), rng.Offset(1, 0))
Selection.Copy
'opening workbook
Workbooks.Open Filename:="H:\Finance\CBF\Invoices\Monthly Invoicing Summary\" & Year(Date) & "\ASM\" & (Now(mm) - 1) & Now(yy) & " ASM CBF Reg Summary.xlsx"
Selection.Paste

End If
End Sub

A: What you're looking for is the Format function.
Format(Now, "mmyy")

returns 0914 at the time of writing.
However, it looks like you want to subtract one month from today's date. This will do the trick:
Format(DateSerial(Year(Now), Month(Now) - 1, 1), "mmyy")

which should replace (Now(mm) - 1) & Now(yy) which won't compile because that's not how Now works.
To SaveAs and Close, it's easiest to first set a reference to the workbook you're opening:
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="...somewhere...")
'... do stuff to the workbook
wb.SaveAs Filename:="...somewhere else..."
wb.Close


text:
Q: How to eliminate nothing elements in a array (1D) in Julia? I would like to know how I could eliminate nothing elements in a Julia array (1D) like the one below. It was built from reading a text file with lines with no relevant information mixed with lines with relevant information. "nothing" is type Void and I would like to clean the array of all of it.
nothing
nothing
nothing
nothing
nothing
"   -16.3651\t     0.1678\t    -4.6997\t   -14.0152\t    -2.6855\t   -16.0294\t    -7.8049\t   -27.1912\t    -5.0354\t   -14.5187\t\r\n"
"   -16.4490\t    -1.0910\t    -3.6087\t   -12.6724\t    -1.5945\t   -14.7705\t    -7.2174\t   -25.2609\t    -3.7766\t   -14.3509\t\r\n"
"   -16.4490\t    -2.2659\t    -2.4338\t   -10.9100\t    -0.5875\t   -13.6795\t    -6.7139\t   -22.9950\t    -2.9373\t   -14.0991\t\r\n"

A: testvector[testvector.!=nothing] is also a very readable option.
benchmarking can help choose the most efficient code.

A: How are you reading that file?
You can filter out nothings from an array:
filter(x -> !is(nothing, x), [nothing, 42])    # => Any[42]

But you may want to clean your data first, with a tsv (tab separated values) file like this:
-16.3651    0.1678  -4.6997 -14.0152    -2.6855 -16.0294    -7.8049 -27.1912    -5.0354 -14.5187
-16.4490    -1.0910 -3.6087 -12.6724    -1.5945 -14.7705    -7.2174 -25.2609    -3.7766 -14.3509
-16.4490    -2.2659 -2.4338 -10.9100    -0.5875 -13.6795    -6.7139 -22.9950    -2.9373 -14.0991

Using readdlm:
julia> readdlm("data.tsv")
3x10 Array{Float64,2}:
 -16.3651   0.1678  -4.6997  -14.0152  …  -27.1912  -5.0354  -14.5187
 -16.449   -1.091   -3.6087  -12.6724     -25.2609  -3.7766  -14.3509
 -16.449   -2.2659  -2.4338  -10.91       -22.995   -2.9373  -14.0991

Using DataFrmaes.readtable:
julia> df = readtable("data.tsv");

julia> names!(df, [symbol(x) for x in 'A':'J'])
2x10 DataFrames.DataFrame
| Row | A       | B       | C       | D        | E       | F        | G       |
|-----|---------|---------|---------|----------|---------|----------|---------|
| 1   | -16.449 | -1.091  | -3.6087 | -12.6724 | -1.5945 | -14.7705 | -7.2174 |
| 2   | -16.449 | -2.2659 | -2.4338 | -10.91   | -0.5875 | -13.6795 | -6.7139 |

| Row | H        | I       | J        |
|-----|----------|---------|----------|
| 1   | -25.2609 | -3.7766 | -14.3509 |
| 2   | -22.995  | -2.9373 | -14.0991 |

A: one simple way is using filter! function to update your vector like this:
testvector=[fill(nothing,10) ; [1,2,3]];
# =>13-element Array{Any,1}:
#    nothing
#    nothing
#    nothing
#    nothing
#    nothing
#    nothing
#    nothing
#    nothing
#    nothing
#    nothing
#    1
#    2
#    3

filter!(x->x!=nothing, testvector)
# => 3-element Array{Any,1}:
#     1
#     2
#     3

thanks @Daniel Arndt
EDIT, Refer to this paragraph from Julia doc:

nothing is a special value that does not print anything at the
  interactive prompt. Other than not printing, it is a completely normal
  value and you can test for it programmatically.

I think all of the conditions below, reach us to the same result
x!=nothing
x!==nothing
!is(x,nothing)
!isa(x,Void)
typeof(x)!=Void

A: To add to the answers above, it appears:
filter(!isnothing, [nothing, 42])

is a working shorthand for filter(x -> !isnothing(x), [nothing, 42]), and will correctly return 42.

A: Dear All,
At the end, the code became this:
tmpFile=open(fileName)
tmp=readdlm(tmpFile);
ind=pmap(typeof,tmp[:,1]).!=SubString{ASCIIString}; # if the first column typeof is string, than pmap will return false, else, it return true. This will provide an index of valid/not valid rows.
tmpClean=tmp[ind,:]; # only valid rows will be used

If you may have any suggestion to improve it, I would appreciate it. Thank you for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opening common ports - does it make a network more vulnerable/susceptible to attack? Our network admins/security admin make the case that we should keep common (external facing) ports (FTP, XMPP, IMAP, IPSEC) closed as it is a greater security risk and makes us more susceptible to attack. While I can appreciate that these choices are made with security in mind, it tends to make work difficult at best and challenging at worse for our end-users/staff/consultants.
Does blocking commonly used ports make our overall network more secure?

A: I think you're referring to egress filtering?
It's simply a question of what level of risk is acceptable to your organization, really.  As far as whether it increases security, I'd answer with a qualified yes - generally speaking, it's a good security step, but it needs to be done well to be effective (I'd be surprised if they were just blocking certain ports specifically - more likely, they're allowing only certain whitelisted ports).
Example scenarios where it'd be of use are security issues like botnet zombie reporting and spam relaying, as well as policy/bandwidth use issues like bittorrent or streaming video.
The approach you should probably take would be to state the business case for a protocol's allowance - and try to find middle ground, if needed, like allowing IMAP only to approved servers.  Remember, there's likely a policy reason that it was put in place.

A: I'm going to differ with the answers already here, and say no, almost certainly not.  If you have any of your systems externally, then allowing unencrypted connections to them might expose eg login IDs that you have an interest in keeping secure, but since we're talking egress filtering I'm guessing you don't have any such systems out there, so by blocking unencrypted services (ftp, pop, imap) you're only protecting other people's secrets, and that's not your job.
Moreover, it's pointless.  As long as you allow port 443 outbound - and there would be a riot in any organisation I've ever worked in if that was forbidden - you've got users making SSL-encrypted tunnels out of the building left, right, and centre, and you have no idea what they're passing through them.  Could be HTTP, sure, but it could also be SSH, could be IMAP, could be OpenVPN, could be anything at all as long as it's inside that SSL-encrypted tunnel.
So sure, you can annoy people by blocking other ports outbound, but as long as you're allowing HTTPS it's utterly pointless from a security standpoint; it won't prevent a determined adversary for more than a minute, and it'll really annoy all your legitimate users.


text:
Q: struct pointer casting and its memory allocation The point here is the code int header = (((int)(txUserPtr) - 4)) Illustration of UserTypes and struct pointer casting is great of help! How should I set incoming pointer txUserPtr so that Fun() would skip following lines. I don't want to execute error().
typedef union UserTypes
{
    SAUser           AUser;
    BUser            BUser;
    SCUser           CUser;
    SDUser           DUser;
} UserTypes;

typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;
typedef struct AUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } AUser;

typedef struct BUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } BUser;

typedef struct CUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } CUser;

typedef struct DUser
{
    int              userId;
    int              dbIndex;
    ChannelType      ChanType;
 } DUser;

//this is the function I want to test

void Fun(UserTypes * txUserPtr)
{

   int header = (*((int*)(txUserPtr) - 4));

   //the problem is here
   //how should i set incoming pointer "txUserPtr" so that
   //Fun() would skip following lines.
   // I don't want to execute error()

        if((header & 0xFF000000) != (int)0xAA000000)
        {
            error("sth error\n");
        }
   /*the following is the rest */
}

A: The code is relying on undefined behavior, as well as various implementation-defined behavior. Somewhere in your code there should be a struct looking similar to
typedef struct
{
  unsigned int header;
  UserTypes user;
} AHeaderPlusUserTypes;

Once you have located that struct, fix the code:
void Fun (AHeaderPlusUserTypes* txUserPtr)
{
  if((txUserPtr->header & 0xFF000000u) != 0xAA000000u)
  {
    error("sth error\n");
  }
  /*the following is the rest */
}

A: It's very hard to understand the question.
You wish to avoid the pointer having a certain bit-pattern in its most signficant bits, but it's not clear if the pointer is still expected to somehow contain the address of something you can access in the removed code.
More information about your platform's exact memory map would be necessary in order to solve this, I think.

A: How about this code?
void Fun (int header, UserTypes* txUserPtr)
{
  // exactly safe code
  if ( header & 0xFF000000u) != 0xAA000000u ) {
    error("sth error\n");
  }
  /*the following is the rest */
}


text:
Q: Passing php array data to a js file I've got some data in the following array.
$seats = array();
while ($statement->fetch()) {
    $seats[] = $book;
}

Here the result is:
  Array ( [0] => 10 [1] => 50 ).

How can I pass this data to another JS file as follows?
//Case II: If already booked
var bookedSeats = [10, 50];
init(bookedSeats);

A: Use json_encode()
//Case II: If already booked
var bookedSeats = <?= json_encode($seats) ?>;
init(bookedSeats);


text:
Q: Highlight string search string I'm using the code below to search the text in a textarea for a string entered in a textinput. I'm trying to highlight the string in the textarea after it's been searched for. I assume the way to do this is selectRange(). I'm not sure how to find the endIndex for the second parameter of selectRange(). Below is what I have:
protected function searchBtn_clickHandler(event:MouseEvent):void
{
    text = mainTextField.text;
    search_Str = searchTxt.text;

    var search_result:int = text.search(search_Str);
    trace(search_result);

EDIT
    <?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:titleContent>
        <s:TextInput id="searchTxt"/>
        <s:Button label="Button" click="searchBtn_clickHandler(event)"/>
    </s:titleContent>
    <s:TextArea id="mainTextField" x="33" y="35" width="544" height="444"/>
    <fx:Script>
        <![CDATA[
            public var text:String;
            public var search_Str:String;

            protected function searchBtn_clickHandler(event:MouseEvent):void
        {
            text = mainTextField.text;
            search_Str = searchTxt.text;

            var search_result:int = text.search(search_Str);
            trace(search_result); // Traces correct int values
            trace(mainTextField.selectRange(search_result,search_result+search_Str.length)); // Traces "undefined"
        }
        ]]>
    </fx:Script>
</s:View>

A: Can't you just calculate it based on the length of the search string?
The modified code would be like this:
protected function searchBtn_clickHandler(event:MouseEvent):void
{
    text = mainTextField.text;
    search_Str = searchTxt.text;

    var search_result:int = text.search(search_Str);
    trace(search_result);
    mainTextField.selectRange(search_result,search_result+search_Str.length);
}

Update,  In response to the original poster's code update; I went ahead and tested.  A TextAre will not display an item as selected if it does not have focus.  Therefore the solution to get the selected range to highlight is to set focus to the textArea after the button is clicked. Here is code demonstrating this:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <s:titleContent>
        <s:TextInput id="searchTxt" text="Quick" />
        <s:Button label="Button" click="searchBtn_clickHandler(event)"/>
    </s:titleContent>
    <s:TextArea id="mainTextField" x="33" y="35" width="544" height="444" text="The Quick Brown Fox Jumped Over The Lazy Dogs"/>
    <fx:Script>
        <![CDATA[
            public var text:String;
            public var search_Str:String;

            protected function searchBtn_clickHandler(event:MouseEvent):void
            {
                mainTextField.setFocus();
                text = mainTextField.text;
                search_Str = searchTxt.text;

                var search_result:int = text.search(search_Str);
                trace(search_result); // Traces correct int values
                trace(search_result+search_Str.length);
//              trace(mainTextField.selectRange(search_result,search_result+search_Str.length)); // Traces "undefined"
                mainTextField.selectRange(search_result,search_result+search_Str.length)
            }
        ]]>
    </fx:Script>

</s:View>


text:
Q: How do I troubleshoot ssh tunnels disconnection? I am using SSH tunnels launched via autossh at boot on a device installed at remote locations. Up to now everything was working fine but yesterday the connection partly went down and autossh wouldn't do its thing. And I would love to figure out what happened to prevent it ever happening again. I have to deal with SLAs and all.
Here are the details:
THE SETUP
Remote site:
-Raspbian on a raspberry pi (debian wheezy)
-Autossh running at boot connects to our server and establishes 3 ssh tunnels
   Tunnel 1: regular tunnel forwarding a local port on the raspberry pi to a server in our office
   Tunnel 2: reverse tunnel opens a port on our server pointing to a device on the remote network
   Tunnel 3: reverse tunnel opens a port from our server's loopback (127.0.0.1) adapter pointing to the ssh port of the raspberry pi on its loopback adapter.
So basically with this setup I have to ssh in our server from which I can ssh into each remote devices.
SSH Server:
-Debian Wheezy
-No firewall/iptables on the server, we use another box for this
THE PROBLEM
Both reverse tunnels (tunnels 2 and 3) stopped working. The output of
sudo netstat -atp | grep ssh

Showed that the only port still opened was for tunnel # 1
When I killed the ssh process on the server for tunnel # 1 autossh did its thing and all tunnels were reconnected but I would prefer if I didn't have to do this.
Is it normal behavior for autossh? Does autossh have issues monitoring reverse tunnels?
SYSLOG from the remote device
Sep  7 06:25:06 remote_hostname rsyslogd: [origin software="rsyslogd" swVersion="5.8.11" x-pid="1661" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
Sep  8 06:25:05 remote_hostname rsyslogd: [origin software="rsyslogd" swVersion="5.8.11" x-pid="1661" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
Sep  8 10:24:57 remote_hostname autossh[1428]: ssh exited with error status 255; restarting ssh
Sep  8 10:24:57 remote_hostname autossh[1428]: starting ssh (count 2)
Sep  8 10:24:57 remote_hostname autossh[1428]: ssh child pid is 24161
Sep  8 16:53:53 remote_hostname autossh[1428]: ssh exited with error status 255; restarting ssh
Sep  8 16:53:53 remote_hostname autossh[1428]: starting ssh (count 3)
Sep  8 16:53:53 remote_hostname autossh[1428]: ssh child pid is 30541
Sep  9 06:25:05 remote_hostname rsyslogd: [origin software="rsyslogd" swVersion="5.8.11" x-pid="1661" x-info="http://www.rsyslog.com"] rsyslogd was HUPed

A: You are using various ways to create log output,
but do not mention the most important ones:
The command ssh itself has a "verbose" option -v.
And more interesting, it also has a "verry verbose" option -vv.
Oh, and "verry verry verbose", -vvv, which may actually be too verbose!
Does it give more insight to run ssh with options -v, -vv, or -vvv?
Showing how much verbosity the options enable:
$ ssh -v   localhost true |& wc -l
56
$ ssh -vv  localhost true |& wc -l
122
$ ssh -vvv localhost true |& wc -l
282


text:
Q: Is it possible to use two different colorbox style on same page? I use colorbox to show images and html content on one page. Initializing of this elemets is different, one for the image and another for html content.
Design of window is different,  padding in cboxLoadedContent div for "image" colorbox is "padding:15px" and padding in cboxLoadedContent div for "html" colorbox is "padding:0px 15x".
I can add special class when click on "html" link and padding will be correct. But main colorbox window does not change his height.
Beside both  links are part of different galleries. So I can't call colorbox for the html with strong width and height.
Can somebody help with this?

A: I like the solution provided in the comments, but with some minor changes to make the code more generic.  The idea is that all colorbox css files are included in the ´head´ but are disabled. Then when a colorbox window is opened, only the css file with the corresponding theme is enabled.
There's a lot of ways to achieve that, one of them:
function useColorboxTheme() {
    var selectedTheme = $(this).attr("data-theme");

    $(".colorboxTheme").attr("disabled", "disabled");
    $("#" + selectedTheme).removeAttr("disabled");
}

function defaultColorboxTheme() {
    $(".colorboxTheme").attr("disabled", "disabled");
    $(".colorboxTheme.default").removeAttr("disabled");
}

$(document).ready(function(){
    $("a.colorbox").colorbox({
        onOpen: useColorboxTheme,
        onClosed: defaultColorboxTheme
    });
});

The useColorboxTheme() looks for a data-theme attribute in your colorbox anchors, e.g.:

Note that "theme1" corresponds to the id of the ´link´ tag in the head section. E.g.:
<link id="theme1" class="colorboxTheme" rel="stylesheet" type="text/css" href="css/colorbox/example1/colorbox.css">

You'll probably want to adjust that to what code or CMS you are working with, but this gives the general idea.  Here's a fiddle for that.
Be aware, however, that this is not the intended usage of colorbox. You'll have to thoroughly test it in all browsers to be sure you won't run into problems with using multiple themes.  One quirk I did notice is that the example 5 theme needs to be linked before the other themes for all themes to work together.


text:
Q: Event Binding in The Angular? I am facing certain error with $event in angular 11. Please someone help me to debug it..
$event error in angular
Error message :
Error Message

Error: src/app/recipes/recipes.component.html:4:26 - error TS2739: Type 'Event' is missing the following properties from type 'Recipe': name, description, imagePath

4     (recipeWasSelected)="selectedRecipe=$event"></app-recipe-list>
                           ~~~~~~~~~~~~~~~~~~~~~

  src/app/recipes/recipes.component.ts:6:16
    6   templateUrl: './recipes.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component RecipesComponent.

Error: src/app/shopping-list/shopping-list.component.html:3:64 - error TS2345: Argument of type 'Event' is not assignable to parameter of type 'Ingridient'.
  Type 'Event' is missing the following properties from type 'Ingridient': name, amount

3         <app-shopping-edit (ingridientAdded)=onIngridientAdded($event)></app-shopping-edit>
                                                                 ~~~~~~

  src/app/shopping-list/shopping-list.component.ts:6:16
    6   templateUrl: './shopping-list.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ShoppingListComponent.

CODE LINK:

https://github.com/Umang01-hash/RecipeBook

A:
Error: src/app/recipes/recipes.component.html:4:26

That is a typo, you listen to recipeWasSelected while your output is named recpieWasSelected within RecipesListComponent

Error: src/app/shopping-list/shopping-list.component.html:3:64

Basically the same, but I wouldn't call that "typo" in that case. You listen to ingridientAdded, while your output is named ingridientEmitter within ShoppingEditComponent.
Extended answer as per your comment
You have 2 further issues.

*

*The click event within recipes-item.component.html is not a function call, please add ()

*The EventEmitter name recipeWasSelected within RecipesListComponent is also wrong

After all I recommend to take hand on a good IDE, it would highlight you most of those issues

A: the mistake is here:
<app-shopping-edit (ingridientAdded)="onIngridientAdded($event)"> </app-shopping-edit>

The name of the Output parameter in the tag is incorrect.
You have to change the word (ingridientAdded) to (ingridientEmitter)
a working application at work
https://stackblitz.com/edit/angular-48vyda?file=src/app/app.component.html


text:
Q: Rails 5/jQuery: On click touchstart event not working I'm trying to use a bourbon/refills componenet (sliding_panel) and I have on('click touchstart') event. I'm using this for my navigation menu. The event will work just fine on first page load but after that will stop. The event uses toggleClass to show and hide the menu. I'm wasn't sure if this was a turbolinks problem so I did some digging and found the jquery-turbolinks gem. I went through the installation instructions but same outcome. Has anyone else had this problem?
Code below:
_navbar.html.erb
<button type="button" class="js-menu-trigger sliding-panel-button">
 Click for Sliding Panel
</button>

<%= link_to 'Users', users_path %>

Item 2

Item 3

sliding_panel.js
$(document).ready(function(){
 $('.sliding-panel-button,.sliding-panel-fade-screen,.sliding-panel-close').on('click touchstart',function (e) {
 $('.sliding-panel-content,.sliding-panel-fade-screen').toggleClass('is-visible');
 e.preventDefault();
 });
});

sliding_panel.scss
.sliding-panel-content {
  $action-color: #477DCA !default;
  $dark-gray: #333 !default;
  $sliding-panel-border-color: $dark-gray;
  $sliding-panel-background: lighten($sliding-panel-border-color, 5%);
  $sliding-panel-color: #fff;
  $sliding-panel-border: 1px solid $sliding-panel-border-color;
  $sliding-panel-background-hover: $action-color;
  $sliding-panel-color-hover: #fff;
  $sliding-panel-background-focus: lighten($sliding-panel-background, 5%);

  @include position(fixed, 0 auto 0 0);
  @include size(220px, 100%);
  background: $sliding-panel-background;
  -webkit-overflow-scrolling: touch;
  overflow-y: auto;
  transform: translateX(-220px);
  transition: all 0.25s linear;
  z-index: 999999;

  ul {
    padding: 0;
    margin: 0;
  }

  li {
    list-style: none;
  }

  li a {
    border-bottom: $sliding-panel-border;
    color: $sliding-panel-color;
    display: block;
    font-weight: bold;
    padding: 1em;
    text-decoration: none;

    &:focus {
      background-color: $sliding-panel-background-focus;
    }

    &:hover {
      background-color: $sliding-panel-background-hover;
      color: $sliding-panel-color-hover;
    }
  }

  &.is-visible {
    transform: translateX(0);
  }
}

.sliding-panel-fade-screen {
  @include position(fixed, 0);
  background: black;
  opacity: 0;
  transition: all 0.2s ease-in-out;
  visibility: hidden;
  z-index: 999998;

  &.is-visible {
    opacity: 0.4;
    visibility: visible;
  }
}

.sliding-panel-button {
  cursor: pointer;
  display: inline-block;
  outline: none;
  padding: 10px 16px;
  position: relative;

  img {
    height: 1.3em;
  }
}

These are exact copied exactly from the bourbon/refills site here.

A: You shouldn't listen to ready event, but to page:load event. So, the code will be something like this:
$(document).on('page:load', function(){
 $('.sliding-panel-button,.sliding-panel-fade-screen,.sliding-panel-close').on('click touchstart',function (e) {
 $('.sliding-panel-content,.sliding-panel-fade-screen').toggleClass('is-visible');
 e.preventDefault();
 });
});

Source: Rails 4: how to use $(document).ready() with turbo-links
Hope it helps.

A: Ok so I had Turbolinks ~> 5.2. I went back to Turbolinks ~> 5.0.1 and then loaded the jQuery like so: $(document).on('turbolinks:load', function() instead of using ready(). This SO post helped me figure out the solution.


text:
Q: Make enum bindable to datagridview I have an object which contains a number of string properties and an enum property called CRAction.
I have another object which represents a collection of the above object.
When I bind the collection object to something like a gridview, all of the string properties bind fine, but the enum doesn't appear.
I have added another string property which returns CRAction.ToString, but is there a better way to make an enum bindable to a control as part of an object?
It all seems a little hackish to have another property for the same thing purely for data binding!

A: This works for me:
<asp:Label> <%# DataBinder.Eval(Container.DataItem, "CRAction") %></asp:Label>


text:
Q: Table searches fast on local SQL Server but slow on host SQL Server I have a SQL Server 2008 database with a table that contains about a 100,000 rows, I have setup all the correct indexes and primary keys and Full Text Search and made sure its fine tuned.
I created a stored procedure that searches a nvarchar column in the table, the SP is long and has multiple select / insert statements.
Now when I run the SP on my local SQL Server I get the result in one second, then I backed up the database and restored it on another machine and tried the same search and I  got it in one second.
My problem is when I create the database in my hosts shared SQL Server and import all the data from my SQL Server and run the search I get the result in 7 seconds! although I made sure I have the same indexes and primary keys and FTS working.
The only difference in my database in the hosts sql server is that I created the schema using a script then I imported all the data using the import/export wizard, so to check if this is whats causing this problem I created a new database on my machine and imported the data using the wizard, and I got the search result in 3 seconds!
I checked the execution plan of the SP in the database on the hosts SQL Server and found one index scan is taking 49% of the cost while on my machine it was 0%
Can somebody please point out why this is happening?
Thanks.
EDIT:
Now when I run the execution plan for both servers I get exactly the same plan and costs, but still the speed difference is huge (1 second and 7 seconds).

A: Although I didn't solve the strange behavior in SQL Server, I ended up replacing this stored procedure with Full Text Search and it gave a faster result.


text:
Q: Can you play a radio stream with google actions? Is there a way to output a radiostream on devices that use googles assistant? Basically I need to develop an action that is streaming audio constantly just like any other already built in radio service. But here the action would have to be activated manually and then the device would start to play radio.
Thanks in advance

A: No the actions on Google platform doesn't support streaming audio.


text:
Q: Usage of the phrase fall back I came across the usage of "falling back" in a poem (Ted Hughes' Crow and Mama), and googled for its meaning and its usages.
Putting the poem aside, what I'd like to understand is when an english speaker would use this phrase, and when would he use the other synonyms such as retreat, withdraw, and recoil.


text:
Q: Can anyone explain the code about cin.tie() in C++? // redefine tied object
#include <iostream>     // std::ostream, std::cout, std::cin
#include <fstream>      // std::ofstream

int main () {
  std::ostream *prevstr;
  std::ofstream ofs;
  ofs.open ("test.txt");

  std::cout << "tie example:\n";

  *std::cin.tie() << "This is inserted into cout";
  prevstr = std::cin.tie (&ofs);
  *std::cin.tie() << "This is inserted into the file";
  std::cin.tie (prevstr);

  ofs.close();

  return 0;
}

We can get same output if we remove the line:
std::cin.tie (prevstr);

Why is this?

A: std::cin.tie(prevstr) doesn't do anything in your original code because you didn't perform any operations on the stream afterward. *std::cin.tie() << "This is inserted into the file2" prints to stdout because std::cin.tie(prevstr) ties std::cin back to std::cout. prevstr points to the stream that std::cin was tied to before you set it to ofs, which is std::cout. If that line wasn't there it would have printed to the file.


text:
Q: Efficient cross join with aggregation and filter As per the title, I am looking to do a cross join with a table which performs an aggregation function and filters on a couple of variables within the table.
I have similar data to the following:
library(dplyr)
library(data.table)
library(sqldf)

sales <-  data.frame(salesx = c(3000, 2250,850,1800,1700,560,58,200,965,1525)
                     ,week = seq(from = 1, to = 10, by = 1)
                     ,uplift = c(0.04)
                     ,slope = c(100)
                     ,carryover = c(.35))
spend <- data.frame(spend = seq(from = 1, to = 50000, by = 1))

tempdata <- merge(spend,sales,all=TRUE)
tempdata$singledata <- as.numeric(1)

And here is an example of what I am trying to accomplish via my sql based solution:
newdata <- sqldf("select a.spend, a.week,
                 sum(case when b.week > a.week
                 then b.salesx*(b.uplift*(1-exp(-(power(b.singledata,b.week-a.week)/b.slope))))/b.spend
                 else 0.0 end) as calc3
                 from tempdata a, tempdata b
                 where a.spend = b.spend
                 group by a.spend,a.week")

This provides the results I want, but it is a little slow, particularly with my real dataset of around 1 million records. It would be great to have some advice on a) how to speed up the sqldf function; or b) using a more efficient data.table/dplyr approach (I can't get my head around the cross join/aggregation/filter trifecta problem).
Clarity on non-equi join solution below:
I had a couple of questions about the non-equi join solution – output is fine and very quick. In looking to understand how the code worked, I broke it down like this:
breakdown <- setDT(tempdata)[tempdata, .(spend, uplift, slope,carryover,salesx,  singledata, week, i.week,x.week, i.salesx,x.salesx, x.spend, i.spend), on=.(spend, week > week)]

Based on the breakdown, in order to be consistent with the original calculation, it should be:
x.salesx*(uplift*(1.0-exp(-(`^`(singledata,x.week-week)/slope))))/i.spend

The reason why this isn't apparent is because with the example I used the 'power' part of the equation wasn't really doing anything (always 1). The actual calc used is (adding a carryover variable to data):
SQL
b.salesx*(b.uplift*(1-exp(-(power((b.singledata*b.carryover),b.week-a.week)/b.slope))))/b.spend (sql)

My data.table solution
sum(salesx.y*(uplift.y*(1-exp(-((singledata.y*adstock.y)^(week.y-week.x)/slope.y))))/spend), by=list(spend, week.x)

However, I am unable to get this working with the non equi join solution when adding the 'carryover' variable ie.
x.salesx*(uplift*(1.0-exp(-(`^`((singledata*carryover),x.week-week)/slope))))/i.spend

A: With version 1.9.8 (on CRAN 25 Nov 2016) of data.table non-equi joins were introduced which help to avoid memory-consuming cross joins:
library(data.table)
newdata4 <-
  # coerce to data.table
  setDT(tempdata)[
    # non-equi self-join
    tempdata, on = .(spend, week > week),
    # compute result
    .(calc3 = sum(salesx*(uplift*(1.0-exp(-(`^`(singledata,week-i.week)/slope))))/i.spend)),
    # grouped by join parameters
    by = .EACHI][
      # replace NA
      is.na(calc3), calc3 := 0.0][]

# check that results are equal
all.equal(newdata, as.data.frame(newdata4[order(spend, week)]))

[1] TRUE

Benchmark
The OP has provided three different solutions, two sqldf variants and one data.table approach using a cross join. These are compared against the non-equi join.
The code below
dt_tempdata <- data.table(tempdata)
microbenchmark::microbenchmark(
  sqldf = {
    newdata <- sqldf("select a.spend, a.week,
                 sum(case when b.week > a.week
                     then b.salesx*(b.uplift*(1-exp(-(power(b.singledata,b.week-a.week)/b.slope))))/b.spend
                     else 0.0 end) as calc3
                     from tempdata a, tempdata b
                     where a.spend = b.spend
                     group by a.spend,a.week")
  },
  sqldf_idx = {
    newdata2 <- sqldf(c('create index newindex on tempdata(spend)',
                        'select a.spend, a.week,
                        sum(case when b.week > a.week
                        then b.salesx*(b.uplift*(1-exp(-(power(b.singledata,b.week-a.week)/b.slope))))/b.spend
                        else 0.0 end) as calc3
                        from main.tempdata a left join main.tempdata b
                        on a.spend = b.spend
                        group by a.spend,a.week'), dbname = tempfile())
  },
  dt_merge = {
    newdata3 <- merge(dt_tempdata, dt_tempdata, by="spend", all=TRUE, allow.cartesian=TRUE)[
      week.y > week.x,
      .(calc3 = sum(salesx.y*(uplift.y*(1-exp(-(singledata.y^(week.y-week.x)/slope.y)))))),
      by=.(spend, week.x)]
  },
  dt_nonequi = {
    newdata4 <- dt_tempdata[
      dt_tempdata, on = .(spend, week > week),
      .(calc3 = sum(salesx*(uplift*(1.0-exp(-(`^`(singledata,week-i.week)/slope))))/i.spend)),
      by = .EACHI][is.na(calc3), calc3 := 0.0]
  },
  times = 3L
)

returns these timings:

Unit: seconds
       expr       min        lq      mean    median        uq       max neval cld
      sqldf  9.456110 10.081704 10.647193 10.707299 11.242735 11.778171     3   b
  sqldf_idx 10.980590 11.477774 11.734239 11.974958 12.111064 12.247170     3   b
   dt_merge  3.037857  3.147274  3.192227  3.256692  3.269412  3.282131     3  a
 dt_nonequi  1.768764  1.776581  1.792359  1.784397  1.804156  1.823916     3  a

For the given problem size, the non-equi join is the fastest, nearly twice as fast as the merge/cross-join data.table approach and 6 times faster than the sqldf codes. Interestingly, index creation and/or temp file usage seems to be rather costly on my system.
Note that I have streamlined OP's data.table solution.
Finally, all versions except the merge/cross-join (I have refrained from fixing this version) return the same result.
all.equal(newdata, newdata2) # TRUE
all.equal(newdata, as.data.frame(newdata3[order(spend, week.x)])) # FALSE (last week missing)
all.equal(newdata, as.data.frame(newdata4[order(spend, week)])) # TRUE

Larger problem size
The OP has reported that the merge/cross-join data.table solution runs out of memory for his production data set of 1 M rows. To verify the non-equi join approach consumes less memory, I have tested it with a problem size of 5 M rows (nrow(tempdata)) which is ten times larger than in the previous benchmark runs. On my PC with 8 GB of memory the run completed without problems in about 18 seconds.

Unit: seconds
       expr      min       lq     mean   median       uq      max neval
 dt_nonequi 18.12387 18.12657 18.23454 18.12927 18.28987 18.45047     3

A: Finally had time to investigate this again:
My original solution:
  system.time(newdata <- sqldf("select a.spend, a.week,
                   sum(case when b.week > a.week
                   then b.salesx*(b.uplift*(1-exp(-(power(b.singledata,b.week-a.week)/b.slope))))/b.spend
                   else 0.0 end) as calc3
                   from tempdata a, tempdata b
                   where a.spend = b.spend
                   group by a.spend,a.week"))

   user  system elapsed
  11.99    3.77   16.11

With an index (although something tells me this isn't working properly):
system.time(newdata2 <- sqldf(c('create index newindex on tempdata(spend)',
                                    'select a.spend, a.week,
                                    sum(case when b.week > a.week
                                    then b.salesx*(b.uplift*(1-exp(-(power(b.singledata,b.week-a.week)/b.slope))))/b.spend
                                    else 0.0 end) as calc3
                                    from main.tempdata a left join main.tempdata b
                                    on a.spend = b.spend
                                    group by a.spend,a.week'), dbname = tempfile()))

   user  system elapsed
  12.73    2.93   15.76

Data.table solution (doesn't return 0's from the ifelse statement in sql):
    datatablefunc <- function(g){
    tempdata2 <- as.data.table(g)
    setkey(tempdata2, spend)
    tempdata3 <- merge(tempdata2, tempdata2, by="spend", all=TRUE, allow.cartesian=TRUE)
    tempdata4 <-  tempdata3[week.y > week.x, sum(salesx.y*(uplift.y*(1-exp(-(singledata.y^(week.y-week.x)/slope.y))))/spend), by=list(spend, week.x)]
    return(tempdata4)
  }
  system.time(newdata3 <- datatablefunc(tempdata))

   user  system elapsed
   2.36    0.25    2.62

The beauty of the sql based solution is that because the temporary output is stored in the sql server and not in memory then I don't run into pesky 'cannot allocate vector' problems, which happens with the data.table/dplyr solutions (when I add more data)...the downside is it takes a bit longer to run.


text:
Q: How to get Id in ext.net, Code line return null (extjs)? I try to use below line to get ID, it works fine in Ext.Net V1.x but create problem with V2.X with IE10.
var f=Ext.get('<%=BtnID.ClientID%>');

as the same get function does't work with any extjs control.
Same thing happen with:
var jj = Ext.get(<%=grd.ClientID %>.getView().getHeaderCell(0).childNodes[0]);

A: ok ... in V2.x, we can access controls without Ext.get. like;
var f=<%=BtnID.ClientID%>;


text:
Q: Serialization Interface is empty in JDK Source. What is the use of implementing it It was marked duplicate and i am expanding my question.
My question is how JDK internally serializing objects.  How ObjectxxxStreams class serializing when the class implements that interface.?
I was looking into the serialization topic and deeply dived into the JDK Source code.
This was the source code of serialization Interface in JDK.
package java.io;
public interface Serializable {
}

There is nothing in this interface.  What is the use of implementing this interface.  I know that, to serialize a object we should implement this.  I know what serialization is and how to work with that.  But how serialization happens internally using ObjectInputStream and ObjectOutputStream.  These classes are how related to serialization. Alternatively let us keep that those two classes are doing their duty.  All my question is why we need to implement this empty interface to serialize and deserialize objects and how it works internally?  Please explain in detail about this.

A: why we need to implement this empty interface ??

Its a design pattern

The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata.

A: Serializable  is marker interface

java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used.

Refer javadoc and  Requirement of the serializable interface

A: Serializable is marker interface and marker interface does not have any methods but significance of it in method signature so that JVM can identify it.

A: java.io.Serializable it's what is called a marker interface. It doesn't declare any functionality, it just flags to other entities handling the implementing class that it's serialisable. For a good discussion about these subjects have a look at:
marker interface in java
Why Java needs Serializable interface?

A: we can't say that an interface which doesn't have any method is a marker interface. because the word "Marker" itself signifies the meaning that " marking something". so i say, the interface(whatever may be it's contents) by implementing which if a class gains some extra or specialized behavior like allow object to store into a persistence storage(Serializable) OR allow an object to make it's duplicate or raplica(Cloneable) OR allow a user to implement only one method(like run()) instead of implementing nearly 4 t0 5 methods in a subclass in thread programming(Runnable) .
these are the specialized behavior which can be gained by an object when it implements those interfaces which are nothing but called as MARKER INTERFACE.
CONCLUSION
Marker interface may or may not contain methods...
it can also be called as tagged interface,dummy interface,empty interface....
You can also refer which I found itself from SO:
Why Java needs Serializable interface?


text:
Q: How do I input a TextButton background color to a function in Flutter/dart I'm trying to create a function where under buildKey I can input two elements, the background color and the soundNumber so that when buildKey is called I can enter say buildKey(red, 2) or buildKey(colName: red, soundNumber: 2) etc.
The soundNumber element works however no matter what I try I can't get a valid background color input to work.
Any help hugely appreciated.

class _MyHomePageState extends State<MyHomePage> {
  void playSound(int noteNumber) {
    AssetsAudioPlayer.newPlayer().open(
      Audio("/assets/note$noteNumber.wav"),
    );
  }

  Expanded buildKey({required MaterialColor color, required int soundNumber}) {
    return Expanded(
      child: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: color,
        ),
        onPressed: () {
          playSound(soundNumber);
        },
        child: const Text(''),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            buildKey(color: MaterialStateProperty.all(Colors.red), soundNumber: 1),
          ],
        ),
      ),
    );
  }
}

A: You have to use MaterialStateProperty class to apply color. Here is the Example:
TextButton(
    child: Text('Your Text'),
    style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
    onPressed: () {},
),

A: Was helped with a fix. It kept the original styleFrom on the TextButton instead of using MaterialStateProperty. I was inputing the argument incorrectly so using Color as the data type worked.
Expanded buildKey({required Color colName, required int soundNumber}) {
    return Expanded(
      child: TextButton(
        style: TextButton.styleFrom(
          backgroundColor: colName,
        ),
        onPressed: () {
          playSound(soundNumber);
        },
        child: const Text(''),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            buildKey(colName: Colors.red, soundNumber: 1),
            buildKey(colName: Colors.orange, soundNumber: 2),
            buildKey(colName: Colors.yellow, soundNumber: 3),
            buildKey(colName: Colors.green, soundNumber: 4),
            buildKey(colName: Colors.teal, soundNumber: 5),
            buildKey(colName: Colors.blue, soundNumber: 6),
            buildKey(colName: Colors.purple, soundNumber: 7),
          ],
        ),
      ),
    );
  }
}


text:
Q: Planet Class with variables I'm working on a text-based space exploration game in Python. I would like the planets to be assigned attributes based on their type (gas giant, terrestrial, ice giant). I have a class with mass, density, gravity, radius, resources, and number of moons. My question is what is the best way to define these variables? Here is what I have so far.
class GasGiant:
    def __init__(self, mass, density, gravity, radius, resources, moons=None):
        if moons is None:
            moons = random.radint(1,20)
        self.mass = mass
        self.density = density
        self.gravity = gravity
        self.radius = radius
        self.resources = resources
        self.moons = moons

A: In terms of structure it looks fine, but if this is just a data object, then I would highly recommend using a dataclass.
Dataclasses allow for less boilerplate and provide many usefull methods like a constructor, equality, and string, repr, hashing, etc.
Also by using type annotations you provide better readability for what the fields are, and enable tools like mypy to do static analysis of code:
from dataclasses import dataclass, field
import random

@dataclass
class GasGiant:
    mass: float
    density: float
    gravity: float
    radius: float
    resources: list[str]
    moons: int = field(default_factory=lambda: random.randint(1, 20))

A: *

*Maybe you want this feature to auto set self value?

code:
from functools import wraps
import inspect
import random
def initializer(func):
    names, varargs, keywords, defaults = inspect.getargspec(func)

    @wraps(func)
    def wrapper(self, *args, **kargs):
        for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
            setattr(self, name, arg)

        for name, default in zip(reversed(names), reversed(defaults)):
            if not hasattr(self, name):
                setattr(self, name, default)

        func(self, *args, **kargs)

    return wrapper

class GasGiant:
    @initializer
    def __init__(self, mass, density, gravity, radius, resources, moons=None):
        if self.moons is None:
            self.moons = random.randint(1,20)

g = GasGiant(1,2,3,4,5)
print(g.__dict__)
g = GasGiant(1,2,3,4,5,6)
print(g.__dict__)

result:
{'mass': 1, 'density': 2, 'gravity': 3, 'radius': 4, 'resources': 5, 'moons': 16}
{'mass': 1, 'density': 2, 'gravity': 3, 'radius': 4, 'resources': 5, 'moons': 6}

A: If something is likely to vary based on different instances of class then it is recommended to set it in init.
Otherwise, if it's something you want it to remain same for all instances of the class, it should be set directly in the class definition.
If your class is inheriting from some other class, then you have to put the name of that class from which it is inheriting in the paranthesis
class Base(object):
    def __init__(self):
        print("base class")

class firstChild(Base):
    def __init__(self):
        Base.__init__(self)

A: I'm a beginner to python myself but maybe you can do something like this:
class GasGiant:
    def __init__(s, mass, density, gravity, radius, resources,moons=random.radint(1,20)):
        s.mass,s.density,s.gravity,s.radius,s.resources,s.moons = mass,density,gravity,radius,resources,moons

It is just pretty much cramping everything into smaller spaces.


text:
Q: wpf color the cells in DataGrid Based on value I want to change text color of cells based on value that cell contains
I use a value converter, but somehow the type of object that is getting passed to Convert function is DataRowView, and i want to pass the Cell, because i want to hightlight one cell at a time based on its value. Hope that makes sense.
Thanks!!
Code if style that i apply to DataGrid:
<UserControl.Resources>
    <local:MyBkColorConverter x:Key="bkColorCvrt"/>
    <Style x:Key="GridStyle" TargetType="DataGrid">
        <Setter Property="ItemsSource" Value="{Binding}" />
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="RowBackground" Value="Transparent" />
        <Setter Property="HeadersVisibility" Value="None" />
        <Setter Property="GridLinesVisibility" Value="None" />
        <Setter Property="SelectionUnit" Value="Cell" />
        <Setter Property="SelectionMode" Value="Single" />
        <Setter Property="IsReadOnly" Value="True" />
        <Setter Property="HorizontalScrollBarVisibility" Value="Disabled" />
        <Setter Property="CellStyle">
            <Setter.Value>
                <Style TargetType="{x:Type DataGridCell}">
                    <Setter Property="Foreground">
                        <Setter.Value>
                            <Binding Converter="{StaticResource bkColorCvrt}"/>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="Black">
                            </Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Setter.Value>
        </Setter>
      </Style>
</UserControl.Resources>

And the c# part:
public class MyBkColorConverter : IValueConverter
    {
        #region IValueConverter Members
    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //The type of value here is actually DataRowView
        //here i would like to have a cell passed. is that possible to archive?
        return Brushes.LightGray;
    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

A: If you create a style that will apply on each control matches that type.
Simply use the DataGridTemplateColumn and create your custom Template you can do as you wish.
  <DataGridTemplateColumn Header="Name">
      <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Foreground="{Binding Name,Converter={StaticResource colconverter}}" Text="{Binding Name}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
   </DataGridTemplateColumn>

A: It works if you pass a Path to the property that needs to be converted in the Binding.
<DataGridTextColumn Binding="{Binding Path=AgentUtilization, StringFormat=P}" Header="Agent Utilization">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="Foreground" Value="{Binding Path=AgentUtilization, Converter={StaticResource UtilizationFormat}}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

The type that gets passed to the converter is then the type of the property in your binding path (of course, after the cast).


text:
Q: Storing data in an Array and outputting that data I am working on a program that stores data in an Array from the user and outputs that data.
For example:
An input:
Happy HAPPY@foo.com

The output:
 NAME:  Happy
 EMAIL: HAPPY@foo.com

I was hoping someone could look at what I've got so far and give me a pointer on how to continue. I know I have to use the scanner class and  scan.nextLine, I'm not sure what comes next. I understand I don't have much, I'm not looking for someone to complete this, but maybe someone who can give me some pointers or point me in the right direction. I believe I have the correct base to my program.
My Code So Far:
    import java.util.ArrayList;
    import java.util.Scanner;

    public class Program5 {

      void loadContacts()
      {
        Scanner scan = new Scanner(System.in);
        System.out.println(scan.nextLine());

        scan.close();
      }

      void printContacts()
      {

      }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Program5 program5 = new Program5();
        program5.loadContacts();
        program5.printContacts();

    }

}

A: You should have a global varible to store the name and the email. Try adding these lines on the top of the code. after public class Program5 {.
private String Name, Email;

The you must assing this values to void loadContacts(). Spliting the string you read.
void loadContacts()
{
    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();
    String arr[] = input.split("\\s+");
    Name = arr[0];
    Email = arr[1];
    scan.close();
}

And finally on void printContacts().
void printContacts()
{
    System.out.println("NAME: " + Name + "\nEMAIL: " + Email);
}

Here is the code runnig: http://ideone.com/mjyfHK

A: Better name the class "person" or like this, but nevermind for the explanation :
public class Program5 {
    private String name;
    private String mail;

    public Program5(){}

    void loadContacts(){
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a name and a mail like this : name email@email.com (separate with ' ')");
        String[] line = scan.nextLine().split(" ");
        while(line.length!=2){
            System.out.println("Again, enter a name and a mail like this : name email@email.com (separate with ' ')");
            line = scan.nextLine().split("/");
        }
        this.setName(line[0]);
        this.setMail(line[1]);
        scan.close();
    }

    void printContacts() {
        System.out.println("NAME : "+this.name+"\nEMAIL : "+this.mail);
    }

    public static void main(String[] args) {
        Program5 program5 = new Program5();
        program5.loadContacts();
        program5.printContacts();
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setMail(String mail) {
        this.mail = mail;
    }
}

In the loadyou ask the user, check it he enter 2 element separate by '/' and if yes store them as attributes to be able to get them in another method ;)

A: You can do a variety of things.

*

*You can make loadContacts() and printContacts() static methods, and also change loadContacts() so that it returns an Array or 2D array or however you choose to represent a name-email pair. Then change printContacts()` to take in that type and iterate through that Array to print out each name/email pair. This solution is a bit more work but you won't have to create an object of the same class within the main method of that class.

or

*You can keep your method as they are and instead create a new field for the program class, called contacts and it would be of the type that you choose for representing name/email pairs. You would add items to contacts in loadContacts() and iterate through it in printContacts(). Then you don't have to change anything in your main method.


text:
Q: @task_postrun.connect signal in Celery and executing another task results in some infite loop of executions I need following workflow for my celery tasks.
when taskA finishes with success I want to execute taskB.
I know there is signal @task_success but this returns only task's result, and I need access to parameters of previous task's arguments. So I decided for code like these:
@app.task
def taskA(arg):
    # not cool, but... https://github.com/celery/celery/issues/3797
    from shopify.tasks import taskA
    taskA(arg)

@task_postrun.connect
def fetch_taskA_success_handler(sender=None, **kwargs):
    from gcp.tasks import taskB
    if kwargs.get('state') == 'SUCCESS':
        taskB.apply_async((kwargs.get('args')[0], ))

The problem is the taskB seems to be executed in some endless loop many, many times instead only once.

A: This way it works correctly:
@app.task
def taskA(arg):
    # not cool, but... https://github.com/celery/celery/issues/3797
    # otherwise it won't added in periodic tasks
    from shopify.tasks import taskA
    return taskA(arg)

@task_postrun.connect
def taskA_success_handler(sender=None, state=None, **kwargs):

    resource_name = kwargs.get('kwargs', {}).get('resource_name')

    if resource_name and state == 'SUCCESS':

        if sender.name == 'shopify.tasks.taskA':
            from gcp.tasks import taskB
            taskB.apply_async(kwargs={
                'resource_name': resource_name
            })

just for reference:
celery==4.1.0
Django==2.0
django-celery-beat==1.1.0
django-celery-results==1.0.1
flower==0.9.2
amqp==2.2.2

Python 3.6


text:
Q: Running Test Cases in Django, just like testcases in leetcode, codesignal and codewar Does anybody knows, how we can  run test cases on a data(function) sent by the user in Django, (as implemented by leetcode, codesignals and codewar)
How my function(solution) is tested against these test, how can I implement this functionality at backend using django, django rest framework (click on this link to see the image)

A: import subprocess

def test_submission():
    compiled_code = "test.out"
    test_input = open("path/to/test_input.txt")
    submission_output = open("path/to/submission_output.txt")

    cmd = [f"./{compiled_code}"]
    subprocess.run(cmd, stdin=test_input, stdout=submission_output)

    # At this point the output of executed code with test_input is stored in "path/to/submission_output.txt"
    return

The test_program can be any file be it C, C++ or Python.

A: If you don't need test support, you should be able to run code easily by just using the official container images for the language and the Docker CLI.
and there is a tool too which was used by codewar and qualified,
and you can also see this clone of codewar too for better understanding, I think it's bit simplified and a practical implementation of this codewar CLI too,
and one last thing, if you are in python use can also use eval but the prob with using this, some malicious user can insert rogue script that could be harmful, so I think you should avoid using it,
personally I think, you should use the simple docker option with a bit of sandboxing, because in our case, It's mostly just a thin wrapper around Docker API that takes the submitted code, prepares the environment and executes them. It's so simple that the original PoC was just few lines of shell script and a tiny tool written in Go.


text:
Q: need to populate an array in php with urls as key I need an Array of the following structure:
Array
(
[www.example.com] => Array
    (
        [0] => http://www.example.com/
        [1] => http://www.example.com/something.html
        [2] => http://www.example.com/anything.html
    )

[www.beispiel.com] => Array
    (
        [0] => http://www.beispiel.com/product-services/
        [1] => http://www.beispiel.com/non-disclosure-agreement/
    )
 )

As input arrays I have the following two
Array ( [0] => http://www.example.com/
        [1] => http://www.example.com/something.html
        [2] => http://www.example.com/anything.html
        [3] => http://www.beispiel.com/product-services/
        [4] => http://www.beispiel.com/non-disclosure-agreement/
      )

and
Array ( [0] => www.example.com [1] => www.beispiel.com )

in the moment I have something like this:
Array
(
[0] => Array
    (
        [www.example.com] => http://www.example.com/
    )

[1] => Array
    (
        [www.example.com] => http://www.example.com/something.html
    )

[2] => Array
    (
        [www.example.com] => http://www.example.com/anything.html
    )

[3] => Array
    (
        [www.beispiel.com] => http://www.beispiel.com/product-services/
    )

[4] => Array
    (
        [www.beispiel.com] => http://www.beispiel.com/non-disclosure-agreement/
    )

)

is that possible or do I miss some information about php (for example key could not be an parsed url (host)) ?

A: Try:
$arr1 = array('http://www.example.com/','http://www.example.com/something.html','http://www.beispiel.com/product-services/' ...); // 1st input array
$arr2 = array('www.example.com', 'www.beispiel.com'); // 2nd input array
$arr1_val = array_values($arr1);
foreach($arr2 as $v) {
 foreach($arr1 as $m) {
   if(strpos($m, $v) !== FALSE)
    $new_arr[$v][] = $m;
  }
}

Demo

A: It is not possible. Same naming rules apply for array keys, as it does for variables.


text:
Q: HTAccess URL Rewrite affect GET variables We're using wordpress, and we have the following in the .htaccess:
# BEGIN WordPress

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

# END WordPress

We have a URL like http://subdomain.example.com/select-a-card/?q=fuel, and we want to rewrite it so that it becomes something like http://subdomain.example.com/fuel-card/
What do I need to add to the htaccess to do this? Also, will this affect the queries from running that uses GET variables?

A: nothing, just read the wordpress manual and edit your settings. checkout http://codex.wordpress.org/Using_Permalinks
--- EDIT
This can be done, but only if you have some sort of a standard markup of the url's you want to have rewritten. Ie. if you only want to rewrite the select-a-card url's, or only the url's with a syntax like http://site.com/uri/?q=something. But you if the syntax of the url's differ too much you will have to add a lot of rewrites.
In this specific case something like this should work:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # add your specifics below:
    RewriteRule ^/select-a-card/\?q=(.*) $1-card/

    RewriteRule . /index.php [L]
</IfModule>


text:
Q: Creating a modal with yes/no commands for web Right now, I have a card for people to add, edit, or delete a device, with subsequent FAS font-awesome icons. Basically, I want to know how to create a popup command or option for when someone clicks one of these icons. For example, if someone one were to click a "delete" symbol, a popup that would include text, yes, and no buttons. Where I am stuck is trying to make the modal close with the yes and no buttons, and how to submit information for the yes command.
Separately, I am trying to change the styling (border, background color) of the buttons and getting stuck.
Currently, an example of my code can be accessed w3schools.com--
https://www.w3schools.com/code/tryit.asp?filename=G77OAKK28TTH

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
body {
  font-family: Arial, Helvetica, sans-serif;
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content */

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

<button id="myBtn">Open Modal</button>

    ×

Would you like to delete this device?

    <button>Yes</button><button>No</button>

A: I added id's to your buttons and this code to close the modal when the button with id "yes-button" is clicked:
document.getElementById("yes-button").onclick = function() {
  modal.style.display = "none";
}

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

// Close modal when button with id "yes-button" is clicked
document.getElementById("yes-button").onclick = function() {
  modal.style.display = "none";
}
body {
  font-family: Arial, Helvetica, sans-serif;
}

/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content */

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

<button id="myBtn">Open Modal</button>

    ×

Would you like to delete this device?

    <button id="yes-button">Yes</button><button id="no-button">No</button>


text:
Q: A simple RcppArmadillo index issue I'm coding with RcppArmadillo and got stuck with a very basic question. Suppose I have a vector "v", and I want to take its first 10 elements, like in R: v[1:10]. Since 1:10 doesn't work in RcppArmadillo, I tried v.elem(seq_len(10)), but it didn't work. Any hint?

A: Assuming you're taking about an arma::vec, this should work:
#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::vec f(const arma::vec & v, int first, int last) {
    arma::vec out = v.subvec(first, last);
    return out;
}

/*** R
f(11:20, 3, 6)
*/

Note that this uses zero-based indexing (11 is the 0th element of the vector). Coerce to NumericVector as desired.
When source'ed into R, the code is compiled, linked, loaded and the embedded example is executed:
R> sourceCpp("/tmp/armaEx.cpp")

R> f(11:20, 3, 6)
     [,1]
[1,]   14
[2,]   15
[3,]   16
[4,]   17
R>

So it all really is _just one call to subvec().  See the Armadillo documentation for more.


text:
Q: Code alignment lines? Does Aptana Studio 3 have the ability to show vertical lines that match the opening and ending tags so that you know that the tags are correctly aligned? I have found this very useful in Notepad++ and was wondering if this was an option in Aptana.
Thank you

A: Did this worked on Aptana Studio 3, build: 3.4.1.201306062137 ?

A: For code alignment click in:
Source > Format


text: Q: Closed-form of $\int_0^{{z^{ - \delta }}} {\left( {1 - \frac{1}{{{{\left( {1 + {t^{ - \frac{ 1}{\delta} }}} \right)}^{i + 1}}}}} \right)} dt$? Can the following definite integral be solved in closed-form? $$\int_0^{{z^{ - \delta }}} {\left( {1 - \frac{1}{{{{\left( {1 + {t^{ - \frac{ 1}{\delta} }}} \right)}^{i + 1}}}}} \right)} dt,$$ where $z\ge 0$, $0<\delta<1$, $i=0,1,2,3,\cdots$.


text:
Q: Sorting an array of letters by order they came out from original string in JavaScript I'm currently learning javascript sorting on terminal/console and due to my limited experience, I'm getting stuck figuring this one out... so please, bare with me.
I'm making a function that will return an array containing vowels of a string. The result array's elements is ordered by which character came first. For example:
Suppose I have this string = "Sample Case"
The function should return a result array like this = [a,a,e,e]
Below is my code and right now, what I can do is to extract the vowels with my function:
const prompt = require('prompt-sync')();

const isVowel = (c) => {
    if(c) {
      return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1;
    } else {
      return 'string is empty';
    }
};

const sortChar = () => {
    const wordsInput = prompt("Input one line of word(s): ");
    let vowels = wordsInput.split(' ').join('').split('').filter((x) => isVowel(x));
    let consonants = wordsInput.split(' ').join('').split('').filter((x) => !isVowel(x));

    console.log(vowels.sort((a, b) => {
        if(a === b) {
            return 1;
        }
        return 0;
    }))
};

sortChar();

Current output with above code: [a,e,a,e]
How to sort this result array so that the new result is [a,a,e,e]?
Any input will be appreciated, thank you in advance!

A:
Note: if what you're looking for is not sorting vowels lexically (in alphabetic order) but in the order of appearance, localeCompare() doesn't seem to be an appropriate tool. If I missed the whole point, you may safely ignore this answer.

To me, sorting is a way too expensive operation for this particular use case. I would rather think of it as filtering out vowels and stacking them in the order of appearance (where Map might come in handy).

const sourceString = 'Sample Case'

const isVowel = char =>
  'aeiouAEIOU'.includes(char)

const stackFilteredVowels = str => {
  const vowelsMap = [...str.toLowerCase()]
    .reduce((acc, char) => {
      const isCharVowel = isVowel(char)

      if(isCharVowel) {
        const vowelOccurence = acc.get(char)
        acc.set(char, (vowelOccurence || 0)+1)
      }

      return acc
    }, new Map)

  const stackedVowels = [...vowelsMap.entries()]
    .reduce((acc, [vowel, occurence]) =>
      (acc.push(...Array(occurence).fill(vowel)), acc), [])

  return stackedVowels
}

console.log(stackFilteredVowels(sourceString))
.as-console-wrapper{min-height: 100%;}

A: You could

*

*get all vowels,

*iterate the vowels,

*

*check if index for theis vowel exist, if not assign a new index and push an empty array to the result set vowels,

*push vowel to the according array,

*get flat array,

*return this array.

function orderVowels(string) {
    const
        indices = {},
        vowels = [];

    for (const v of string.match(/[aeiou]/ig)) {
        if (!(v in indices)) {
            indices[v] = vowels.length;
            vowels.push([]);
        }
        vowels[indices[v]].push(v);
    }
    return vowels.flat();
}

console.log(orderVowels("Sample Case"));

A: const isVowel = (c) => !c ? 'string is empty' : ['a', 'e', 'i', 'o', 'u'].includes(c);

const sortChar = () => {
   const wordsInput = "Input one line of word(s): ";
   const vowels = [...wordsInput].filter(char => isVowel(char) && char.match(/\w/));
   const consonants = [...wordsInput].filter(char => !isVowel(char) && char.match(/\w/));

   console.log({
      vowelsSorted: vowels.sort((a, b) => new Intl.Collator('en').compare(a, b)),
      consonantsSorted: consonants.sort((a, b) => new Intl.Collator('en').compare(a, b))
   })
}
   ;

sortChar();

A: Let's simplify this. Spread the string into an array and filter the consonants with isVowel. Sort using localeCompare

const isVowel = c => `aeiou`.indexOf((c || ``).toLowerCase()) > -1;
//                                    ^ use empty string if !c
const sortChar = words => {
    return [...words].filter( chr => isVowel(chr) )
//          ^ spread into array
//                   ^ filter delivers array
      .sort( (a, b) => a.localeCompare(b) )
//                       ^ sort using localeCompare
      .join(``);
};

console.log(sortChar(`As said: input one line of word(s)`));


text:
Q: How to insert image to mongodb via SimpleSchema How can I define a SimpleSchema template to store image data/binary data inside a mongodb storage.
What is the type I should use? Should I use Object type?

A: You can use Buffer type to store image.
But there is size limit of 16 MB for BSON-document so GridFS may help you to store files larger than 16 MB.

A: It's not always a good idea to store images or other files in MongoDB database(or any other database). Rather store them in a separate Storage server like AWS S3 or Azure blob storage or whatever storage server and keep the link to the file in your MongoDB database. It will help you keep the DB server lean.
For more details study on multi-tier application architecture.


text:
Q: python re.sub removes numeric characters palindrome I am trying to remove punctuation to check if a phrase (or word) is a palindrome, though when I have a word with numbers they are removed and it return True instead of False. "1a2" after cleaning punctuation with sub returns 'a' though it should still give me '1a2'. I thought I picked up only punctuation for substitution.
import re
def isPalindrome(s):
    clean = re.sub("[,.;@#?+^:%-=()!&$]", " ", s)
    lower = ''.join([i.lower() for i in clean.split()])
    if lower == lower[::-1]:
        return True
    else:
        return False

print(isPalindrome("1a2"))

A: You're using - inside your regex and you need to escape it correctly, try this instead:
re.sub("[,.;@#?+^:%\-=()!&$]", " ", s)

Have a look in the doc for a list of special characters and how to note a [].

A: Special characters must be escaped in your regex string. I.e.
clean = re.sub(r"[,\.;@\#\?\+\^:%\-=\(\)!\&\$]", " ", s)

or use re.escape, which automatically escapes special characters
esc = re.escape(r',.;@#?+^:%-=()!&$')
clean = re.sub("[" + esc + "]", " ", s)

A: I would use str.maketrans and the punctuation set from the string module in your case, because I think that this is more readable than a regex :
import string
s = s.translate(str.maketrans('', '', string.punctuation))


text:
Q: Overloading + and += operators in parent and child class in C++ Okay guys, this one has me confused not least because of how little info for this there is online...
Okay so lets say I have a parent and a child class as such:
   class ParentPlot
   {
      public:
         int a;
         int b;
         datacontainer Events;

         friend ParentPlot& operator+(ParentPlot& plotA, const ParentPlot& plotB)
         {
            //add stuff
            return sumPlot;
         }
         virtual ParentPlot operator+=(const ParentPlot &plotB)
         {
            //+= stuff using 'this'
            return *this;
         }
   }

   class ChildPlot: public ParentPlot
   {
      public:
         int q;

      friend ChildPlot& operator+(ChildPlot& plotA, const ChildPlot& plotB)
         {
             //Static cast and add the parents.
            ParentPlot PlotACast = static_cast<ParentPlot>(plotA); //2 Static casts
            ParentPlot PlotBCast = static_cast<ParentPlot>(plotB);
            ParentPlot ParentSum = PlotACast + PlotBCast; //Add as ParentPlots
            ChildPlot BasePlot = ChildPlot(ParentSum);

            //Add child members
            BasePlot.q = plotA.q + plotB.q;

            return BasePlot;
         }
      ChildPlot& operator+=(const ChildPlot& plotB)
      {
          //How do I correctly implement this?
      }
   }

How am I supposed to correctly manage the addition and += of these classes? Every combo seems to give errors of some kind and I cannot get this to work. For example the method implemented above gives the following error:
"too few parameters for this operator function"
I have tried making ParentPlot an abstract class and then just implementing in the child class but then the addition operator breaks because I can't return a parent in the addition operator.
Technically ParentPlot will be abstract but will have many children which will need to be summed, and it has multiple members. Should I not implement an addition operator or += for the parent and only the children or am I missing something? Genuinly no idea the correct way to handle this. Any ideas would be helpful...
Thanks

A: 1. Fix your operator return types.
operator + should return a copy. operator += should return a reference to this.
friend ParentPlot operator+(ParentPlot& plotA, const ParentPlot& plotB)
ParentPlot& operator+=(const ParentPlot &plotB)
friend ChildPlot operator+(ChildPlot& plotA, const ChildPlot& plotB)
ChildPlot& operator+=(const ChildPlot& plotB)

2. Implement your operator + using operator +=
This little trick is makes your code DRY and it will make it easier to implement those extra operators.
Note that first parameter is taken by value, we need a copy that will be modified by operator +=.
friend ParentPlot operator+(ParentPlot plotA, const ParentPlot& plotB)
{
    return plotA += plotB;
}

friend ChildPlot operator+(ChildPlot plotA, const ChildPlot& plotB)
{
    return plotA += plotB;
}

3. Implement child operator +=
Assuming that you already have operator += for ParentPlot, you can use it in two ways:
static_cast<ParentPlot&>(*this) += plotB;
//or
ParentPlot::operator+=(plotB);

Then you add child-specific implementation and return *this; as usual.
Full code (see it online):
class ParentPlot {
public:
    int a;
    int b;

    friend ParentPlot operator+(ParentPlot plotA, const ParentPlot& plotB)
    {
        return plotA += plotB;
    }
    ParentPlot& operator+=(const ParentPlot& plotB)
    {
        a += plotB.a;
        b += plotB.b;
        return *this;
    }
};

class ChildPlot : public ParentPlot {
public:
    int q;

    friend ChildPlot operator+(ChildPlot plotA, const ChildPlot& plotB)
    {
        return plotA += plotB;
    }
    ChildPlot& operator+=(const ChildPlot& plotB)
    {
        //static_cast<ParentPlot&>(*this) += plotB;
        ParentPlot::operator+=(plotB);
        q += plotB.q;
        return *this;
    }
};


text:
Q: How to get a list of duplicate objects out of another list? I have a list of objects FilteredItems. Each item has a Property NewFileName. I want now a new list, so that I can act on each object where the NewFileName is not unique. (I want to change another property of those objects)
I started to write a Linq query, I am able to group them by their NewFileName, but I am unsure on how to continue now. How can I filter now those where the group count is > 1?
Or am I on the wrong path and there is a completely different solution to get the objects that have not a unique NewFileName?
var result = from files in FilteredItems
             group files by files.newFileName;

foreach (var item in result) {
    item.NewFileNameUnique = false;
}

A: Each of your items in your foreach loop is a list of FilteredItem, you should check this list size is bigger than 1 or not, and if is, change all the values in this list:
var result = from files in FilteredItems
         group files by files.newFileName;

foreach (var item in result) {
    if (item.Count() > 1)
    {
       foreach(var fileDetail in item)
          fileDetail.NewFileNameUnique = false;
    }
}

Finally you can set your list by changed value as below:
FilteredItems = result.SelectMany(x=>x).ToList();

Edit:
I think should add something here, and that's linq is good for search query's but for updating something is not good, for example you can handle your problem simply with two for loop:
for(int i=0;i<FilteredItems.Count - 1;i++)
  for (int j=i+1;j<FilteredItems.Count;j++)
  {
      if (FilteredItems[i].newFileName == FilteredItems[j].newFileName)
      {
         FilteredItems[i].NewFileNameUnique = FilteredItems[j].NewFileNameUnique = false;
      }
  }

Which is more readable, Also you can do it faster by first sorting your list by their newFileName values and then check each item with its next/prev items (in O(n log n)).

A: You can also achieve this with a LinQ method chain. Group the list by the 'NewFileName' (GroupBy) and get only those who are not unique (Where) and with the SelectMany you put them in an IEnumerable. Afterwards loop the IEnumerable and set the NewFileNameUnique-property to 'false';
var duplicates = FilteredItems.GroupBy(i => i.NewFileName)
                              .Where(g => g.Count() > 1)
                              .SelectMany(r => r.ToList());

foreach(var item in duplicates)
    item.NewFileNameUnique = false;

Hope this helps!


text:
Q: Convert std::string number in hexadecimal number I have searched online, but it doesn't seem to be a solution to my problem. Basically I have a std::string which contains a hexadecimal memory address (like 0x10FD7F04, for example). This number is read from a text file and saved as a std::string, obviously.
I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?

A: You can use C++11 std::stoi function:
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string your_string_rep{"0x10FD7F04"};
    int int_rep = stoi(your_string_rep, 0, 16);
    std::cout << int_rep << '\n';
    std::cout << std::hex << std::showbase << int_rep << '\n';
}

Outputs:
285048580
0x10fd7f04

A:
I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?

There are two parts to your question:

*

*Convert the string hexadecimal representation to an integer.
std::string your_string_rep{ "0x10FD7F04" };
std::istringstream buffer{ your_string_rep };
int value = 0;
buffer >> std::hex >> value;

*Keeping the hex notation on the resulting value. This is not necessary/possible, because an int is already a hexadecimal value (and a decimal value and a binary value, depending on how you interpret it).
In other words, with the code above, you can just write:
    assert(value == 0x10FD7F04); // will evaluate to true (assertion passes)

A: Alternatively you can use something like this
std::string hexstring("0x10FD7F04");
int num;
sscanf( hexstring.data(), "%x", &num);


text:
Q: Smartsheet API - List sheets in a folder not implemented? I am using the Smartsheet 2.0 API with the C# SDK. I am trying to iterate through all of the sheets in folder. However, I am unable to find the API code to do so.
I tried FolderSheetResources interface, but a List() method isn't even implemented like on other interfaces; for example, WorkSpaceFolderResources.
smartsheetClient.WorkspaceResources.FolderResources.ListFolders() // Method exists.

smartsheetClient.FolderResources.SheetResources.ListSheets(); // Method doesn't exist.

And I have also tried the Sheets property of the Folder object.
folder.Sheets; // Always returns null.

Does anyone know how to list all sheets inside a folder?

A: Call getFolder on the specific folder you're looking at.
Folder folder = smartsheet.FolderResources.GetFolder(
  7116448184199044,           // long folderId
  null                        // IEnumerable<FolderInclusion> include
);

Once you have this Folder object, you can take a look at the Sheets array property.
The API Docs will give you more information about what else is present.


text:
Q: Ajuda Formulário PHP Tenho o seguinte código:
<?php

// Do not edit this if you are not familiar with php
error_reporting (E_ALL ^ E_NOTICE);
$post = (!empty($_POST)) ? true : false;
if($post) {
    function ValidateEmail($email){

        $regex = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
        $eregi = preg_replace($regex,'', trim($email));

        return empty($eregi) ? true : false;
    }

    $name = stripslashes($_POST['ContactName']);
    $to = trim($_POST['to']);
    $email = strtolower(trim($_POST['ContactEmail']));
    $subject = stripslashes($_POST['subject']);
    $message = stripslashes($_POST['ContactComment']);
    $error = '';
    $Reply=$to;
    $from=$to;

    // Check Name Field
    if(!$name) {
        $error .= 'Please enter your name.
';
    }

    // Checks Email Field
    if(!$email) {
        $error .= 'Please enter an e-mail address.
';
    }
    if($email && !ValidateEmail($email)) {
        $error .= 'Please enter a valid e-mail address.
';
    }

    // Checks Subject Field
    if(!$subject) {
        $error .= 'Please enter your subject.
';
    }

    // Checks Message (length)
    if(!$message || strlen($message) < 3) {
        $error .= "Please enter your message. It should have at least 5 characters.
";
    }

    // Let's send the email.
    if(!$error) {
        $messages="From: $email
";
        $messages.="Name: $name
";
        $messages.="Email: $email
";
        $messages.="Message: $message

";
        $emailto=$to;

        $mail = mail($emailto,$subject,$messages,"from: $from <$Reply>\nReply-To: $Reply \nContent-type: text/html");

        if($mail) {
            echo 'success';
        }
    } else {
        echo '
'.$error.'
';
    }

}
?>

Alguém sabe me dizer onde eu devo entrar com o meu endereço de e-mail para receber os dados deste formulário?

A: Vejo que não conhece bem a função mail do php
mail(string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]]);

$to = Receptor do email em questão
No seu código $emailto=$to; refere-se ao receptor, $toestá vindo da $_POST de outro formulário

Alguém sabe me dizer onde eu devo entrar com o meu endereço de e-mail para receber os dados deste formulário?

Você pode enviar uma cópia para você colocando o seu email como um dos destinatários:
$to=trim($_POST['to']).',';
$to.='seu@email.com';

Ou pode alterar para enviar apenas para o seu email, neste caso seria interessante retirar a input[name='to'] do formulário que envia informações para este email
$to='seu@email.com';

Simplesmente alterando a linha 16 do seu código


text:
Q: Trying to list movies on my database in an embed It works when i console.log the result[0], but don't add into my embed
var usuarioDB = new Discord.User();
          usuarioDB = message.author;
          // Añadir Clave primaria y campo único
          var row = 0;
          var sql = 'SELECT count(id_estado) as NºFilas from estado;';
          pool.query(sql, function (err, result) {
            var TotalRows = result[0].NºFilas - 1;
            const PelisLista = new Discord.RichEmbed()
            .setTitle("Peliculas Pendientes")
            .setColor(`${cfg.color}`);
            for (row = 0; row < TotalRows; row++) {
              var SQLIST = `SELECT Nombre_Pelicula, FechaAdición from peliculas join estado on estado.id_pelicula = peliculas.id_pelicula where estado like 'Pendiente' order by Nombre_Pelicula desc LIMIT ${row}, 1;`;
              pool.query(SQLIST, function (err, resultPelis) {
                if (err) throw err;
                console.log("\nListing Movies\n\n");
                console.log(resultPelis[0].Nombre_Pelicula);
                console.log(resultPelis[0].FechaAdición);
                PelisLista.addField(':cinema:', `${resultPelis[0].Nombre_Pelicula}`, true)
                PelisLista.addField(':date:', `${resultPelis[0].FechaAdición}`)
                PelisLista.addBlankField()
              });
            }
            PelisLista.addBlankField();
            message.channel.send(PelisLista);
          })

EDIT: I solved it, changed te way to do it
var usuarioDB = new Discord.User();

        const PelisLista = new Discord.RichEmbed()
          .setTitle("Peliculas Pendientes")
          .setColor(`${cfg.color}`);
        var SQLIST = `SELECT Nombre_Pelicula, FechaAdición, estado from peliculas join estado on estado.id_pelicula = peliculas.id_pelicula where estado like 'Pendiente' or estado like 'Viendo' order by Nombre_Pelicula;`;
        pool.query(SQLIST, function (err, resultPelis) {
          if (err) throw err;
          resultPelis.forEach(element => {
            console.log("\nListing Movies\n\n");
            if (element.estado === 'Pendiente') {
              PelisLista.addField(`${element.Nombre_Pelicula}`, `${element.FechaAdición}`);
            } else {
              PelisLista.addField(`${element.Nombre_Pelicula} *(Seleccionada)*`, `${element.FechaAdición}`);
            }

          });  //(entry => {});
          message.channel.send(PelisLista);
        });

The code above returns this embed. But logs this in console
Have to say that i'm so new to programming, more to discord.js.
Thanks you in advance

A: I'm not sure exactly what your question is about, but try to change NºFilas for No_Filas, since some editors have problems with non-letters symbols.


text:
Q: data-bind foreach for an observable number I am trying to display stars for each item in a list
I have an interface that has the 5-star score on a video, how do I do a foreach for the count of that score? rather than creating an array for the score?
interface Video{
    Score: number;
}

A: You could either use Array.from() or the Array(score) to create an array from the score
Array.from({ length: score })

or
[...Array(score)]

(Use score() if it's an observable)
Here's a minimal snippet:

const model = {
  score: 3
}

ko.applyBindings(model)

   *