text:
Q: Array out of bounds error when trying to save attachments in vba/sql I managed to get the code to save the attachment, but now I have put some conditions on it I keep getting array out of bounds error. I did have the attachments.item as (x) but my co-worker advised this wouldn't work. I thought I'd ask the experts anyway.
When I run it in debug mode attachments.item(x) goes from 1 straight to 820.
Here is a fragment of my code:
For i = 1 To EmailCount
    With ObjParentFolder.Items(i)
    If .MessageClass = "IPM.Note" And .ReceivedTime >= teste Then
        Found = False
        If PreviousRex = True Then
            For x = 0 To RexCnt
                If .SenderName = Data(x).Sender And .ReceivedTime = Data(x).Received Then
                    Found = True
                End If
            Next x
        End If
        If Found = False Then
                    rex.AddNew
                        rex.Fields("MailItemPath") = ObjParentFolder.Name
                        rex.Fields("ReceivedTime") = .ReceivedTime
                        rex.Fields("MailDate") = DateValue(.ReceivedTime)
                        rex.Fields("MailHour") = Left(TimeValue(.ReceivedTime), 2)
                        rex.Fields("Subject") = .Subject
                        rex.Fields("SenderName") = .SenderName
                        rex.Fields("MSGBody") = .Body
                        rex.Fields("Last_Updated") = Now
                        rex.Fields("Updated_By") = UCase(CurrentUserName())
                        rex.Fields("new") = True
                        rex.Fields("W_ID") = prop & rex.Fields("ID")
                        TmpID = rex.Fields("W_ID")
                    rex.Update

        End If

        'If .Attachments.Count > 0 Then
        '   For p = 1 To .Attachments.Count
        '       Select Case Right(.Attachments.Item(p).Filename, 4)
        '           Case ".xls"
        '               .Attachments.Item(p).SaveAsFile (ThisWorkbook.Path & "\attachments" & "_" & TmpID & "_" & .Attachments.Item(p).Filename)
        '          Case ".zip"
        '                .Attachments.Item(p).SaveAsFile (ThisWorkbook.Path & "\attachments" & "_" & TmpID & "_" & .Attachments.Item(p).Filename)
        '            Case ".doc"
        '                .Attachments.Item(p).SaveAsFile (ThisWorkbook.Path & "\attachments" & "_" & TmpID & "_" & .Attachments.Item(p).Filename)
        '            Case Else
        '                .Attachments.Item(p).Delete
        '       End Select
        '   Next p
        'End If
    End If
End With

Next i

A: You are deleting attachments in the loop, thus changing the total count. Use a down loop:
For p = .Attachments.Count to 1 step -1

It is also a good idea to avoid using multiple dot notation. Cache the attachments collection before entering the loop and retrieve the attachment only once
dim attachments
dim attach
set attachments = .Attachments
If attachments.Count > 0 Then
       For p = .Attachments.Count to 1 step -1
           set attach = attachments.Item(p)
           Select Case Right(attach.Filename, 4)
               Case ".xls"
                   attach.SaveAsFile (ThisWorkbook.Path & "\attachments" & "_" & TmpID & "_" & attach.Filename)
              Case ".zip"
                    attach.SaveAsFile (ThisWorkbook.Path & "\attachments" & "_" & TmpID & "_" & attach.Filename)
                Case ".doc"
                    attach.SaveAsFile (ThisWorkbook.Path & "\attachments" & "_" & TmpID & "_" & attach.Filename)
                Case Else
                    attach.Delete
           End Select
       Next p
    End If


text:
Q: Getting python's itertools cycle current element I know you can use c = cycle(['a', 'b', 'c']) to cycle between the elements using c.next(), but is there away to get the iterator's current element?
for example if c.next() returned 'c', it means that iterator was at 'b' before. Is there a way I can get 'b' without using next()?

A: Iterators/generators don't have any way to get the current value. You should either keep a reference to it or create some wrapper that holds onto it for you.

A: Note: This only works if there are no repeated elements.
Whether this is a serious practical limitation depends on each one's use.
In my case, most of the itertools.cycle I have worked with fall under this category.
One can actually get the current state of a cycle with a helper function, and other info as well.
It actually uses next, but this is transparent to the caller.
import itertools

def get_cycle_props(cycle) :
    """Get the properties (elements, length, current state) of a cycle, without advancing it"""
    # Get the current state
    partial = []
    n = 0
    g = next(cycle)
    while ( g not in partial ) :
        partial.append(g)
        g = next(cycle)
        n += 1
    # Cycle until the "current" (now previous) state
    for i in range(n-1) :
        g = next(cycle)
    return (partial, n, partial[0])

def get_cycle_list(cycle) :
    """Get the elements of a cycle, without advancing it"""
    return get_cycle_props(cycle)[0]

def get_cycle_state(cycle) :
    """Get the current state of a cycle, without advancing it"""
    return get_cycle_props(cycle)[2]

def get_cycle_len(cycle) :
    """Get the length of a cycle, without advancing it"""
    return get_cycle_props(cycle)[1]

# initialize list
test_list = [3, 4, 5, 7, 1]
c = itertools.cycle(test_list)
print('cycle state =', get_cycle_state(c))
print('cycle length =', get_cycle_len(c))
print('cycle list =', get_cycle_list(c))
next(c)
print('cycle state =', get_cycle_state(c))
print('cycle length =', get_cycle_len(c))
print('cycle list =', get_cycle_list(c))

produces the following output
cycle state = 3
cycle length = 5
cycle list = [3, 4, 5, 7, 1]
cycle state = 4
cycle length = 5
cycle list = [4, 5, 7, 1, 3]

This can actually be taken advantage of to "rewind" a cycle, with the function
def shift_cycle(cycle, npos=0) :
    """Shift a cycle, a given number of positions (can be negative)."""
    (cycle_list, nelem, curr_state) = get_cycle_props(cycle)
    for i in range(nelem+npos) :
        g = next(cycle)
    return

Try
shift_cycle(c, -2)
print('cycle state =', get_cycle_state(c))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Anaconda3 PATH variable issue on Windows 10 I installed Anaconda3 in the default directory : C:\Users\MyUserName
When I am launching Spyder or Anaconda Navigator, Qt is not founded :

Furthermore, conda is not recognized by default in the Anaconda Prompt.

However,conda is recognized if I specify the directory.

It all seems like a PATH variable issue. The thing is, I have created a list of PATH variables in the windows variable manager (My PC -> Properties -> Advanced ...) . I tried a few paths, but it still doesn't work.

Am I missing a PATH variable ?

A: Can you please also add the following paths:
C:\Users...\Anaconda3\bin
C:\Users...\Anaconda3\condabin
and check if you gain access to the conda command?

A: I uninstalled Anaconda3, removed all PATH variables related to Anaconda, and reinstalled it with admin privileges on C:\ProgramData.
The problem was the 'è' character in my user name.


text:
Q: Show results of fgetc as character on screen I am trying to debug the following code:
int check_file(FILE* file)
{
  int c;
  int nl = '\n';

  while((c = fgetc(file)) != EOF)
  {
      if (c == nl) return 0;
  }

  printf("\n ERROR EOF \n");
  return 1;

}

when it gets error and returns 1, I would like to know the reason.
I thought about printing on screen the character read in the variable "c", before I get the error (so I can understand in which part of the read file is the error located) but this is an integer.
Is it possible somehow to print in on screen as character?
Thanks

A: printf("%c\n", c);

A: You don't know you are getting an error.  Most likely, you are just reaching the end of the file.  You should call feof() or ferror() to determine why fgetc() is returning no more data.

A: Your loop is terminating on End Of File (EOF), and, while you can print the character read before it, that generally won't help you.  If you want to do something different at EOF, do that.  In other words: if EOF is an error, then "in which part of the file" is always at the end.
To get a character from an integer, use (char)some_int, and to output a character, use [f]putc or printf("%c", some_int).

A: putc and fputc both take an integer argument.


text:
Q: Repeat and insert directives I have 3 different directives, <one>, <two>, <three>.
I want to loop through their ids and insert them in an ng-repeat

        <panel>

        </panel>

The resulting html I would like to achieve then would be:

        <panel>
            <one></one>
        </panel>

        <panel>
            <two></two>
        </panel>

        <panel>
            <three></three>
        </panel>

And since each has its template:

I am not sure how to do this? Is this possible? do I have to ng-compile to have a directive inside a directive?
Should I use just one directive and use an ng-switch?
Am I missing a more straightforward approach?
I know this works:
make a <panel-content> directive.
I include this on the <panel> directive:
make an
<ng-switch="panel.id">
    <ng-switch-when="one">
    <ng-switch-when="twp">
    <ng-switch-when="three">
</ng-switch>`

But it seems cumbersome.

A: The way that I normally do this is use one directive that picks the specific directive in the link function. That prevents all of the ng-switch bloat.
html
<panel type='one'></panel>
<panel type='two'></panel>

js
angular.module('app').directive('panel', ['$compile', '$injector', function ($compile, $injector) {
    return {
        restrict: 'E',
        scope: {
            type: '='
        },
        link: function ($scope, element, attrs, vm) {
            var template;
            switch($scope.type){
                case 'one':
                    template = '<one></one>';
                    break;
                case 'two':
                    template = '<two></two>';
                    break;
            }
            element.html(template);
            $compile(element.contents())($scope);
        }
    };
}]);

Here's a fiddle showing this in action: http://jsfiddle.net/7cufjqs3/1/

A: If you're willing to live with an extra div between your directive and panel element I created a dynamic directive that knows nothing about the name of the element, and creates it dynamically:
Usage:

    <panel>
       <dynamic-directive element="panel.id"></dynamic-directive>
    </panel>

Directive:
myApp.directive('dynamicDirective', function($compile) {
    return {
        restrict: "E",
        replace: true,
        template: "

",
        scope: {
            element: "="
        },

        link: function(scope, element, attrs) {
            var elm = '<' + scope.element + '></' + scope.element + '>';
            element.html(elm);
            $compile(element.contents())(scope);
        }
    }
});

Fiddle

A: I think a the switch is the best approach because it's most readable in your html

        <panel ng-switch on="panel.id">

<one>1</one>

<two>2</two>

<three>3</three>

        </panel>

http://plnkr.co/edit/ygy6coKCyQNGBoKmSES0?p=preview


text:
Q: Ruby: How can I write a digest to a file in binary format I need to store a Digest::SHA512 object to a file in binary format.
That seemed trivial, but whatever I try just write it as an hexadecimal string.
I was expecting the following code to work:
bindigest=digest.update(chall)
File.open('sha1.bin', 'wb') {|file| file.write(bindigest) }

but it does not: it convert to plain text.
A similar question seems unanswered:
Can I serialize a ruby Digest::SHA1 instance object?
Using unpack tools require translating a bigint into a binary string, which again is not trivial...
Any suggestion?
Thank you in advance!

A: The to_s method of Digest returns the hexadecimal encoding of the hash, so this is what you get by default when trying to output it (since Ruby will use to_s when writing). To get the raw binary, use digest:
digest = Digest::SHA512.new
digest.update(chall)
File.open('sha1.bin', 'wb') { |file| file.write(digest.digest) }

Alternatively you could use the class method version of digest if you're not calculating the hash in chunks:
digest = Digest::SHA512.digest(chall)
File.open('sha1.bin', 'wb') { |file| file.write(digest) }


text:
Q: How to disable pickTime bootstrap dateTimePicker I want to disable the time choice with bootstrap-datetimepicker.
This is my JavaScript:
$('.dateTimePicker2').datetimepicker({
    language: "fr",
    pickTime: false,
});

I know that there are different datetimepicker plugins. I use smalot/bootstrap-datetimepicker. Even if I set pickTime to false, it doesn't work? Any idea?

A: You can use format and minView option, setting format: "yyyy-mm-dd" and minView: "month". The format option determines the format to show in the input while the minView option is the lowest view that the datetimepicker should show.
Here a working sample:

$('.dateTimePicker2').datetimepicker({
    format: "yyyy-mm-dd",
    minView: "month",
    language: "fr"
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/smalot-bootstrap-datetimepicker/2.4.4/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/smalot-bootstrap-datetimepicker/2.4.4/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/smalot-bootstrap-datetimepicker/2.4.4/js/locales/bootstrap-datetimepicker.fr.js"></script>

<input size="16" type="text" readonly class="dateTimePicker2">


text:
Q: Cutoff point detection question Suppose I have two methods $A$ and $B$ that can be used to measure the value $y$ for an outcome variable given the value of an explanatory value $x$.
The following figure shows the scatter-plot of the difference between $y$ values from those two methods ($y_B - y_A$) against $x$ based on one experiment.

Method $A$ is the gold-standard approach, so the outcome values it produces are regarded as true values. But this method is more complicated and expensive as compared to method $B$. On the other hand, method $B$ is sort of an approximation, and might be not statistically accurate as compared to method $A$. Therefore, the collaborators wish to know within which range of $x$ that method $B$ can be used as surrogate to measure the outcome. Suppose that we wish to have that range as wide as possible. Due to the nature of the problem, $x$ is randomly distributed in the range [0, 0.2]. Out of that range, the outcome is not meaningful nor measurable.
Based on the plot, we can clearly see method $B$ produced positively biased outcome values at small $x$. The smaller $x$ is, the large is the bias. And it seems that within range [0.1, 0.2] of $x$, Method $B$ does a good job.
To quantitatively find the cut-off, suppose I pick a cut-off point $c$, and take data in the range $[c, 0.2]$ and do a paired-t test of the $y$ values. If I don't observe significance. Could I then conclude that method $B$ is applicable in this range?
My concerns about it is that the insignificance may be due to the cancellation of the positive bias at lower end and the negative bias at the upper end, which may not imply method $B$ is accurate enough. Should this still be a concern if $X$ is randomly distributed in the range? Statistically speaking, what would be a more rigorous approach to address this question?


text:
Q: Displaying information on Jpanel I am new to this action command and action listener (mouse pressed) event. i used this in my code:
// This is the single event handler for all the buttons
public void actionPerformed(ActionEvent e) {
JButton selectedBtn = (JButton) e.getSource();

for (int row = 0; row < buttons.length; row++) {
  for (int col = 0; col < buttons[row].length; col++) {
    if (buttons[row][col] == selectedBtn) {
       moves++; //incrementing the moves
       System.out.printf("moves: %d%n", moves);
       System.out.printf("Selected row: %d%n", row+1);
       System.out.printf("Selected column: %d%n", col+1);

     }
   }
 }

this piece of code is displaying the rows and columns of the button pressed correctly. but what i'm trying to do is that i'm trying to display this information in front of my Jlabels.
i.e if a button is pressed and it lies on a row 2 and column 4 it should show it like this :

instead it shows as this in the output console :
moves: 1
Selected row: 3
Selected column: 4

any ideas on how do I amend these Jlabels so this information displays on them?
these are my Jlabels
//labels
JLabel label1 = new JLabel("COL: ");
label1.setLocation(10,260);
label1.setSize(100,100);
add(label1);

JLabel label2 = new JLabel("ROW: ");
label2.setLocation(10,280);
label2.setSize(100,100);
add(label2);

any help will be appreciated :)

A: Try using setText() on the instance of JLabel.


text:
Q: Migrating to Identity AspNetUsers I added Identity in my new MVC project, I have DB that have basic Account, Customers etc. tables that are used in WPF app. It all works now, registered users are added in AspNetUsers table... But my DB is useless.
Now I have 1000 Accounts with Id that is auto increment integer, MobileNumber and Passwords. How can I migrate all that in AspNetUsers, or better can I switch to my table and not use AspNetUsers table with String as Id because my other tables work with Account table?

A: Considering that your's isn't a very general case, I don't see how Identity will have a direct solution. You can always use queries to migrate the data from Account to AspNetUsers. Mainly the password and MobileNumber (to username). Once moved, you can use ApplicationUser class to override any properties. I usually do something like this:
[MaxLength(36)]
public override string Id { get; set; }

Although the Id is still a string, it is a smaller string. If you really want to change this pk into a link, there is officially a long way provided https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-primary-key-configuration?tabs=aspnetcore2x
If you are worried about all your foreign keys being strings, a simple way would be to set up an in-between model something like this:
public class UserIdentity
{
    public int ID { get; set; }

    public int ApplicationUserID { get; set; }
    public ApplicationUser ApplicationUser { get; set; }

}

However, do keep in mind that this will have an additional join each time user details need to be verified.
Update
Considering that you already have a table Account with a primary key that is already used in other tables, you can also update your account Account.
public class Account
{
    ...
    public int ApplicationUserID { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

This way you can continue to use Account's fk


text:
Q: ExpandableListView shows only one groupView and no childView I'm a newbie in Android. I want to show my records in a database using an expandable list view, so that records of the same day form a group. I want something like this:
day 1
-------------------
record 1 of day 1
record 2 of day 1

day 2
-------------------
record 1 of day 2
record 2 of day 2
record 3 of day 2
...

But what I get is this:
day 1
-------------------

Only one record is showing as the group view, and when I expand it, nothing shows as a child.
FirstFragment.java:
public class FirstFragment extends Fragment {

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        createExpandableListView();

    }

    private void createExpandableListView() {
        String time = Long.toString(((ShowBillBookActivity)getActivity()).book.getTime().getTimeInMillis());
        BillTableHandler handler = new BillTableHandler(getActivity(),
            ((MyApplication) getActivity().getApplication()).BILL_TABLE_NAME_PREFIX + time);
        ExpandableListView view =  (ExpandableListView) getView().findViewById(R.id.expandableListView);
        Cursor c = handler.getAllBills();
        Log.d("tag", "handler.getAllbills(): "+c.getCount());
        ExpandableListAdapter adapter = new ExpandableListAdapter(handler,
            this.getActivity(),
            handler.getAllBills(),
            R.layout.group_expandable_list_view,
            new String[]{BillEntry.DAY, BillEntry.AMOUNT},
            new int[]{R.id.textview_time, R.id.textview_extra},
            R.layout.child_expandable_list_view,
            new String[]{BillEntry.PAYER, BillEntry.AMOUNT},
            new int[]{R.id.textview_payer, R.id.textview_amount});
        view.setAdapter(adapter);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
}

ExpandableListAdapter.java
public class ExpandableListAdapter extends SimpleCursorTreeAdapter {
    BillTableHandler handler;

    public ExpandableListAdapter(BillTableHandler handler, Context context, Cursor cursor, int groupLayout,
                             String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom,
                             int[] childTo){
        super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom, childTo);
        this.handler = handler;
    }

    @Override
    protected Cursor getChildrenCursor(Cursor groupCursor) {
        long time = groupCursor.getLong(groupCursor.getColumnIndexOrThrow(BillTableHandler.BillEntry.DAY));
        Cursor c = handler.getBillsOfTime(time);
        Log.d("tag","child Count : "+c.getCount());
        c.moveToFirst();
        return c;
    }
}

group_expandable_list_view.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/textview_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:text="TextView"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textview_extra"
    android:layout_width="61dp"
    android:layout_height="18dp"
    android:text="TextView"
    app:layout_constraintLeft_toRightOf="@+id/textview_time"
    android:layout_marginLeft="32dp"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp" />
</android.support.constraint.ConstraintLayout>

child_expandable_list_view.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:focusable="false"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/textview_payer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:text="hello"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textview_amount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="8dp"
    android:text="world"
    app:layout_constraintLeft_toRightOf="@+id/textview_payer"
    app:layout_constraintTop_toTopOf="parent" />
<TextView
    android:id="@+id/textView5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:text="text"
    app:layout_constraintTop_toBottomOf="@+id/textview_amount"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>

I've been working on this for about a week and am getting pretty desperate. So please, any suggestion is welcome.

A: It's working now. The reason is that in the fragment layout, the ExpandableListView is nested in a ScrollView. Apparently, this is not good practice, because the size of ExpandableListView could not be correctly calculated (for more explanations see this blog, unfortunately partly in Chinese). This way, you'll find that getChildView() of the base SimpleCursorTreeAdapter never gets called. That's why the child view never gets rendered.
Solution:

*

*Get rid of ScrollView, just  ExpandableListView will work fine. Or

*Extend ExpandableListView as this answer does, if you have to have it nested under ScrollView.


text:
Q: Remove item from jquery mobile listview? Is there a way to remove an item from a jquery mobile listview without having to repopulate the whole listview?

A: using jQuery....
$('#id').remove();

i think this link can help you..
also, this for jQuery mobile.
Here is the demo for jQuery mobile...


text:
Q: C# - Get Operating System from IP address / DNS Name We are writing an app that will manage servers and I need to be able to see what Operating System is running on any remote machine within the network.
We will not always have credentials to view this information, so WMI is not a solution.
All I need to know, is it running Windows, Linux, or other. And what is the version of the OS.
Currently we are getting this info from the databases on these servers. But I'd like to do this without asking a database.
Is it possible to get this information if I only have the IP address or DNS name? No credentials. A C#/.Net Core solution would be ideal. Or any protocols that would achieve this would also work, I'll convert it into C#.
Conclusion
So depending on what is available and what is not, here are the options brought forward.

*

*If you have an admin account on the remote machine, WMI is the best approach. Example on learn.microsoft.com here

*If you have access to a database like SQL, you can query SQL to return the OS information. This wil very from DB to DB and from version to version. So research is essential.

*Using something like nmap will get you the OS using port fingerprinting. This isn't always accurate and will depend on your server security and setup. Thanks to @MindSwipe and @BlackSpy

*Using an agent to send this information is also a possibility, and would be a good approach, but this requires some overheads which can be avoided with the proper setup. Thanks @BlackSpy and @Clint

A: What you are doing is similar to a CMDB inventory scan, and there are different strategies for windows and linux. For starters, decide on whether to go agent or agent-less.
If you go the agent route, then write a small .net application that exposes a port to query and provide an OS specific implementation for both. Then get you IT department to install it on everything.
Agent-less is a bit more tricky. Start by looking for ports that should be open for management functions (WinRM on Windows - though be careful here - it's turned off by default, SSH on Linux), or any services you know your IT department provision by default (hopefully on their base VM images). If WinRM/SSH is enabled, and you have password store you can programatically query, then you can perform remote logins and run any code you need to extract any further information. As you say you don't have the passwords, the best you can do is guess based on exposed ports.

A: You can leverage the UserAgent string
From MSDN Doc:

When you request a webpage, your browser sends a number of headers to
  the server hosting the site that you're visiting, as shown here.

GET / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Proxy-Connection: Keep-Alive
Host: microsoft.com

The Platform Token will describe your OS (also in the link)
You can query like this
 String ua = Request.UserAgent;
 if (ua.Contains("Windows NT 10"))
     return "Windows 10";
 else if (ua.Contains("Linux"))
     return "Linux"

Link : https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/ms537503(v=vs.85)?redirectedfrom=MSDN
OR
Request.Headers["User-Agent"].ToString();


text:
Q: StackExchange.Redis.RedisTimeoutException occuring Frequently we are using Elastic cache redis that aws provides in our .Net Core application and when we perform the below operation sometimes we are getting the below TimeoutException after sometime can someone please help me to solve this attaching exception for reference
_redis.KeyExists("cusID"+customerID) -> operation performed
Exception has occurred: CLR/StackExchange.Redis.RedisTimeoutException
Exception thrown: 'StackExchange.Redis.RedisTimeoutException' in StackExchange.Redis.dll: 'Timeout performing EXISTS (5000ms), next: EXISTS cusID1, inst: 0, qu: 0, qs: 0, aw: False, bw: SpinningDown, rs: ReadAsync, ws: Idle, in: 0, serverEndpoint: master.test-stage-test-new-jayaram3.mvg9d6.aps1.cache.amazonaws.com:6379, mc: 1/1/0, mgr: 10 of 10 available, clientName: JAYA-397(SE.Redis-v2.5.61.22961), IOCP: (Busy=0,Free=10000,Min=10000,Max=10000), WORKER: (Busy=2,Free=32765,Min=10000,Max=32767), POOL: (Threads=13,QueuedItems=0,CompletedItems=790), v: 2.5.61.22961 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts)'
at StackExchange.Redis.ConnectionMultiplexer.ExecuteSyncImpl[T](Message message, ResultProcessor1 processor, ServerEndPoint server) in /_/src/StackExchange.Redis/ConnectionMultiplexer.cs:line 1857 at StackExchange.Redis.RedisBase.ExecuteSync[T](Message message, ResultProcessor1 processor, ServerEndPoint server) in //src/StackExchange.Redis/RedisBase.cs:line 53
at StackExchange.Redis.RedisDatabase.KeyExists(RedisKey key, CommandFlags flags) in //src/StackExchange.Redis/RedisDatabase.cs:line 667
An exception of type 'StackExchange.Redis.RedisTimeoutException' occurred in StackExchange.Redis.dll but was not handled in user code: 'Timeout performing GET (5000ms), active: GET cusID1, next: GET cusID1 ** possible thread-theft indicated; see https://stackexchange.github.io/StackExchange.Redis/ThreadTheft ** , inst: 1, qu: 0, qs: 0, aw: False, bw: SpinningDown, rs: CompletePendingMessageSync, ws: Idle, in: 0, serverEndpoint: master.suremdm-stage-test-new-jayaram3.mvg9d5.aps1.cache.amazonaws.com:6379, mc: 1/1/0, mgr: 8 of 10 available, clientName: JAYA-397(SE.Redis-v2.5.61.22961), IOCP: (Busy=3,Free=9997,Min=10000,Max=10000), WORKER: (Busy=5,Free=32762,Min=10000,Max=32767), POOL: (Threads=12,QueuedItems=0,CompletedItems=2634), v: 2.5.61.22961 (Please take a look at this article for some common client-side issues that can cause timeouts: https://stackexchange.github.io/StackExchange.Redis/Timeouts)'
If need some more information, just ask me that I'll try to provide. Thanks in advance.

A: Are you setting "AbortOnConnectFail" to false so it continues to try to reconnect? When a connection breaks (could be due to a failover etc), commands already sent to Redis on the now broken connection will timeout on the client.


text:
Q: How to retrieve a list of public Google Docs from one user Is there a way to retrieve a JSON or XML resource from Google Docs using an HTTP GET? I want to list public-only docs belonging to me on a web page, so the user viewing the web page should not need authentication or even to have a Google account.
I can do this easily in the Blogger API.
https://www.googleapis.com/blogger/v3/blogs/blogId/posts
Don't really care the method (writing in PHP) for retrieving the data, but I want it to happen server side and it should not require authentication by the user.
Have I missed something?

A: You can use the Google Documents List API. I believe it only requires auth for non-public data retrieval.


text:
Q: ¿Cómo puedo hacer para descargarme archivos de una fecha específica con OpenSSH? mi problema es el siguiente:
Tengo un sitio web, y hubo un problema y se borraron archivos. No tengo yo almacenado en mi PC los archivos esos (ya que fueron agregados hace unos meses, y no hice en su momento un nuevo backup de la carpeta que los contenía). Consulté al servicio técnico del hosting que tengo contratado, y para poder acceder al contenido de los backups realizados en el servidor, me dijeron que puede ser sólo mediante ssh (ya que el panel de configuración del hosting tiene la posibilidad de recuperar backups, pero no de ver su contenido antes de hacerlo, y necesito ver el contenido antes para no cometer un error), es decir, sólo puedo hacerlo descargándome los archivos del servidor a mi PC mediante ssh. Sin embargo ellos no me ofrecen ayuda con ssh por ser un servicio externo a ellos.
Lo que necesito es saber si es posible descargarme archivos de una fecha específica, y en ese caso, cómo hacerlo.
Y si no, si alguien me podría facilitar documentación (si es posible, en Español, y si no, en Inglés) lo agradecería, ya que tampoco estoy logrando encontrar documentación completa que me ayude a entender cómo, por ejemplo, descargarme un directorio completo.
El servidor es Linux, y mi computadora tiene Windows 7 (sin posibilidad de actualizar el SO actualmente). El servidor contratado es Donweb, y el panel de control que utilizan es Ferozo.


text:
Q: Post data on slack channel I am using shell script to find the tps and error count in a single day using shell script and store the data in a txt file.
Now i want to use the same shell script to post data form that result file onto a slack group, but sometimes command gives bad request, sometimes Invalid Payload and sometimes it works.
curl -X -POST -H --silent --data-urlencode "payload={\"text\": \"$(cat <filepath>/filename.txt)\"}" "<slack url>"

Please help


text:
Q: Which of 3 classes does the model.predict() output corresponds to? When i load a trained model and feed it with new data to predict (model.predict(textstr)) i get:
[[0.3345264  0.33339804 0.33207548]]

The model was trained with a dataframe that looks like:
                text  sent
1     Textstring1...     1
2     Textstring2...     2
3     Textstring3...     0
4     Textstring4...     0
5     Textstring5...     2

How can i tell which class (sent, train value) corresponds to the output i get? Does the 0.3345264 value above corresponds to sent 0 as an answer from the model?
Here are some details of the model and its configuration:
 model = tf.keras.Sequential([
            tf.keras.layers.Embedding(VOC, EMB_SIZE),
            tf.keras.layers.GlobalAveragePooling1D(),
            tf.keras.layers.Dense(node1,activation='relu'),
            tf.keras.layers.Dropout(dropout),
            tf.keras.layers.Dense(3, activation='softmax')])

 model.compile(optimizer='adadelta',
              loss='sparse_categorical_crossentropy',
              metrics=['sparse_categorical_accuracy'])

Thanks in advance.
Update Edit2:
I used tokenizer like so to create train_seqs:
      tokenizer = tf.keras.preprocessing.text.Tokenizer(
            num_words=WORDS
          , oov_token='<UNK>')
        tokenizer.fit_on_texts(train_df['text'])

    #convert text data to numerical indexes
        train_seqs=tokenizer.texts_to_sequences(train_df['text'])
        test_seqs=tokenizer.texts_to_sequences(test_df['text'])

#pad data up to SEQ_LEN (note that we truncate if there are more than SEQ_LEN tokens)
    train_seqs=tf.keras.preprocessing.sequence.pad_sequences(
       train_seqs
       , maxlen=SEQ_LEN
       , padding="post")
    test_seqs=tf.keras.preprocessing.sequence.pad_sequences(
       test_seqs
       , maxlen=SEQ_LEN
       , padding="post")

train_seqs
Out[12]:
array([[ 144,    8,   46, ...,   42,    3, 1734],
       [   6,  315,  277, ...,   44, 2247, 2095],
       [   5,   18,  162, ...,  159,   56, 1483],
       ...,
       [   9,  132,   76, ...,  194,  234, 1628],
       [ 660,   66,    7, ...,    0,    0,    0],
       [ 514,  879,  126, ...,    6,   68,  590]], dtype=int32)

train_df['sent'].values
Out[13]: array([1, 0, 2, ..., 0, 1, 0])

history = model.fit(train_seqs, train_df['sent'].values
                    , batch_size=BATCH_SIZE
                    , epochs=EPOCHS
                    , validation_split=0.2
                    , callbacks=callbacks)

A: If I understand it correctly, you want to predict the sent column, which seems to be a categorical variable whose values may be 0, 1 or 2. Your final layer is of 3 neurons (with a softmax activation), so you will have 3 outputs per inference. I assume you used something like One Hot Encoding for the ground truth outputs. The order of the predictions will be the same as the one set by your One Hot Encoder.
How did you prepare your dataset ground truth outputs?
UPDATE:
It is actually a nice question as there not much documentation about it.
I've searched and I found a similar question on SO, so I asked for more details here:

In case of using sparse_categorical_crossentropy, the category you
  have assigned to number 0 is actually class 0; the category you have
  assigned to number 1 is actually class 1; and so on. For example, if
  you use LabelEncoder from sklearn, you can find out this mapping
  via .classes_ attribute (see the documentation and examples).

Hope this helps!


text:
Q: слить три отсортированных файла здравствуйте, есть задача слить 3 отсортированных файла в один... подскажите алгоритм действий, не могу въехать толком, особенно если у файлов совершенно разные размеры...

A: Для трёх последовательностей, работает простейший алгоритм:

*

*выводим минимум из текущих трёх значений и сдвигаем последовательность, содержащую минимум

*если любая из последовательностей закончилась, то используем алгоритм для двух последовательностей

#include <algorithm> // merge

template <class It, class OutIt> // InputIterator, OutputIterator
OutIt merge3(It afirst, It aend, It bfirst, It bend, It cfirst, It cend,
             OutIt out)
{
  for ( ; ; ) {
    if (afirst == aend)
      return std::merge(bfirst, bend, cfirst, cend, out);
    else if (bfirst == bend)
      return std::merge(afirst, aend, cfirst, cend, out);
    else if (cfirst == cend)
      return std::merge(afirst, aend, bfirst, bend, out);

    auto a = *afirst, b = *bfirst, c = *cfirst;
    if (a < b) {
      if (a < c) {
        *out++ = a; // a < b && a < c i.e., a == min(a, b, c)
        ++afirst;
      } else {
        *out++ = c; // a < b && !(a < c) i.e.,  b > a >= c
        ++cfirst;
      }
    } else if (b < c) {
        *out++ = b; // !(a < b) && b < c i.e., a >= b && c > b
        ++bfirst;
    } else {
        *out++ = c; //  !(a < b) && !(b < c) i.e., a >= b >= c
        ++cfirst;
    }
  }
}

К примеру, чтобы объединить отсортированные последовательности чисел из файлов a, b, c:
#include <iostream>  // cout
#include <iterator>
#include <fstream>   // ifstream

int main()
{
  std::ifstream afile("a"), bfile("b"), cfile("c");
  typedef std::istream_iterator<int> It;
  merge3(It(afile), It(), It(bfile), It(), It(cfile), It(),
         std::ostream_iterator<int>(std::cout, "\n"));
}

Чтобы объединить отсортированные строки:
#include <cstring>
#include <iostream>
#include <iterator>
#include "merge.hpp"

int main()
{
  const char* a[] = {"aabbc", "bcdd", "acdfff"};
  merge3(a[0], a[0] + std::strlen(a[0]),
         a[1], a[1] + std::strlen(a[1]),
         a[2], a[2] + std::strlen(a[2]),
         std::ostream_iterator<char>(std::cout, " "));
}

Результат:
a a a b b b c c c d d d f f f

Чтобы поместить результат в строку, вместо вывода на экран, можно std::back_inserter(s) использовать (где s это std::string) вместо ostream_iterator<>():
#include <iostream>
#include <iterator>
#include <string>

int main()
{
  using namespace std;

  string a[] = {"aabbc", "bcdd", "acdfff"};
  string s;
  merge3(begin(a[0]), end(a[0]),
         begin(a[1]), end(a[1]),
         begin(a[2]), end(a[2]),
         back_inserter(s));
  cout << s;
}

Результат:
aaabbbcccdddfff

mergek() — объединение k сортированных последовательностей
Чтобы поддерживать произвольное количество файлов k, можно использовать кучу (heap), чтобы для каждого элемента не приходилось бы каждый раз ~k сравнений производить, чтобы новый минимум найти:
template <class MinHeap, class OutIt>
OutIt mergek(MinHeap& heap, OutIt out)
{
  while(!heap.empty()) {
    auto range = heap.top(); // pop minimum in O(1)
    heap.pop();

    *out++ = *range.first++; // output the minimum, move input

    if (range.first != range.second) // push unless empty range
      heap.emplace(range); // find new minimum in O(log k)
  }
  return out;
}

До тех пор пока есть последовательности в куче (в виде пары итераторов, указывающих на первый и за последний элемент соответственно):

*

*выбирается последовательность из кучи, соответствующая минимальному элементу

*выводится в результат и соответствующая позиция в последовательности сдвигается

*сдвинутая позиция добавляется назад в кучу, чтобы новый минимум найти.

*повтор

Смысл использования heap в том, что используется порядка O(log k) сравнений вместо O(k), если просто набор k последовательностей   хранить (log10(1000000) == 6 так что O(log k) значительно лучше чем O(k) для достаточно большого k).
К примеру, чтобы объединить произвольное число файлов заданных в командной строке:
#include <fstream>
#include <iostream>
#include <iterator>
#include <queue>
#include <vector>

int main(int argc, char *argv[])
{
  using namespace std;

  // input files are streams (iterators) of ints here
  typedef istream_iterator<int> It;
  // the heap contains pairs of iterators over files: (current_position, eof)
  typedef pair<It, It> Range;
  auto greater_first = [](Range lhs, Range rhs) {
    return *lhs.first > *rhs.first;
  };
  priority_queue<Range, vector<Range>, decltype(greater_first)>
    heap(greater_first);
  ifstream file[argc]; //NOTE: dummy file[0]
  while (--argc) {
    file[argc].open(argv[argc]); //NOTE: ignore errors
    heap.emplace(It(file[argc]), It());
  }
  mergek(heap, ostream_iterator<int>(cout, "\n"));
}

Пример запуска:
$ ./merge-k a b c

Каждый входной файл, как и в случае merge3(), представлен как пара итераторов: (current_position, eof). Эти пары заносятся в кучу (priority_queue<>), чтобы можно было бы быстро минимум находить среди текущих позиций во всех файлах. Сравнение происходит с помощью greater_first() функции (используется > операция, так как по умолчанию priority_queue<> возвращает наибольший элемент, а мы хотим минимум найти).
Можно перенести создание кучи внутрь mergek() (код практически идентичен тому, что выше в main() написано, но работает не только с файлами):
#include <queue>
#include <utility>   // pair
#include <vector>

template <class RandomIt, class OutIt>
OutIt mergek(RandomIt first, RandomIt last, OutIt out)
{
  typedef decltype(begin(*first)) It;
  typedef std::pair<It, It> Range;
  auto greater_first_it = [](Range a, Range b) {
    return *b.first < *a.first;
  };
  std::priority_queue<Range, std::vector<Range>, decltype(greater_first_it) >
    heap(greater_first_it);
  for ( ; first != last; ++first)
    heap.emplace(std::begin(*first), std::end(*first));
  return mergek(heap, out);
}

Чтобы объединить отсортированные строки:
#include <iostream>
#include <iterator>
#include <string>

int main()
{
  using namespace std;

  string a[] = {"aabbc", "bcdd", "acdfff"};
  mergek(begin(a), end(a), ostream_iterator<char>(cout, " "));
}

Результат:
a a a b b b c c c d d d f f f

A: Ну точно так, как я вам уже отвечал на предыдущий вопрос:
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <limits>
#include <algorithm>

using namespace std;

void makeFile(const char * name)
{
    ofstream out(name);
    int curval = rand()%100;
    for(int j = 0; j < 10000+rand()%100; ++j)
    {
        out << curval << "\n";
        curval += rand()%100;
    }
}

struct Get
{
    int val;
    ifstream* f;
};

int main(int argc, const char * argv[])
{
    makeFile("data1");  // Создали три отсортированных файла
    makeFile("data2");
    makeFile("data3");

    vector<Get> ps;        // Вектор структуры с последним считанным значением и указателем, откуда читаем
    ifstream in1("data1");
    ifstream in2("data2");
    ifstream in3("data3");

    int x;
    in1 >> x;                // Читаем из первого файла
    ps.push_back({x,&in1});  // и вносим в вектор файлов
    in2 >> x;                // Читаем из второго файла
    ps.push_back({x,&in2});  // и вносим в вектор файлов
    in3 >> x;                // Читаем из третьего файла
    ps.push_back({x,&in3});  // и вносим в вектор файлов

    ofstream out("sort");    // Выходной файл
    for(;ps.size();)         // Пока есть какие-то данные (что читать)
    {                        // Находим минимальный элемент из трех фвйлов
        auto g = min_element(ps.begin(), ps.end(),
                             [](const Get&g1, const Get&g2) { return g1.val < g2.val; });
        out << g->val << "\n";    // Выводим его в новый файл
        if (!((*g->f) >> g->val)) // Читаем из файла, откуда был взят элемент, новый элемент
        {                         // Если не удалось (конец файла)
            ps.erase(g);          // Выбрасываем этот файл из рассмотрения
        }
    }
}

A: Открыть все три и прочитать первые токены. Найдя среди них минимальный, сбросить его в выход и подчитать из этого файла следующий. Повторять, пока все файлы не закончатся.


text:
Q: Calling child constructor by casting (ChildClass)parentObject; to track revisions To track revisions of a Page class, I have a PageRevision class which inherits from Page and adds a revision ID (Guid RevisionID;).
If possible, how should I cast an existing Page object to a PageRevision and ensure that the PageRevision constructor is called to create a new revision ID?
I could could have a PageRevision(Page page) constructor which generates the Guid and copies all the Page attributes, but I want to automate it, especially if a Page class has many attributes (and I later add one, and forget to modify the copy constructor).
Desired use
Page page = new Page(123, "Page Title", "Page Body"); // where 123 is page ID
PageRevision revision = (PageRevision)page;
// now revision.RevisionID should be a new Guid.

Page, PageRevision classes:
public class Page
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

public class PageRevision : Page
{
    public Guid RevisionID { get; set; }

    public PageRevision()
    {
        this.RevisionID = Guid.NewGuid();
    }
}

Edit based on feedback:
Besides the now-obvious (Horse)Animal; casting problem, Jon Skeet recommends a composite revision:
public class PageRevision : Page
{
    private readonly Page page;
    private readonly Guid id;
    public Guid RevisionID { get { return id; } }
    public Page Page { get { return page; } }

    public PageRevision(Page page)
    {
        this.id = Guid.NewGuid();
        this.page = page;
    }
}

However, this is quite different from my data model and I'd like to keep the two as similar  as possible. In my database, the PageRevisions table has the same columns as the Pages table, expect for an extra RevisionID column. This is easy to version with a database trigger.

*

*In the light of this composite approach, would it make more sense to have a PageRevisions to store all page data: a RevisionID, Title and Body, while a Pages table only stores an URL Slug and a RevisionID that refers to the PageRevisions table?

A: Why not make your PageRevision class compose instead of inheriting?
public class PageRevision : Page
{
    private readonly Page page;
    private readonly Guid id;
    public Guid RevisionID { get { return id; } }
    public Page Page { get { return page; } }

    public PageRevision(Page page)
    {
        this.id = Guid.NewGuid();
        this.page = page;
    }
}

A: During a cast, there is no constructor called, because the object is already created.
Although your cast will fail at runtime, cause Page cannot be cast to PageRevision (the other way is possible)
In your case i would add the RevisionId to your base class Page. If you create a Page object it could be created with Guid.Empty. Derived classes could set the RevisionId using an constructor of your base class Page.
public class Page {

    public Page() {
        RevisionId = Guid.Empty;
    }

    protected Page(Guid revisionId) {
        RevisionId = revisionId;
    }

    public Guid RevisionId {
        get;
        private set;
    }
}

public class PageRevision : Page {

    public PageRevision()
        : base(Guid.NewGuid()) {

    }
}

A: You cannot.
A horse is an animal, but not every animal is a horse.
So horse => animal is possible, but animal => horse not. And you are trying to cast your animal into a horse.

A: The PageRevision constructor ALWAYS gets called regardless if you cast the class to PageRevision or not. So this isn't going to work at all.
It likely makes more sense you tell why you want to do that because you are likely doing that for reasons that are solved in other ways.


text:
Q: RegEx find string between lookbehind and lookahead so I have this example string out of a html mail given:
Abholstellenname (Firmenname, Details): Musterfirma GmbH

I'm using the following expression to find the company name, in this case Musterfirma GmbH:
(?<=Abholstellenname \(Firmenname, Details\): ).*

But I need to exclude the
 tag following the company name.
How can I achieve this?
I would not ask here if I haven't read through the tutorials and still didn't get it.

A: You can use
(?<=Abholstellenname \(Firmenname, Details\): ).*?(?=
|$)

The main idea is to turn the .* part into a .*?(?=
|$) pattern that matches any zero or more chars other than line break chars as few as possible followed with either
 or end of string.
See the regex demo.
If the spaces can be any whitespace chars, replace the literal spaces in the pattern with \s.

A: You would need to escape spaces with \s and escape parenthesis with \( and \)
[^
] matches any char other than <, >, b and r. This could work for your
 but if you have anything after that, it will be captured again.
(?<=Abholstellenname\s\(Firmenname,\sDetails\):\s).*[^
]


text:
Q: "false" text being inserted into my database I have an insert statement with a number of DataGridViewComboBoxColumns. When I try and insert the values of these DataGridViewComboBoxColumns into my database the text "False" is being inserted into the fields.
Why is this happening?
Dim para As New SqlClient.SqlParameter
Dim dateValue As String = CStr(DateTimePicker1.Value)
Dim calendar = Microsoft.VisualBasic.Left(dateValue, 10)
para.ParameterName = "@company"
para.Value = company.Selected.ToString
para.ParameterName = "@division"
para.Value = division.Selected.ToString
para.ParameterName = "@date"
para.Value = DateTimePicker1.Value
para.ParameterName = "@supplier"
para.Value = supplier.Selected.ToString
para.ParameterName = "@material_group"
para.Value = materialGroup.Selected.ToString
para.ParameterName = "@cost"
para.Value = netprice.Selected.ToString
para.ParameterName = "@dsc"
para.Value = description.Selected.ToString
para.ParameterName = "@email"
para.Value = cmbEmail.SelectedValue
para.ParameterName = "@userID"
para.Value = id
para.ParameterName = "@Name"
para.Value = txtEmployee.Text
para.ParameterName = "@val"
para.Value = newName
para.ParameterName = "@quantity"
para.Value = quantity.Selected.ToString
para.ParameterName = "@wbs"
para.Value = wba.Selected.ToString
para.ParameterName = "@marketingCode"
para.Value = markCodes.Selected.ToString
para.ParameterName = "@hccNumber"
para.Value = hccNumber.Selected.ToString
para.ParameterName = "@currency"
para.Value = currency.Selected.ToString

Insert details:
Dim con As New SqlClient.SqlConnection
Dim myCommand As New SqlClient.SqlCommand
myCommand.Parameters.Add("@company", SqlDbType.NVarChar, 30).Value = company.Selected.ToString
myCommand.Parameters.Add("@division", SqlDbType.NVarChar, 30).Value = division.Selected.ToString
myCommand.Parameters.Add("@date", SqlDbType.NVarChar, 30).Value = DateTimePicker1.Value
myCommand.Parameters.Add("@supplier", SqlDbType.NVarChar, 30).Value = supplier.Selected.ToString
myCommand.Parameters.Add("@material_group", SqlDbType.NVarChar, 30).Value = materialGroup.Selected.ToString
myCommand.Parameters.Add("@cost", SqlDbType.NVarChar, 30).Value = netprice.Selected.ToString
myCommand.Parameters.Add("@dsc", SqlDbType.NVarChar, 30).Value = description.Selected.ToString
myCommand.Parameters.Add("@email", SqlDbType.NVarChar, 30).Value = cmbEmail.SelectedValue
myCommand.Parameters.Add("@userID", SqlDbType.NVarChar, 30).Value = id
myCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 30).Value = newName
myCommand.Parameters.Add("@quantity", SqlDbType.NVarChar, 40).Value = quantity.Selected.ToString
myCommand.Parameters.Add("@wbs", SqlDbType.NVarChar, 40).Value = wba.Selected.ToString
myCommand.Parameters.Add("@marketingCode", SqlDbType.NVarChar, 40).Value = markCodes.Selected.ToString
myCommand.Parameters.Add("@hccNumer", SqlDbType.NVarChar, 40).Value = hccNumber.ToString
myCommand.Parameters.Add("@currency", SqlDbType.NVarChar, 40).Value = currency.Selected.ToString

Dim myAdapter As New SqlClient.SqlDataAdapter
Dim sql As String = "Insert into details (company, division, date, supplier, material_group, cost, dsc, email, userID, fullName, marketingCode, wbs, qty, currency) VALUES (@company, @division, @date, @supplier, @material_group, @cost, @dsc, @email, @userID, @Name, @marketingCode, @wbs, @quantity, @currency)"
myCommand.Connection = con
myCommand.CommandText = sql
myAdapter.InsertCommand = myCommand
myCommand.Connection.Open()
myCommand.ExecuteNonQuery()
myCommand.Connection.Close()

A: You are storing if something is selected.
para.Value = company.Selected.ToString

Selected is a boolean!

A: I'm not certain on what you are trying to achieve here, but I don't think this script will work how you wish. You're not building a list of parameters with values, but replacing one parameter object over and over.
para.ParameterName = "@company"
para.Value = company.Selected.ToString
para.ParameterName = "@division"
para.Value = division.Selected.ToString

This will just first set the para object to be @company, and value: company.Selected.ToString, then set it again to be @division and value: division.Selected.ToString.
Your datatypes are all NVarChar and you are explicitly setting your boolean values to a string (.ToString()).
If you wish to store boolean values, change your data types to bit. Then change your values so you are passing the boolean value, not an explicitly converted boolean to string:
myCommand.Parameters.Add("@currency", SqlDbType.bit).Value = currency.Selected

A: company.selected returns true if the item is selected, and false if not...
You probably want to use company.ToString


text:
Q: Find the minimum of a energy conservation equation. I have an equation for two particle collisions (the equation is just energy-momentum conservation):
$$k_{A,x}+k_{B,x} = p_{1,x}+p_{2,x}$$
$$k_{A,y}+k_{B,y} = p_{1,y}+p_{2,y}$$
$$k_{A,z}+k_{B,z} = p_{1,z}+p_{2,z}$$
$$\sqrt{m_{1}^{2}+\mathbf{k}_{A}^{2}}+\sqrt{m_{2}^{2}+\mathbf{k}_{B}^{2}} = \sqrt{m_{1}^{2}+\mathbf{p}_{1}^{2}}+\sqrt{m_{2}^{2}+\mathbf{p}_{2}^{2}}.$$
where, $k_{A,x}\in[p_{c,x}-3\sigma,p_{c,x}+3\sigma]$, $k_{B,x}=-k_{A,x}$ and $k_{A,y},k_{B,y},k_{A,z},k_{B,z}\in[-3\sigma,3\sigma]$, $p_{c,x}$ and $\sigma$ is a positive number, and $ p_{c,x} > 3\sigma $.
The first three equations will give $\mathbf{p}_{2}$ in terms of $\mathbf{k}_{A},\mathbf{k}_{B},\mathbf{p}_{1}$.
I would like to know the minimum and maximum value of $|\mathbf{p}_{1}|$ if we already know $|\mathbf{k}_{A}|_{min},|\mathbf{k}_{A}|_{max},|\mathbf{k}_{B}|_{min},|\mathbf{k}_{B}|_{max}$. Or the boundary for $|\mathbf{p}_{1}|$ in terms of $p_{c,x}$ and $\sigma$,i.e., I would like to know the minimum and maximum value of $|\mathbf{p}_{1}|$ in terms of $p_{c,x}$ and $\sigma$.
Here is a solution I found for this question, which I can not persuade myself, but it may help clear the question.
Since $\mathbf{k}_{A}$ and $\mathbf{k}_{B}$ denoting the input momentum of two incoming particles, if $|\mathbf{k}_{A}|$ and $|\mathbf{k}_{B}|$ all take the minimum values, i.e., $\mathbf{k}_{A}=(p_{c,x}-3\sigma,0,0)$ and $\mathbf{k}_{B}=(-p_{c,x}+3\sigma,0,0)$ hence $\mathbf{k}_{A}+\mathbf{k}_{B}=\mathbf{p}_{1}+\mathbf{p}_{2}$, the outcoming particles would have the minimum values. Thus we have
 $$\sqrt{m_{1}^{2}+\mathbf{k}_{A}^{2}}+\sqrt{m_{2}^{2}+\mathbf{k}_{A}^{2}} = \sqrt{m_{1}^{2}+\mathbf{p}_{1}^{2}}+\sqrt{m_{2}^{2}+\mathbf{p}_{1}^{2}}.$$
Thus one can easily see that the minimum value for $|\mathbf{p}_{1}|$ is $|\mathbf{k}_{A}|_{min}$
This is somewhat reluctant.
Does anyone have once encountered such problem or how to make my proof more convinsing?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Or equivalently, if $\delta_{1},\delta_{2},\delta_{3},\delta_{4}\in[-3\sigma,3\sigma]$ and $p_{c,x}$ and $\sigma$ are positive numbers,  and $ p_{c,x} > 3\sigma $., how to prove the following inequality to be wrong:
$$\sqrt{m_{1}^{2}+(-p_{c,x}+\delta_{1})^{2}+\delta_{2}^{2}}+\sqrt{m_{2}^{2}+(p_{c,x}+\delta_{3})^{2}+\delta_{4}^{2}} < \sqrt{m_{1}^{2}+(p_{c,x}-3\sigma)^{2}}+\sqrt{m_{2}^{2}+(p_{c,x}-3\sigma)^{2}+(\delta_{1}+\delta_{3})^{2}+(\delta_{2}+\delta_{4})^{2}}$$


text:
Q: Comparison script diffrent files i am trying to write a script that compares a bunch of files based on a search word, in this case i searched for  106, then i want the code to match the words from file 1 to the words in file 2 and print a list with the ones that dont match.
For example in file A i have this line
106_LB01_GP61_HAL;LB01;10892;DIGITAL;0;0;0;0;;;Smutsigt tilluftsfilter;;
and in file B i have
"Prefix": "106_LB01_GP61",
those lines match and then i want it to ignore that tag
when the script find lines that dont match etc when a tag in file A cant fint its buddy in file B i want it to write those tags to a file,
for example:
Total unused tags:1

*

*106_LB01_GP61

right now i am stuc at making it read to diffrent files at the same time

#!/usr/bin/env python

#Import os module
import os

# Ask the user to enter string to search
search_path = (".")
file_type = (".wpp")
search_str = input("Enter searchword: ")
resultsFile = "results.csv"
file_name = ("results.csv")

# Append a directory separator if not already present
if not (search_path.endswith("/") or search_path.endswith("\\") ):
        search_path = search_path + "/"

# If path does not exist, set search path to current directory
if not os.path.exists(search_path):
        search_path ="."
0
# Repeat for each file in the directory
for fname in os.listdir(path=search_path):

   # Apply file type filter
   if fname.endswith(file_type):

        # Open file for reading
        fo = open(search_path + fname)

        # Read the first line from the file
        line = fo.readline()

        # Initialize counter for line number
        line_no = 1

        # Loop until EOF
        wf = open(search_path + resultsFile, 'a')
        while line != '' :
                # Search for string in line
                index = line.find(search_str)
                if ( index != -1) :
                    print(fname, "[", line_no, ",", index, "] ", line, sep="")
                wf.write(line + "  ")
                # Read next line
                line = fo.readline()
                # Increment line counter
                line_no += 1

        # Close the files
        fo.close()

def check_if_string_in_file(file_name, string_to_search):
    """ Check if any line in the file contains given string """
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            if string_to_search in line:
                return True
    return False

def check_if_string_in_file(file_name2, string_to_search):
    """ Check if any line in the file contains given string """
    # Open the file in read only mode
    with open(file_name2, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            if string_to_search in line:
                return True
    return False

def search_string_in_file(file_name, string_to_search):
    """Search for the given string in file and return lines containing that string,
    along with line numbers"""
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            # For each line, check if line contains the string
            line_number += 1
            if string_to_search in line:
                # If yes, then add the line number & line as a tuple in the list
                list_of_results.append((line_number, line.rstrip()))
    # Return list of tuples containing line numbers and lines where string is found
    return list_of_results

def search_multiple_strings_in_file(file_name, list_of_strings):
    """Get line from the file along with line numbers, which contains any string from the list"""
    line_number = 0
    list_of_results = []
    # Open the file in read only mode
    with open(file_name, 'r') as read_obj:
        # Read all lines in the file one by one
        for line in read_obj:
            line_number += 1
            # For each line, check if line contains any string from the list of strings
            for string_to_search in list_of_strings:
                if string_to_search in line:
                    # If any string is found in line, then append that line along with line number in list
                    list_of_results.append((string_to_search, line_number, line.rstrip()))
    # Return list of tuples containing matched string, line numbers and lines where string is found
    return list_of_results

def main():
    print('*** Loading *** ')
    matched_lines = search_string_in_file(file_name, search_str)

    for elem in matched_lines:
        print('Line Number = ', elem[0], ' :: Line = ', elem[1])

    # search for given strings in the file 'sample.txt'
    matched_lines = search_multiple_strings_in_file(file_name, [search_str])
    print('*** Checking if',  [search_str], 'exists in a file *** ')
    print('Total Matched lines : ', len(matched_lines))
      # Check if string 'is' is found in file 'sample.txt'
    if check_if_string_in_file(file_name, search_str):
        print('Yes, string found in file')
    else:
        print('String not found in file')

if __name__ == '__main__':
    main()


text:
Q: how to get local timezone datetime for date comparison in django I am trying to fire a reminder based on a users timezone.  The users timezone is 'America/New_York'
I attempt to get the users time with the following:
now = datetime.now()
now_plus_10 = test_customer.time_zone.localize(now + timedelta(minutes = 10))
now_minus_10 = test_customer.time_zone.localize(now + timedelta(minutes = -10))

The reminder time is at 13:00.  It is gathered from the customer object like this:
 reminder = customer.reminder #set to 13:00

I then want to send a reminder if within 10 minutes + or - of the reminder.
I do the comparison like:
if reminder > now_minus_10 and gb_real_time < now_plus_10:
    reminder_email.send()
else:
    print 'ceiling '+str(now_plus_10)
    print 'not in window don t send'
    print 'floor '+str(now_minus_10)

This prints:
ceiling 2014-09-03 10:10:54.547901-04:00
not in window don t send
floor 2014-09-03 09:50:54.547901-04:00

I am in the timezone: 'America/Los_Angeles' in which it is 10:00am
Why is it that even though I localized now_plus_10 and now_minus_10 dates, but they do not convert to New_York time which would make them 13:00 like the reminder and in turn fire the reminder?

A: I think you've misunderstood what localize() does. (I assume you're talking about the pytz localize(), in which case you can see the documentation here.)
It doesn't convert times, it takes a naive (timezone-unaware) datetime and makes it aware (assigns it a timezone). Here's what's going on in your example:
now = datetime.now()  # 10:00am local time (no timezone)
later = now + timedelta(minutes=10)  # 10:10am (no timezone)
now_plus_10 = ny_timezone.localize(later)  # 10:10am (NY timezone)

If you really want to convert between timezones directly, using pytz, you can do something like this:
now = la_timzeone.localize(datetime.now())  # 10:00am local time (LA timezone)
later = now + timedelta(minutes=10)  # 10:10am (LA timezone)
later_safe = la_timezone.normalize(later)  # because of DST and such
later_ny = later_safe.astimezone(ny_timezone)  # 13:10 (NY timezone)
later_ny_safe = ny_timezone.normalize(later_ny)  # again

Now, that's complicated! Which is why both pytz and Django discourage you from manually localizing and converting time zones. You'll have to review the documentation, but basically the Django approach is this:

*

*All internal datetimes are timezone-aware and use UTC.

*Use django.utils.timezone.now() to get the current time in UTC.

*User-entered datetimes (for example, if your user enters his or her reminder time in a form) are automatically made aware. To do this you have to know the user's timezone and then call activate(). You can also do it manually with localtime().

*Do all of your comparisons and arithmetic with these UTC datetimes.

I definitely recommend doing things the Django way.


text:
Q: Fixed div inside scrolling div I need to make the main of my site that has 980px width and 500px height (class="main") be fixed only when the mouse is over a scrolling div and has a height of 1500px and a width of 100% (class="container-scroll"), that is inside other div with height of 500px. (class="container")
Pretty confused, right?
I made a fiddle, I'm almost there, the problem is that if I set up the main to fixed, it will scroll with the page , not just inside the div
This is my fiddle:  https://jsfiddle.net/8oj0sge4/1/embedded/result/
HTML:

CSS:
    #wrapper {
        width: 100%;
        height: 1500px;
        border: 1px solid red;
        padding-top: 380px;
    }
    #wrapper .container {
        border: 1px solid green;
        width: 100%;
        height: 500px;
        overflow: scroll;
    }
    #wrapper .container-scroll {
        height: 1500px;
        width: 100%;
        border: 1px solid yellow;
    }
    #wrapper .main {
        width: 980px;
        height: 500px;
        background: black;
        overflow: scroll;
        /*position: fixed;*/
    }

A: There is no pure CSS to do that, but you could work around it with some Javascript.
One solution could be to disable scrolling on the inner div if the scrolls has been initiated on the #wrapper, which is demoed on this fiddle:
https://jsfiddle.net/qmjmthbz/
Here is the code:
var wrapper = $('#wrapper');
var container = $('.container');
var timer;

// Listen to mouse scroll events
$('body').on('mousewheel', function(e) {
    var target = $(e.target);
    /* If the scroll is initiated from the #wrapper,
       disable scroll on the container and re-enable it
       100ms after the last scroll event */
    if (target[0] === wrapper[0]) {
        container.addClass('no-scroll');
        clearTimeout(timer);
        timer = setTimeout(function() {
            container.removeClass('no-scroll');
        }, 100);
    }
});

Note: it is useless to use jQuery to achieve that but I am rushing that at a train station. I will provide a better code when I can find more time :-)

A: If I'm understanding this correctly, you want the main div to stay on the top of the parent div?
Fiddle: https://jsfiddle.net/8oj0sge4/3/ (full)
Changes made:

*

*#wrapper .main: Added position:absolute ("fixed" to parent)

*#wrapper .container-scroll: Added position: relative (determines what parent to "fix" to)

*Added an id to the main div (for convenience)

JavaScript code:
var main = document.getElementById('main-site');
var maxTop = main.parentNode.scrollHeight-main.offsetHeight; // Make sure we don't go outside the parent

main.parentNode.parentNode.onscroll = function() {
   main.style.top = Math.min(this.scrollTop,maxTop) + "px";
}

A: Basicly I think you can't make the div scroll because the content of the div does not exceed the height of the div. In order for the div to become scroll-able the content should actually exceed the height of the div.
Try giving the div a height of lets say 100px, and insert an amount of text large enough to exceed the 100px height, thus making the div scrollable, and then try if what you want to achieve works.


text:
Q: IVF baby probability? We have two embryos.  Our IVF doc said the probability of success implanting a single embryo is 40% whereas the probability of having one baby with implanting two embryos at once is 75% (with a 30% chance of twins).
What is the chance of having at least one child if we implant the embryos one at a time?
My calculation is 1- (chance of failure twice in a row)= 1 - 0.6*0.6 = 64%.  Is this correct?  Does it underestimate our chances since we would stop if the first was a success?
Thanks.

A: No.  The probability of having 1 success when you attempt the procedure at most twice, but stop on the first success, is the same as the probability of having at least 1 success when you perform the procedure twice whatever the result of the first try.
If you stop when the first trial is successful, then the probability of a success is: $$0.4 + 0.6\cdot 0.4 = 0.64$$
If you perform both trials reguardless of the result of the first, then the probability of at least one success is: $$0.4\cdot0.4 + 0.4\cdot 0.6 + 0.6\cdot 0.4 = 0.64$$
Which is also $1-0.6\cdot 0.6 =0.64$ in both cases.
All stopping on the first success affects is the probability of having two successes.  Obv.

PS: This is assuming that the attempts are independent.   That the result of having tried the procedure once before does not affect the probability of success on a second trial.   This may not be the case.

A: For the 1st specific question, I would agree with your combined probability of 64% for one or more children after 2 independent single embryo implants.
For your 2nd question, the 2nd implant is no longer independent from the results of the 1st implant.  Therefore, you want to list all 3 possible outcome states, and calculate probabilities for each:
   baby on first implant then stop:  .40
   first implant fails, 2nd one succeeds:  .60 x .40 = .24
   both implants fail:  .60 x .60 = .36
Now, combine the two outcomes where you get one success, .40 + .24 = .64
Even tho you're comparing two different scenarios, the probabilities for them are the same.  In the first scenario, you could end up with 2 successful pregnancies, and in the 2nd scenario, the most you can end up with is one. Isn't choice great?


text:
Q: Yii2 - onCondition added to where part of child query I noticed in v2.1, the onCondition is being added to the where condition -https://github.com/yiisoft/yii2/blob/2.1/framework/db/ActiveQuery.php#L202
I do not know why, but this is affecting me from being able to use my relation as below.
I am working on the RBAC module for a new project. I am not using Yii2's default because it is a SaaS system, roles have to be defined per account, we would rather use id instead of name as unique keys and we do not like the naming conventions.
I have tables permissions, privileges and roles
privileges - [id, name] - things you can do in the system
roles - [account_id, id, name] - different roles per account
permissions - [parent_type, parent_id, child_type, child_id] - mapping of roles to privileges, roles to roles, and privileges to privileges.
Problem now is i need to findAll permissions and get the child / parent having the appropriate objects.
For parent, I have
public function getParentPrivilege($type) {
    return $this->hasOne(Privilege::className(), ['id' => 'parent_id'])->onCondition('parent_type = "privilege"');
}

public function getParentRole() {
    return $this->hasOne(Role::className(), ['id' => 'parent_id'])->onCondition('parent_type = "role"');
}

public function getParent(){
    if($this->parentPrivilege)
        return $this->parentPrivilege;
    else
        return $this->parentRole;
}

Then i do a find by:
$permissions = \app\models\Permission::find()
    ->joinWith(['parentRole','parentPrivilege'])
    ->all();

Problem is, onCondition is used in the SQL on condition since I used joinWith BUT, the onCondition is still being added to the where clause of the parent queries as seen below.
SELECT `permissions`.* FROM `permissions`
LEFT JOIN `roles` ON (`permissions`.`parent_id` = `roles`.`id`) AND (parent_type = "role")
LEFT JOIN `privileges` ON (`permissions`.`parent_id` = `privileges`.`id`) AND (parent_type = "privilege")

SELECT * FROM `roles` WHERE (`id` IN ('3', '1', '4', '2', '25')) AND (parent_type = "role")
SELECT * FROM `privileges` WHERE (`id` IN ('5')) AND (parent_type = "privilege")

WHY?!!!
Makes no sense to add AND (parent_type = "role") and AND (parent_type = "privilege") to the following relation queries
How can I make this work?

A: As we see onCondition doesn't affect joinWith().
Try to remove onCondition from relations' declations and to rewrite the query like this
    $permissions = \app\models\Permission::find()
        ->joinWith([
            'parentRole' => function ($query) {
                $query->andOnCondition('parent_type = "role"');
            },
            'parentPrivilege' => function ($query) {
                $query->andOnCondition('parent_type = "privilege"');
            }
        ])->all();


text:
Q: How to join a variable number of lines I have a file with Feature names and a variable number of usernames below:
Feature1
user1
user2
Feature2
user3
I'd like to be able to move the usernames to the same line as the Feature name (along the lines of the vi join command).  The Feature names begin with an uppercase letter and the usernames begin with lowercase.  Is there a way to do this?

A: That's pretty easy with sed:
sed ':a;N;$!ba;s/\n\+\([a-z]\)/ \1/g;'

Small description how it works:
:a;N;$!ba; will add all lines into match pattern. we need it to delete all newlines in the next step.
s/\n\+\([a-z]\)/ \1/g; will delete all newlines before user* and save newlines before Feature*.
btw it also can be done with
tr '\n' ' ' | sed 's/ \([A-Z]\)/\n\1/g'

 $ cat test_file
Feature1

user1

user2
Feature2

user3
Feature2
user3
user3

ouser3

user3

 $ sed ':a;N;$!ba;s/\n\+\([a-z]\)/ \1/g;' test_file
Feature1 user1 user2
Feature2 user3
Feature2 user3 user3 ouser3 user3

A: It's very straightforward in AWK:
awk '/^[[:upper:]]/ {if (line) {print line}; line = $0} /^[[:lower:]]/ {line = line " " $0} END {if (line) {print line}}'

A: You will want to chunk your data before writing it.  Something like the following pseudocode (you will need to make this into proper BASH syntax yourself).
out_line=""
for in_line in $(cat $file); do
  if $(echo in_line | egrep ^Feature) != ""
    echo $out_line >> $out_file
    out_line="$in_line"
  else
    out_line="$out_line $in_line"
  fi
done
echo $out_line >> $out_file


text:
Q: having trouble understanding how to chain objects in the implementation of other classes I'm having a compiler error when trying to add each card(suit and rank) into the object's Card.
Here is the Card.h file:
#define CARD_H
#include <iostream>

using namespace std;

class Card{

    private:
        int rank;
        int suit;

    public:
    // must have constructors, destructor, accessor methods, and mutator methods
    Card();
    Card(int, int);
    ~Card();

    int get_rank();
    int get_suit();

    void set_rank(int);
    void set_suit(int);
    string fillrank(int) ;
    string fillsuit(int) ;
    void printcards();
    /*
    string getr_ank();
    string gets_uit();
    void setr_ank(string);
    void sets_uit(string);
    */

};

#endif

Card.cpp
#include <iostream>
#include "card.h"
#include <string>

using namespace std;

Card::Card(){

    rank = 0;
    suit = 0;

}

Card::Card(int r, int s){

    rank = r;
    suit = s;
    //cout << "Parameterized constructor" << endl;

}

int Card::get_rank(){

    return rank;

}

int Card::get_suit(){

    return suit;

}

void Card::set_rank(int rank){

    this->rank = rank;

}

void Card::set_suit(int suit){

    this->suit = suit;

}

string Card::fillrank(int rank) {

switch(rank){
        case 0:
            return "Ace";
                break;
        case 1:
            return "2";
                break;
        case 2:
            return "3";
                break;
        case 3:
            return "4";
                break;
        case 4:
            return "5";
                break;
        case 5:
            return "6";
                break;
        case 6:
            return "7";
                break;
        case 7:
            return "8";
                break;
        case 8:
            return "9";
                break;
        case 9:
            return "10";
                break;
        case 10:
            return "Jack (J)";
                break;
        case 11:
            return "Queen (Q)";
                break;
        case 12:
            return "King (K)";
                break;
    }

}

string Card::fillsuit(int suit) {

    switch(suit){

        case 0:
            return "Clubs";
                break;
        case 1:
            return "Spades";
                break;
        case 2:
            return "Hearts";
                break;
        case 3:
            return "Diamonds";
                break;

    }
}

void Card::printcards(){

cout << rank << " of " << suit << endl;

}

Card::~Card(){
 cout << "Destructor called!" << endl;

deck.h
#ifndef DECK_H
#define DECK_H
#include "card.h"

class Deck{
    private:
        Card cards[52];
        int n_cards; //Number of cards remaining in the deck.
    public:
        //must have constructors, destructor, accessor methods, and mutator methods.

    Deck();

    int get_cards();

    void set_cards(int);
    void filldeck();
    void printdeck();
    ~Deck();

};

#endif

deck.cpp
#include <iostream>
#include "deck.h"
#include <string>

using namespace std;

Deck::Deck(){

    n_cards = 0;

}

int Deck::get_cards(){

    return n_cards;
}

void Deck::set_cards(int cards){

    n_cards = cards;

}

void Deck::filldeck(){

    int a = 0;
    Card p1;
    for (int x = 0; x <13 ;x++){
        for(int y = 0; y < 4; y++){
            cards[a] = p1.fillrank(x);
            cards[a] =  p1.fillsuit(y) ;

            a++;
        }
    }

}

void Deck::printdeck(){

    for (int i = 0; i < 52; i++){
        cards[i].printcards();
    }

}

Deck::~Deck(){

}

This is the error I'm getting:
deck.cpp:52:22: error: no match for 'operator=' (operand types are 'Card' and 'std::string {aka std::basic_string<char>}')
             cards[a] = p1.fillrank(x);
ard.h:7:7: note: Card& Card::operator=(const Card&)
 class Card{
       ^
card.h:7:7: note:   no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const Card&'
deck.cpp:53:22: error: no match for 'operator=' (operand types are 'Card' and 'std::string {aka std::basic_string<char>}')
             cards[a] =  p1.fillsuit(y) ;

Why can't I fill each rank and suit into the Card object? what I'm missing here? how should I approach this? Thank you beforehand.

A: What happens here is that your fillrank and fillsuit doesn't actually fill the rank and suit of that card, instead it returns the rank and suit it should be filled with.
To actually make the fill the rank, you need to do something like rank = "Ace" in that function.
So you would change your function to something like:
void fillrank(int rank)
{
    switch(rank)
    {
        case 0:
            this.rank = "Ace";
            break;
        case 1:
            this.rank = "2";
            break;
        case 2:
            .
            .
            .
    }
}

And in your filldeck function, you could just call each card from the deck, and apply fillrank on them directly, like:
cards[a].fillrank(x);


text:
Q: Fill your tables with junk data? I am lazy, sometimes excruciatingly lazy but hey (ironically) this is how we get stuff done right?
Had a simple idea that may or not be out there. If it is I would like to know and if not perhaps I will make it.
When working with my MSSQL database sometimes I want to test the performance of various transactions over tables and view and procedures etc... Does anyone know if there is a way to fill a table up with x rows of junk data mearly to experiment with.
One could simple enough..
INSERT INTO `[TABLE]`
SELECT `COLUMNS` FROM [`SOURCE_TABLE`]

Or do some kind of...
DECLARE count int
SET count = 0

WHILE count <= `x`
BEGIN
INSERT INTO `[TABLE]`
(...column list...)
VALUES
(...VALUES (could include the count here as a primary key))

SET count = count + 1
END

But it seems like there is or should already be something out there. Any ideas??

A: I use redgate
SQL Data generator

A: Use a Data Generation Plan (a feature of Visual Studio database projects).

A: WinSQL seems to have a data generator (which I did not test) and has a free version. But the Test data generation wizard seems to be reserved to the Pro version.

A: My personal favorite would be to generate a CSV file (using a 4.5 lines script) and load it into your SQL DB using BULK INSERT. This will also allow better customization of the data as sometimes is needed (e.g. when writing tests).


text:
Q: my css and js folder are inside resource directory instead of public directory how can i sort this issue directory structure
look JS and CSS folder are inside resources directory instead it should be public directory and the asset folder is also missing. I have already install NPM and node  latest version and i have run npm run watch dev all these commands but it is not working


text:
Q: Creating individual columns to write to new csv A CSV returns the following values
"1,323104,564382"
"2,322889,564483"
"3,322888,564479"
"4,322920,564425"
"5,322942,564349"
"6,322983,564253"
"7,322954,564154"
"8,322978,564121"

How would i take the " marks off each end of the rows, it seems to make individual columns when i do this.
reader=[[i[0].replace('\'','')] for i in reader]

does not change the file at all

A: It seems strictly easier to peel the quotes off first, and then feed it to the csv reader, which simply takes any iterable over lines as input.
import csv
import sys

f = open(sys.argv[1])
contents = f.read().replace('"', '')

reader = csv.reader(contents.splitlines())

for x,y,z in reader:
     print x,y,z

A: Assuming every line is wrapped by two double quotes, we can do this:
f = open("filename.csv", "r")
newlines = []
for line in f:  # we could use a list comprehension, but for simplicity, we won't.
    newlines.append(line[1:-1])
f.close()

f2 = open("filename.csv", "w")
for index, line in enumerate(f2):
    f2.write(newlines[index])
f2.close()

[1:-1] uses a list-indexing operation to get the second letter of the string to the last letter of the string, each represented by the indexes 1 and -1.
enumerate() is a helper function that turns an iterable into (0, first_element), (1, second_element), ... pairs.
Iterating over a file gets you its lines.


text:
Q: Creating a Mixin class for pandas DataFrame and native Python dict How to create a mixin class for pandas DataFrame and native Python dict such that the dataframe columns can be accessed like a nested dict?
From Accessing pandas DataFrame as a nested list, using the df.loc() function is the way to access the row/column/slices desired.
But the goal is to access the 2-D dataframe using the same syntax as a native Python dict. E.g.
>>> import pandas as pd
>>> df = pd.DataFrame([['x', 1,2,3,4,5], ['y', 6,7,8,9,10], ['z', 11,12,13,14,15]])
>>> df.columns = ['index', 'a', 'b', 'c', 'd', 'e']
>>> df = df.set_index(['index'])
>>> df
        a   b   c   d   e
index
x       1   2   3   4   5
y       6   7   8   9  10
z      11  12  13  14  15

>>> df['x']
[1, 2, 3, 4, 5]

>>> df['x']['a']
1

>>> df['x']['a', 'b']
(1, 2)

>>> df['x']['a', 'd', 'c']
(1, 4, 3)

I've tried to create a mixin class as such:
from pandas import DataFrame

class VegeTable(DataFrame, dict):
    def __init__(self, *args, **kwargs):
        DataFrame.__init__(self, *args, **kwargs)
    def __getitem__(self, row_key, column_key):
        if type(row_key) != list:
            row_key = [row_key]
        if type(column_key) != list:
            column_key = [column_key]
        return df.loc[row_key, column_key]

But I think there's something missing such that the dictionary key access didn't work and the dict.get returns a strange values:
>>> from pandas import DataFrame
>>>
>>>
>>> class VegeTable(DataFrame, dict):
...     def __init__(self, *args, **kwargs):
...         DataFrame.__init__(self, *args, **kwargs)
...     def __getitem__(self, row_key, column_key):
...         if type(row_key) != list:
...             row_key = [row_key]
...         if type(column_key) != list:
...             column_key = [column_key]
...         return df.loc[row_key, column_key]
...
>>>
>>> vt = VegeTable([['x', 1,2,3,4,5], ['y', 6,7,8,9,10], ['z', 11,12,13,14,15]])
>>> vt.columns = ['index', 'a', 'b', 'c', 'd', 'e']
>>> vt = vt.set_index(['index'])
>>> vt
        a   b   c   d   e
index
x       1   2   3   4   5
y       6   7   8   9  10
z      11  12  13  14  15
>>> vt['x']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 2062, in __getitem__
    return self._getitem_column(key)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/frame.py", line 2069, in _getitem_column
    return self._get_item_cache(key)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/generic.py", line 1534, in _get_item_cache
    values = self._data.get(item)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 3590, in get
    loc = self.items.get_loc(item)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/indexes/base.py", line 2395, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5239)
  File "pandas/_libs/index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5085)
  File "pandas/_libs/hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20405)
  File "pandas/_libs/hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20359)
KeyError: 'x'
>>> vt.get(['x'])
>>> vt.get('x')
>>> vt.get('x', 'a')
'a'
>>> vt.get('x', ['a', 'b'])
['a', 'b']
>>> vt.get('x', ['a', 'b'])

How to create a mixin class for pandas DataFrame and native Python dict such that the dataframe columns can be accessed like a nested dict? Is that possible at all? If so, how?

A:
Error in reasoning.

*

*vt = vt.set_index(['index'])
    This will redefine df to <class 'pandas.core.frame.DataFrame'>.
    You have to overload it or Typecast the resulting df.

*def __getitem__(self, row_key, column_key=None):
    Only one Parameter is passed to def __getitem__(....
    Multiple Parameter have to be inside [...],
    e.g. vt['x', ['a', 'b', 'c']]

If you accept this slightly different notation,
this implementation do what you want:
class DataFrame2(DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __getitem__(self, item):
        if isinstance(item, tuple):
            row = self.loc[item[0]]
            sub_item = item[1]
            if isinstance(sub_item, list):
                r = [row.loc[key] for key in sub_item]
                if len(r) == 1:
                    return r[0]
                else:
                    return tuple(r)
            else:
                # NotImplemented, Parameter other than tuple('x', [list])
                raise Exception(NotImplemented)
        else:
            return tuple(self.loc[item])

    def set_index(self, index):
        return DataFrame2(super().set_index(index))

# Usage:
df = DataFrame2(data)
df.columns = ['index', 'a', 'b', 'c', 'd', 'e']
df = df.set_index(['index'])

print('df[\'x\']={}\n'.format(df['x']))
print('df[\'x\'][\'a\']={}\n'.format(df['x',['a']]))
print('df[\'x\'][\'a\', \'b\']={}\n'.format(df['x', ['a', 'b']]))
print('df[\'x\'][\'a\', \'b\', \'c\']={}\n'.format(df['x', ['a', 'b', 'c']]))

Output:

df['x']=(1, 2, 3, 4, 5)
df['x']['a']=1
df['x']['a', 'b']=(1, 2)
df['x']['a', 'b', 'c']=(1, 2, 3)

Tested with Python: 3.4.2

A: I don't think it's good idea to create create a mixin class. When you use pandas you should think in pandas way. And I also doubt that native  Python nested dict can be assess by this way:
In []: df['x']['a', 'b']

But, if you insist, try this code first:
In []: df.T.to_dict()
Out[]:
{'x': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5},
 'y': {'a': 6, 'b': 7, 'c': 8, 'd': 9, 'e': 10},
 'z': {'a': 11, 'b': 12, 'c': 13, 'd': 14, 'e': 15}}


text:
Q: Memory leak in obj-c/c++ code I'm using instruments and I have a lot of memory being leaked by this method. It is used everywhere in my app, and when I built it, I used some c++ (i think).
Please let me know where the leak is happening if possible?
Instruments just says Malloc 16 bytes and has about 60 MB worth of these guys...
/*
 Parses a dicionary into an object
 */
+(id)makeObject:(id)object fromDictionary:(NSDictionary *)dict{

    @autoreleasepool {
        NSArray *keys = @[@"@\"NSMutableArray\""];

        //Init result
        id result = object;

        //Iterate every key
        for (id key in [dict allKeys]) {

            //Convert key to const char
            const char * c = [key cStringUsingEncoding:NSASCIIStringEncoding];

            //Use c to see if the class has this property
            if (class_getProperty([object class], c)) {

                //get the property
                objc_property_t property = class_getProperty([result class], c);

                //Get the property name and type
                const char *name = property_getName(property);
                const char *type = property_copyAttributeValue(property, "T");

                //Cast const char to string
                NSString *pNameString = [NSString stringWithFormat:@"%s",name];
                NSString *typeString = [NSString stringWithFormat:@"%s",type];

                //Add relationships
                if ([keys containsObject:typeString]) {

                    //Get array of objects
                    NSArray *relationship = [dict objectForKey:pNameString];

                    NSMutableArray *allSubObjects = [[NSMutableArray alloc]init];
                    //Parse each individual object
                    for (NSDictionary *relationshipObj in relationship) {

                        //Create class from relationship
                        Class class = NSClassFromString(pNameString);

                        //Create object
                        id sub = [self makeObject:[[class alloc]init] fromDictionary:relationshipObj];

                        [allSubObjects addObject:sub];
                    }

                    [result setValue:allSubObjects forKey:pNameString];
                }else{
                    //If so set the property for the key
                    [result setValue:[dict objectForKey:key] forKey:key];
                }

            }else{
                //NSLog(@"%@ did not respond to : %@", result, key);
            }

        }

        //Return result
        return result;
    }

}

EDIT:
Instruments shows these two items most likely the culprits. What's the best way to fix this?
//Cast const char to string
                    NSString *pNameString = [NSString stringWithFormat:@"%s",name];
                    NSString *typeString = [NSString stringWithFormat:@"%s",type];

A: 1) [NSString cStringUsingEncoding]
This allocate some memory internally which will not freed until the NSString object is deallocated. I don't know exactly but could it be possible repeatedly sending cStringUsingEncoding incur unused memory building up?
2) property_copyAttributeValue
Documentation says,

Return Value A C array of pointers of type objc_property_t describing
  the properties declared by proto. Any properties declared by other
  protocols adopted by this protocol are not included. The array
  contains *outCount pointers followed by a NULL terminator. You must
  free the array with free().

You need to free const char *type.
3) NSMutableArray *allSubObjects = [[NSMutableArray alloc]init]
It should be NSMutableArray *allSubObjects = [NSMutableArray array].
4) Object creation
Class class = NSClassFromString(pNameString);
//Create object
id sub = [self makeObject:[[class alloc]init] fromDictionary:relationshipObj];

I'd put this code block in its own autorelease pool.
[class alloc]init] is also suspicious.


text:
Q: Find a random unanswered question I'd like to find a random unanswered question on my site.  I know of the 'Unanswered' tab on the All Questions page (/questions), but that sorts by votes.  Is there a way to get it to sort randomly?
Someone else suggested to me that they'd periodically like to look at a random set of old unanswered questions.  Currently, when going to that page, they'll always see the same ones.  Is there a way to be presented with random ones to look at?


text:
Q: react-router-dom v6: Does v6 support for class components? I need help to fix this error with the best way I don't want to recall component inside withRouter with props
import { useNavigate } from 'react-router-dom'
import { Outlet } from 'react-router-dom'

class App {
  componentDidMount(): void {
    const navigate = useNavigate()
    navigate('/phone')
  }

  render(): React.ReactNode {
    return (
      <div className='App'>
         <Outlet />
      </div>
    )
  }
}

export default App

I try to navigate between two class components and I want to use animaiton between two classes via navigation
I search on the best to solve this error


text:
Q: RandomForest Classifier Output After my model prints out the output, it looks something like this
id        val
234       0.99
235       0.3
236       0
237       0.92

i wanted the val column to be binary, so did thresholding.
test[test["val"] < 0.5] = 0
test[test["val"] >= 0.5] = 1

after thresholding, for some reason my output looks like this
id        val
1         1
0         0
0         0
1         1

how do i make sure the id column doesn't change?

A: The condition you're providing only gives the rows that should change. Use loc and provide the column that should change as well.
test.loc[test["val"] < 0.5, "val"] = 0
test.loc[test["val"] >= 0.5, "val"] = 1

Output:
    id  val
0  234  1.0
1  235  0.0
2  236  0.0
3  237  1.0