text:
Q: dropping string from a series based on character length with list comprehension Python I have this series in a dataframe of df:
column1                     column2   column3
needs n before mi toilets   2013      sport

I want to drop string in column1 with character counts below 4 times so that my dataframe would look like this:
column1               column2   column3
needs before toilets   2013      sport

I tried list simple for loop with this code:
for i in df['column1'].str.split():
    for j in i:
        if len(j) < 4:
            df['column1'].drop(j)

but I got error saying:
"['n'] not found in axis"

I also tried to simplify the code to list comprehension, but so far I don't get the good code. This is my attempt to do that but with print (j) as my output:
 [print(j) for i in df['column1'].str.split() for j in df['column1'] if len(j) < 4]

and I got no return for that code.
Anyone has any idea why? thank you

A: Use pandas.Series.str.findall with join:
df['column1'].str.findall('\w{4,}').str.join(' ')

Output:
0    needs before toilets
Name: column1, dtype: object

A: df['column1'] = ' '.join(j for i in df.column1 for j in i.split() if len(j)>4)

print(df)
          column1         column2 column3
0  needs before toilets     2013   sport

A: Here is the complete solution  using the str join from pandas
df = pd.DataFrame(data = {"column1":["needs n before mi toilets"],"column2":
                                     ["2013"],"column3": ["sport"]})
df["column1"] = df['column1'].str.findall('\w{4,}').str.join(' ')

now the data frame contains the updated string in column1


text:
Q: Populating Two UITableView in the same View I have 2 UITableView in the same View and my question is how to populate them with different data in the viewDidLoad method? thanks.

A: You populate them in the
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

and in that function you can compare the tableView to see what table it is, and load the appropriate data for that table.
//Assume the following property
@property (nonatomic, retain) NSDictionary *myData;

add this to the Code file
- (NSDictionary) myData
{
    if (myData == nil) //Notice I am accessing the variable, not the property accessor.
    {
        NSString *filePath=[[NSBundle mainBundle] pathForResource:@"someName" ofType:@"plist"];
        myData = [[NSDictionary dictionaryWithContentsOfFile:filePath] retain];
    }
    return myData;
}

then when you access the self.myData property it will open up if it is not opened already.

A: To answer the plist part of your question:
NSString *filePath=[[[NSBundle mainBundle] pathForResource:@"someName" ofType:@"plist"] retain];
NSDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:filePath] retain];

So just use two of these, one for each table, then just have two tableView, as it appears you already understand.

A: All delegate and datasource protocol methods always pass a pointer to the tablesView they are called for. Just do an if to check which is meant in each method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "There is no such file sbjson.h" chimpkit I am trying to subscribe a maillist. I need to use mailchimp API for it. I know chimpkit2 is the wrapper for objective-c. I downloaded a sample project using this link: https://github.com/mailchimp/chimpkit2 and tried to run it but it did not work. I gives me "There is no such file sbjson.h" error. I tried to include sbjson framework to my project but it gave other errors this time.
How can I make it work?
Thanks

A: You may have forgotten to import the json-framework dependency. From the Chimpkit docs:

cd Lib/ChimpKit
git submodule init
git submodule update


text:
Q: How to add 3 elements in Bootstrap's modal header? I need my modal to have 3 elements in it:
To the left: a button
In the center: a title
To the right: the close button
When you look at my modal it seems like I achieved what I need, but in reality, my title is not centered.  Here's my code:

.modal-dialog {
  max-width: 90%;
}

.modal-header {
  border: none;
}

.modal-title-filter {
  color: #2D2D2D;
  font-size: 1.2em;
  text-align: center;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  <button class="btn btn-primary">Limpiar filtros</button>

Filtros

  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                      </button>

A: the title is centered, centered with respect to its container h5, no to the modal-header, but if you want the title looks centered with respect to modal-header you can edit the margin-left of your title for that, try with this:
.modal-header .modal-title{
  margin-left: -20px;
}

The higher the negative value the title will be moved to the left or more centered according to your taste.
I hope i was help you. Regards

A: You can achieve something like this by setting the display of the modal header to flex, and justifying the content by the space between the items.
Note: I had to add a thing of margin-left:0 to the close button as it has a declaration of margin-left:auto.

.modal-dialog {
  max-width: 90%;
}

.modal-header {
  border: none;
}

.modal-title-filter {
  color: #2D2D2D;
  font-size: 1.2em;
  text-align: center;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  <button class="btn btn-primary">Limpiar filtros</button>

Filtros

  <button type="button" class="close" style="margin-left:0;" data-dismiss="modal" aria-label="Close">
                        ×
                      </button>


text:
Q: How To Integrate ReactJS with OctoberCMS I am trying to integrate ReactJS with OctoberCMS with react application residing inside a directory named react inside of the OctoberCMS installation. I am unable to set the routing properly. Hitting the URL directly for example http://example.com/react/blog results in a 404 page. If I navigate to the same url (using my navbar) after first visiting the homepage I am able to open the page successfully. Please help me setting the routes correctly.
Also how shall I couple the two(react and octoberCMS). I think that my approach of keeping the react build inside a folder in the OctoberCMS install is false. What should be the correct approach?
In package.json I placed "homepage": "/react/" it works fine but opening the page in a new tab results in a 404 page rendered by OctoberCMS
I also tried <BrowserRouter basename = {'react'}> With this I end up with a url looking like http://example.com/react/react/about-us/
I tried placing the build content directly inside the root directory of octoberCMS installation, resulting in a straight up 404 page on hitting my base url.
<BrowserRouter>
  <TopBar />
  <Switch>
    <Route path={ `${process.env.PUBLIC_URL}/`} exact component={ HomePage} />
    <Route path={ `${process.env.PUBLIC_URL}/about-us`} exact component={ AboutUs} />
    <Route path={ `${process.env.PUBLIC_URL}/enquiry`} exact component={ Enquiry} />
    <Route path={ `${process.env.PUBLIC_URL}/contact`} exact component={ ContactUs} />
    <Route path={ `${process.env.PUBLIC_URL}/blog`} exact component={ Blog} />
    <Route path={ `${process.env.PUBLIC_URL}/terms`} exact component={ Terms} />
    <Route path={ `${process.env.PUBLIC_URL}/privacy-policy`} exact component={ PrivacyPolicy} />
    <Route path={ `${process.env.PUBLIC_URL}/request-purchase-offer`} exact component={ RequestPurchaseOffer} />
    <Route path={ `${process.env.PUBLIC_URL}/sell-now/benefits`} exact component={ Benefits} />
    <Route path={ `${process.env.PUBLIC_URL}/sell-now/how-dorrmat-works`} exact component={ HowDorrmatWorks} />
    <Route path={ `${process.env.PUBLIC_URL}/sell-now/customer-reviews`} exact component={ CustomerReviews} />
    <Route path={ `${process.env.PUBLIC_URL}/sell-now/offers`} exact component={ Offers} />
    <Route path={ `${process.env.PUBLIC_URL}/sell-now/faqs`} exact component={ FAQS} />
    <Route component={ NoMatchFound} />
  </Switch>
  <Footer />
  <button onClick={ ()=> this.scrollToTop(500)} className = "scroll-top"></button>
</BrowserRouter>

I expect the react routing handling my routes instead of octoberCMS routing to a 404 page. Also When I try to open the page in a new tab it should not redirect to a 404 page.
Any kind of suggestion on how should I couple these two together would be helpful.

A: If your React application lives inside OctoberCMS is perfectly normal that all paths are handled by OctoberCMS's router. You can solve your issue in two ways:

*

*You can instantiate your app from a page handled by OctoberCMS, keeping in mind that you will have to define a route to redirect all requests to the entry point of your app. (you'll have to create a custom empty plugin and in its root create a routes.php file in order to define it)

*Alternatively, in the OctoberCMS .htaccess file you can whitelist the path to your entry point, in order to bypass OctoberCMS
Hope this helps, happy coding!


text:
Q: Cannot deploy Spring Boot application I'm currently evaluating CloudControl as platform provider for my Java based applications.
I created a very simple Spring Boot (https://github.com/mhmpl/gradle-example-app) app with Gradle but I'm unable to deploy the app.
There are no errors in the Error log which could give me some information. However, this is the output of the Deploy log:
8/3/14 12:53 PM lxc-1272 INFO Container did not come up within 120 seconds.
8/3/14 12:53 PM lxc-1250 INFO Waiting for the container to be reachable...
8/3/14 12:53 PM lxc-1272 INFO Waiting for the container to be reachable...
8/3/14 12:52 PM lxc-1250 INFO Waiting for the container to be reachable...
8/3/14 12:52 PM lxc-1272 INFO Waiting for the container to be reachable...
8/3/14 12:52 PM lxc-1250 INFO Waiting for the container to be reachable...
8/3/14 12:52 PM lxc-1272 INFO Waiting for the container to be reachable...
8/3/14 12:51 PM lxc-1250 INFO Deploying ...

Finally, the app is not deployed and I cannot see an error which I've potentially made. I already tried to set the memory to 1024MB and added a second container, but that did not change anything at all.

A: You need to bind the webserver to the correct port, which is defined in the PORT environment variable.


text:
Q: load testing with websockets -JMeter? From what I have found and tested, you can use the WebSocket Sampler for Apache JMeter, however you cannot record your test requests because the WebSocket request will not be passed appropriately through and back from the Java Proxy Server.
So, what are my options?  I can build every request by hand instead of recording - and keep using JMeter -very tedious.
Build a new WebSocket Sampler?
Build onto the Java Proxy Server?
Or use something besides JMeter?
Before I dive into another deep pit, a little good advice would be much appreciated!  Thank you so much!


text:
Q: Python - Split string into characters while excluding a certain substring I'm trying to split up a string of characters into a list while excluding certain substrings.
For example:
>>> sentences = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
>>> substring1 = '<s>'
>>> substring2 = '</s>'
>>> print(split_string(sentences))
['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's',
'.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd',
'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']

As you can see, the string is split up into characters, except for the listed substrings. How can I do this in Python?

A: You could use re.findall for this. :)
import re
sentences = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
print(re.findall(r'<\/?s>|.',sentences))

OUTPUT
['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', '.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']

A: You can use re.split:
import re
s = '<s>I like dogs.</s><s>It\'s Monday today.</s>'
result = [i for b in re.split('\<s\>|\</s\>', s) for i in ['<s>', *b, '</s>'] if b]

Output:
['<s>', 'I', ' ', 'l', 'i', 'k', 'e', ' ', 'd', 'o', 'g', 's', '.', '</s>', '<s>', 'I', 't', "'", 's', ' ', 'M', 'o', 'n', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y', '.', '</s>']

A: Are you trying to exclude from the above output the <s> and </s> substrings?
If so:
>>> sentences = '<s>I like dogs.</s><s>It\'s Monday today</s>'
>>> substrings = ['<s>','<\s>']
>>> [character for character in split(sentences) if character not in substrings]

will give the expected output.


text:
Q: Prove that theory is not Henkin one The definition as it was given to me: The theory $T$ is Henkin theory, if and only if for every formula $\phi$ in $T$ we have constant $c$ language of $T$ such as $T \vdash \exists x \phi \to \phi(x/c)$.
How I have language $\mathcal L = \{ c \}$, where $c$ is a constant, and I have to prove that theory $T = \{ \emptyset \}$ over language $\mathcal L$ is not a Henkin one. My problem is that I don't know how to even prove this, if there is no formulas in the language to "check Henkin condition". How do I approach this task?

A: If the theory $T$ has no non-logical axioms (this is my reading of $T=\{ ∅ \}$) then - by soundness - it can prove only valid formulae.
Assuming that $T$ is an Henkin theory, then for every formula $ϕ$ in the language of $T$ we have a constant $c$ such that $T ⊢ ∃xϕ→ϕ[x/c]$.
Thus, also : $T \vdash ∃x \ \lnot \phi \to \lnot \phi [x/c]$, and then, by contraposition :

$T \vdash \phi [x/c] \to \forall x \ \phi$

which is clearly invalid.


text:
Q: URL rewrite results in a 404, but everything should work! So I modified this code that I found elsewhere and stuck it in a plugin. The plugin works; I can see the .htaccess file updated when I hit save on the permalinks page.
add_action( 'init', 'wpse26388_rewrites_init' );

function wpse26388_rewrites_init(){
    add_rewrite_rule(
        'microsoft/mcsa/',
        'wp-content/microsoft.php?cert=mcsa',
        'top' );
}

add_filter( 'query_vars', 'wpse26388_query_vars' );

function wpse26388_query_vars( $query_vars ){
    $query_vars[] = 'cert';
    return $query_vars;
}

.htaccess
RewriteEngine On
RewriteBase /training/
RewriteRule ^index\.php$ - [L]
RewriteRule ^microsoft/mcsa/ /training/wp-content/microsoft.php?cert=mcsa [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /training/index.php [L]

I can go to /training/wp-content/microsoft.php?cert=mcsa and the page loads. But when I try to access it via /microsoft/mcsa, it does not and gives me a 404.
What gives? And is there any way to enable error logging to see where it's trying to go? Enabling debug mode in wp_config didn't seem to do anything.


text:
Q: "git pull" fails, but only remotely? When I try to ssh -C user@my_server 'cd /home/me/my_repo' it works.
When I try to ssh user@my_server, then cd /home/me/my_repo' and then git pull it works.
But when I try to ssh -C user@my_server 'cd /home/me/my_repo' && git pull it fails with Permission denied (publickey).
My question really is : Why does it even work locally? When I do ssh -C user@my_server 'cd /home/me/my_repo && git pull'does git care about what ssh key I used to connect to my_server, not just the ssh key used to connect to my_repo's remote?

A: SSH by default will use the keys inside your .ssh directory. This is usually in ~/.ssh/.
It seems you wrote the following command which may be a typo:
ssh -C user@my_server 'cd /home/me/my_repo' && git pull

The above command will run ssh, and after a successful completion (exit status 0), run git pull. I am just saying this as it may be related to your issue and hopefully help without being too pedantic.
To answer your question, git will use by default the keys in your .ssh folder on the machine where the command is run.
Therefore is should try to use the keys in the home of user@my_server.
Git does not know about the keys on servers outside of where it resides.


text:
Q: Insert data from auto generated textbox to SQL Server database I have created a code for generating a text box in vb.net using button click and function
 Public Function AddNewTextBox() As System.Windows.Forms.TextBox
    Dim txt As New System.Windows.Forms.TextBox()
    Me.Controls.Add(txt)
    txt.Top = cLeft * 30
    txt.Left = 100
    'txt.Text = "TextBox " & Me.cLeft.ToString
    cLeft = cLeft + 1
    txt.ForeColor = Color.DarkGreen
    txt.BackColor = Color.Gray
    txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
    txt.Size = New Size(237, 31)
    txt.Location = New Point(156, 130 + top1)

    Return txt
End Function

In the button
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'call the function
        AddNewTextBox()

End Sub

I have tried this
cmd.CommandText = "INSERT INTO userlog ([username],[userlastname]) Values ( @username) "
cmd.Parameters.AddWithValue("@username", txt.Text(i).Text)
cmd.Parameters.AddWithValue("@userlastname", txt.Text(i).Text)

but getting an error in
txt.Text(i)

since txt is declared only in AddNewTextBox function.
I have made 3 auto generated text boxs
How do I save this data inside the text box to the database?

A: Since the TextBox is being added to the control collection of the Form, you can use the OfType enumerable method to get all TextBox controls. What's more I would probably assign the Tag of the generated TextBox to the desired field name so that you can query the control collection for the first instance of the TextBox who's tag equals the desired field.
Also its worth mentioning that you can use the With keyword to get rid of some unnecessary code.
With all that being said, your AddNewTextBox method would look like this:
Public Function AddNewTextBox(ByVal fieldName As String) As System.Windows.Forms.TextBox
    Dim txt As New System.Windows.Forms.TextBox()
    Me.Controls.Add(txt)

    With
      .Top = cLeft * 30
      .Left = 100
      '.Text = "TextBox " & Me.cLeft.ToString
      cLeft = cLeft + 1
      .ForeColor = Color.DarkGreen
      .BackColor = Color.Gray
      .Font = New Font("Arial", 14.0, FontStyle.Regular)
      .Size = New Size(237, 31)
      .Location = New Point(156, 130 + top1)
      .Tag = fieldName
    End With

    Return txt
End Function

Your Button's click event would look like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'call the function
    Dim txt As TextBox = AddNewTextBox("username")
End Sub

And your parameterized query would look like this:
Dim usernameTextBox As TextBox = Me.Controls.OfType(Of TextBox).FirstOrDefault(Function(txt) txt.Tag IsNot Nothing AndAlso txt.Tag = "username")

If usernameTextBox IsNot Nothing Then
  cmd.Parameters.AddWithValue("@username", usernameTextBox.Text)
End If

A: Add a FlowlayoutPanel to your form and set the FlowDirection to TopDown. (as commented by @jmcilhinney) This saves calculating the position of the text boxes.
It doesn't make sense to have a function returning a text box when you never use the return value.
The data access code uses the .Add method suggested by @SMor. See
http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
I had to guess at the datatypes. Check your database for correct types.
The values come from the controls collection of the FlowLayoutPanel where the controls were added.
Using blocks ensure that you database objects are closed and disposed even if there is an error. Pass the connection string directly to the constructor of the connection and the command text and connection directly to the constructor of the command.
Public Sub AddNewTextBox()
    Dim txt As New System.Windows.Forms.TextBox()
    txt.Name = "user" & nameTextBox.ToString
    txt.ForeColor = Color.DarkGreen
    txt.BackColor = Color.Gray
    txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
    txt.Size = New Size(120, 30)
    FlowLayoutPanel1.Controls.Add(txt)
End Sub

Private Sub UpdateUsers()
    Using cn As New SqlConnection("Your connection string")
        Using cmd As New SqlCommand("INSERT INTO userlog ([username],[userlastname]) Values ( @username, @userlastname);", cn)
            cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = FlowLayoutPanel1.Controls(0).Text
            cmd.Parameters.AddWithValue("@userlastname", SqlDbType.VarChar).Value = FlowLayoutPanel1.Controls(1).Text
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    AddNewTextBox()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    UpdateUsers()
End Sub

EDIT
    For Each tb As TextBox In FlowLayoutPanel1.Controls
        If tb.Text = "" Then
            MessageBox.Show("Please fill all text boxes before Updating")
            Return
        End If
    Next


text:
Q: Change text on hover I want to change a text of selected input to ccc. I tried using .hover, but nothing happened.

$(function() {
  $(".xxx").each(function() {
    $(this).on("click", function() {
      if ($(this).is(":checked")) {
        $(this).next().html("bbb");
        $(this).parents(".checkbox").toggleClass("selected");
      } else {
        $(this).next().html("aaa");
        $(this).parents(".checkbox").toggleClass("selected");
      }
    });
  });
  $(".checkbox.selected").each(function() {
    $(this)
    .on("mouseover", function() {
      $(this).find("p").html("ccc");
    })
    .on("mouseout", function() {
      $(this).find("p").html("bbb");
    });
  });
});
.checkbox.selected:hover {
  background: red;
}

    <input class="xxx" type="checkbox"/>

aaa

    <input class="xxx" type="checkbox"/>

aaa

A: This returns an empty jQuery collection, because no check boxes have the selected class when it runs:
$(".checkbox.selected")

Instead, you could use a delegated event handler like this:
$(document)
  .on('mouseover', '.checkbox.selected', function() {
    $(this).find("p").html("ccc");
  })
  .on('mouseout', '.checkbox.selected', function() {
    $(this).find("p").html("bbb");
  });

Snippet

$(function() {
  $(".xxx").each(function() {
    $(this).on("click", function() {
      if ($(this).is(":checked")) {
        $(this).next().html("bbb");
        $(this).parents(".checkbox").toggleClass("selected");
      } else {
        $(this).next().html("aaa");
        $(this).parents(".checkbox").toggleClass("selected");
      }
    });
  });

  $(document)
    .on('mouseover', '.checkbox.selected', function() {
      $(this).find("p").html("ccc");
    })
    .on('mouseout', '.checkbox.selected', function() {
      $(this).find("p").html("bbb");
    });
});
.checkbox.selected:hover {
  background: red;
}

    <input class="xxx" type="checkbox"/>

aaa

    <input class="xxx" type="checkbox"/>

aaa


text:
Q: Is there a way to disable built-in deadlines on App Engine dev_appserver? I realize that dev_appserver.py is meant to simulate the production App Engine environment as much as possible, but I'm having trouble debugging an app locally due to slow connection issues (I keep getting DeadlineExceededError exceptions). Since it's not the connection itself that I'm concerned about, is there any way to temporarily disable/extend the timeout for urlfetch (and others) just for the development environment? Unfortunately, the app does need to be connected to a live webservice, and I can't just patch in a dummy response in this case.
This may be a simple fix for someone who knows more about the innards of the SDK, but I haven't had much luck in my Googling. I would appreciate any help or advice you may have.

A: When running on the development server, you could set a higher default urlfetch deadline:
import os
if os.environ['SERVER_SOFTWARE'].startswith('Dev'):
    from google.appengine.api import urlfetch
    urlfetch.set_default_fetch_deadline(60)


text:
Q: Errors Pushing to Heroku (node.js) When I push a default express app to heroku I get the following error.  I've ensured I am up to date with heroku-toolbelt etc but it appears to be an error from the heroku side?  Has anyone seen this?  It pushes alright and works as expected but I suspect this could cause issues in the future.
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (4/4), 404 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)

-----> Heroku receiving push
-----> Node.js app detected

/app/slug-compiler/buildpacks/nodejs2/vendor/json/json:425
  return runInNewContext("(" + JSON.stringify(datum) + ")" + lookupCode);
         ^
TypeError: Cannot read property 'node' of undefined
    at evalmachine.<anonymous>:1:118
    at lookupDatum (/app/slug-compiler/buildpacks/nodejs2/vendor/json/json:425:10)
    at Socket.<anonymous> (/app/slug-compiler/buildpacks/nodejs2/vendor/json/json:628:24)
    at Socket.emit (events.js:61:17)
    at Socket._onReadable (net.js:656:51)
    at IOWatcher.onReadable [as callback] (net.js:177:10)

/app/slug-compiler/buildpacks/nodejs2/vendor/json/json:425
  return runInNewContext("(" + JSON.stringify(datum) + ")" + lookupCode);
         ^
TypeError: Cannot read property 'npm' of undefined
    at evalmachine.<anonymous>:1:118
    at lookupDatum (/app/slug-compiler/buildpacks/nodejs2/vendor/json/json:425:10)
    at Socket.<anonymous> (/app/slug-compiler/buildpacks/nodejs2/vendor/json/json:628:24)
    at Socket.emit (events.js:61:17)
    at Socket._onReadable (net.js:656:51)
    at IOWatcher.onReadable [as callback] (net.js:177:10)
-----> Resolving engine versions
       Using Node.js version: 0.4.7
       Using npm version: 1.0.94
-----> Fetching Node.js binaries
-----> Vendoring node into slug
-----> Installing dependencies with npm

       express@2.5.8 /tmp/build_1m5t2ah1oglfb/node_modules/express
       connect@1.8.5 /tmp/build_1m5t2ah1oglfb/node_modules/express/node_modules/connect
       qs@0.4.2 /tmp/build_1m5t2ah1oglfb/node_modules/express/node_modules/qs
       mime@1.2.4 /tmp/build_1m5t2ah1oglfb/node_modules/express/node_modules/mime
       formidable@1.0.9 /tmp/build_1m5t2ah1oglfb/node_modules/express/node_modules/connect/node_modules/formidable
       mkdirp@0.3.0 /tmp/build_1m5t2ah1oglfb/node_modules/express/node_modules/mkdirp
       jade@0.20.3 /tmp/build_1m5t2ah1oglfb/node_modules/jade
       commander@0.5.2 /tmp/build_1m5t2ah1oglfb/node_modules/jade/node_modules/commander
       mkdirp@0.3.0 /tmp/build_1m5t2ah1oglfb/node_modules/jade/node_modules/mkdirp
       Dependencies installed
-----> Discovering process types
       Procfile declares types -> web
-----> Compiled slug size is 3.1MB
-----> Launching... done, v7

A: This was a heroku issue and appears to have gone away.

A: I'm going to go out on a limb here and say that it has something to do with parsing your package.json. Take a look at Specifying a version of Node.js/npm. Is everything valid JSON?
My guess is that this evalmachine is evaluating your package.json in a sandbox environment (see vm.runInNewContext), and lookupCode is some way of, first, checking engines.node, then engines.npm. Are both of these accessible? If this is the truth, then shame on Heroku's Devs for not expecting this error and accounting for it with some useful message. They're usually good about such things.


text:
Q: bash find returning path with leading '.' how can I eliminate this character from return string? I'm running the following line from the apache logs directory to move older (previously zipped) logs to a storage location:
/usr/local/apache2.2/logs$ find . -name '*.gz' -exec cp {} /home/itadmin/temp4{} \;

The result is slightly off due to the '.' included in the returned file path:
cp: cannot create regular file `/home/itadmin/temp4./default/error/error.1315029600.gz': No such file or directory

Is there a simple way to eliminate the '.' from the file path while still utilizing the above command as closely as possible to the way it's written now?

A: You can copy all files in one invocation of cp like this:
$ find . -name '*.gz' -exec cp --target-directory=/home/itadmin/temp4 {} +

Or just add a slash to your original command:
/usr/local/apache2.2/logs$ find . -name '*.gz' -exec cp {} /home/itadmin/temp4/{} \;

A: I often use
find * -name ...

It's not exactly equivalent; it skips anything in the current directory whose name starts with ..  That's ok if you don't have, or don't care about, any such files or directories.  And it's great if you specifically want to skip them (e.g., .git).
Or you can filter the output of find.  For example (not tested)
find . -name ... | sed 's/^\.\/\(.\)/\1/'

It searches for, and leaves in place, a single character following ./ to avoid mangling the line consisting of just ./ (not needed if you have -type f).  If you're going to use that, consider adding the filter as a command in your ~/bin directory.

A: Don't specify the . directory explicitely.
/usr/local/apache2.2/logs$ find -name '*.gz' -exec cp {} /home/itadmin/temp4/{} \;

A: Instead of using name, use print0, which will correctly handle full pathnames and files with spaces or other unusual characters. Also, you need to wrap {} in single quotes to prevent shell interpretation.
find . -print0 '*.gz' -exec cp '{}' '/home/itadmin/temp4{}' \;


text:
Q: Settings and network missing, cannot connect to the internet Had to type this on a phone and it's sucking lately so i apologize for any typoes/autocorrect snafus i miss while proofing.
I have checked all hardware (the Ethernet port, the cables, etc).
A few days ago i suddenly had no internet on my desktop (running 18.04.1 LTS with Gnome), and my GUI Settings disappeared so i couldn't make any changes to my network settings.
I've looked around for help with the situation but can't seem to find someone with both these problems at once, it's either one or the other.
I've verified my /etc/init.d/networking and network-manager files and they seem to match all examples I've seen.
My problem is that i can't restore the GUI Settings without an internet connection, and i can't connect to the internet without my settings (i assume part 2, as i can't get far enough to test that theory).
I've checked my logs and such and all get is

Failed to start network-manager

but nothing else helpful.  If i try to reinstall or just install the network manager or the gui settings it just does it's thing then tries to contact my PPAs, even though i disabled them all and selected to use the dvd instead.
I'm hoping someone else has had this problem and can help, or who is talented enough to just know the fix.  It's my desktop which makes it hard to post dumps and post them, same with screenshots, as i can only use my cell to access this site, so please only request those if it's really necessary.
Re-installing the OS is going to be an absolute last option as i have a lot of things installed with very customized settings throughout (i never changed the network settings if that thought just popped up to you, it's been untouched since my original install last April).  I know i can backup before, and restore settings after, a reinstall but i never know what files to backup, or have a complete list of what i have personally installed as many items are background. (Oh, and I've not installed, uninstalled, or altered any programs on the system since the new year, so i can't blame that either.) And I'm sure I'd just restore the same network settings as i never know if and what to restore after a reinstall, and then the loop States again.

A: I had issues with this and I went into the grub menu and selected a previous image to get this working

A: Actually you can set you network using legacy way - by editing /etc/network/interfaces.
First you need to list all your interfaces by ip a.
Then, you need to edit interface that you normally use for Internet connection.
It should look like that:
*name of your interface* auto
iface *name of your interface* inet dhcp

Then you can do
ip link set name of your interface down && ^down^up
That will reboot you interface and enable configuration.


text:
Q: Number of files and directories in linux directory, only in level 2 The instruction
$ ls | wc -l
gives us the number of directories and files that are in a certain directory without counting those that exist within the subdirectories of this first level, that is, it gives us the number in a non-recursive way.
How could you know the number of files and directories that are only in the second level of that same directory? That is, the number of subdirectories and files in the subdirectories of the main directory, also in a non-recursive way, only at level 2.
The instruction:
$ shuf -ezn 7 directory/*/*/* | xargs -0 -n1 echo
gives us 7 files or subdirectories random  chosen from the second level of the main one. It works perfectly, but I am unable to reason a similar instruction for what I want to achieve
I hope I have explained myself. Thank you

A: There are probably other better options, but I think I've found it:
$ find directory/  -mindepth 2 -maxdepth 2 | wc -l

gives me the expected result.
Hope it helps someone

A: This command should work:
$ ls * | wc -l


text:
Q: Is possible to communicate via Bluetooth PAN in iOS with tethered devices I have a device with which I share my connection from iOS device though Bluetooth (Bluetooth PAN).
I wonder is it possible to access to create a server on iPhone in PAN network and access it from device or create a server on device and access it from iPhone.
Does anyone have this kind of experience? I know it definitely could be done with Android devices.

A: Yes it is possible. For example, see this question about setting up such a server on an iOS device.
You can do a very quick test by installing a network diagnostics app - e.g. I found one called Console Server by SikYi Chan on the App Store.
In this app, I added a "server connection" on port 12345 and started the server. Tethering from my Mac, in System Preferences -> Network I found that my tethered IP address was 172.20.10.2. I guessed the iPhone was therefore on 172.20.10.1, and did this:
% telnet 172.20.10.1 12345
Trying 172.20.10.1...
Connected to 172.20.10.1.
Escape character is '^]'.
hello

And in Server Console in the iOS app I got:


text:
Q: Extract multiple elements from each list within list oldlist = [[1,2,3,4,5,6,7,8,9,....30], [1,2,3,4,5,6,7,8,9,...30], ...]

I need to extract elements [0:5] [8:13] [17:21] of each list within a list to create newlist. What I have so far, but it does not work (just gives me a list of empty lists):
newlist = [item[0:5][8:13][17:21] for item in oldlist]

A: Use + to concatenate lists.
newlist = [item[0:5] + item[8:13] + item[17:21] for item in oldlist]

A: Try this.
newlist = [item[0:5]+item[8:13]+item[17:21] for item in oldlist]

item[0:5][8:13][17:21] this means to take a slice of item from index 0 to 4, which returns a new list of length 5 now take a slice from the returned list from index 8 to 12 which returns an empty list.
>>> a
[1, 2, 3]
>>> a[0:2]
[1, 2]
>>> a[0:2][5:15]
[]

Why empty is being returned is stated explicitly in the docs. Click here

The slice of s from i to j is defined as the sequence of items with index *k * such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.


text:
Q: Python: Why my module didn't instantiate an object via exec() statement? I created my own version of GridSearchCV module from sklearn.model_selection library. My version includes iterating through each parameter one by one instead of looking for all possible combinations. For example for a SVR model, if we have three parameters defined as follows:
   {
    'gamma' : np.arange(0.0, 1.0, 0.1),
    'C': np.arange(1, 10, 1),
    'epsilon': np.arange(0.0, 1.0, 0.1)
    }

The algorithm would in the first turn find one best gamma coefficient (out of ten). Then it moves to assigning C parameter with given value of gamma. After ten iterations it moves to epsilon and assigns optimal epsilon value with given set of [gamma, C] parameters. This gives us in total 30 combinations to check instead of 1000 (10*10*10).
I'd like to import my opt_grid_search object into my projects, like below:
from own_udf_functions import show_description, opt_grid_search
The code of the object begins with dynamic statement that creates object that is going to be optimized:
exec_string = 'opt_object = ' + object_name + '(' + def_params + ')'
which returns for example:
opt_object = SVR(kernel = 'rbf')
However, when I try to use the code in another script as below:
opt_grid_search(object_name, params_set, X_train, y_train, X_test, y_test,
                cross_val = 2, def_params = def_params)

following error appears:
    *File "C:\Users\Marek\Desktop\Python\Github\Kernele\Kaggle Competitions\own-udf-
   functions\own_udf_functions.py", line 40, in opt_grid_search
    opt_object.fit(X_train,y_train)
    NameError: name 'opt_object' is not defined*

It seems that opt_grid_search function didn't execute the following line of code:
opt_object = SVR(kernel = 'rbf')
and the object named opt_object wasn't actually created.
I think it has to do with classes, but I would like to ask you to help me better understand what actually happened in this error. I think it is a crucial knowledge that would help me a lot write more 'pythonic' codes instead of defining all of the functions in every single code.
Secondly, please let me know if such optimization makes sense as well or is it needed for the GridSearch to go through all possible combinations.
I tried to keep this description as short as possible, however if you would like to see / need it for the reference, my code is accessible below:
https://github.com/markoo26/own-udf-functions

A: The issue here is the exec function and the namespace/scope in which it operates. I'm struggling to get my head around this myself but essentially exec() doesn't work for assignment used inside a function in this way. The easiest workaround is to use eval() instead which explcitly returns an object. So end up with something like:
exec_string = object_name + '(' + def_params + ')'
opt_object = eval(exec_string)


text:
Q: How to Make array_diff ignore One Value in PHP If you do an array_diff between two values:
$ignore = array_diff($arr1, $arr2);

How can you make it avoid removing one specific value from $arr1?

A: Here are two arrays for example.
$arr = ['something', 'another thing', 'three things'];
$arr = ['something', 'another thing', 'different thing'];

And the value you want to keep:
$keep = 'something';

If you need that certain value to always be there, it probably would be easiest to just explicitly add it after doing the diff.
$ignore = array_diff($arr1, $arr2);
$ignore[] = $keep;

but if you only need it to not be removed if it is present, then you can use array_udiff.
$ignore = array_udiff($arr1, $arr2, function($a, $b) use ($keep) {
    if ($a == $keep) return -1;
    return $a == $b ? 0 : 1;
});


text:
Q: Angular Change Detection not triggered, parts of viewlayer not updating. ChangeDetectorRef not solving issue. I have a component:
import { Component, OnInit, Input, NgZone, ChangeDetectorRef } from '@angular/core';
import { Product } from '../product'; // data types
import { PRODUCTS } from '../mock-products'; // database
import { CartService } from '../cart.service'; // service
import { Subscription } from 'rxjs/Subscription';

@Component({
 selector: 'app-checkout',
 templateUrl: './checkout.component.html',
 styleUrls: ['./checkout.component.css']
 })

export class CheckoutComponent implements OnInit {

 get shoppingCart(): Product[] {
   const result = this.cartService.get();
   return result;
  }
 cartTotal: number;
 @Input() PRODUCTS: Product;

 constructor(private cartService: CartService, private zone: NgZone,
   private changeDetectionRef: ChangeDetectorRef) {
     this.cartService.shoppingCart.subscribe((nextValue) => {
     this.changeDetectionRef.detectChanges();
     console.log('nextValue', nextValue); // returns properly
     console.log(`subscribe: ${NgZone.isInAngularZone()}`);  // RETURNS TRUE
});

 }
 ngOnInit() {
  console.log(`ngOnInit: ${NgZone.isInAngularZone()}`); // RETURNS TRUE
  this.estimatedTotal();  // THIS FUNCTION RUNS BUT IS NEVER UPDATED WITH NEW VALUES
  }

 deleteItem(id, shoppingCart) {
  console.log('id to be deleted ' + id.toString());

   const newCart = [];
   for (let i = 0; i < shoppingCart.length; i++) {
     if (shoppingCart[i].id !== id) {
    newCart.push(shoppingCart[i]);
    }
  }

this.cartService.set(newCart);
this.changeDetectionRef.detectChanges(); // THIS DOES NOT SEEM TO BE WORKING AT ALL
}

  estimatedTotal() {
    const totals = [];
      for (let i = 0; i < this.shoppingCart.length; i++) { // looping through cart
        if (this.shoppingCart != null && this.shoppingCart.length > 0) {
          totals.push(this.shoppingCart[i].price * this.shoppingCart[i].quantity);
          this.cartTotal = totals.reduce((total, amount) => total + amount);
           } else {
            this.cartTotal = 0;
        }
      }
    }

which utilizes a service to get( ) and set( ) items to localStorage:
import { Injectable, NgZone } from '@angular/core';
import { Product } from './product'; // data model
import { PRODUCTS } from './mock-products'; // database +
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { Subject } from 'rxjs/Subject';
import { CartItemComponent } from './cart-item/cart-item.component';
import { CheckoutComponent } from './checkout/checkout.component';

@Injectable()
export class CartService {
 shoppingCart: Subject<Object> = new ReplaySubject<Object>(1);
 constructor() { console.log(`cartService: ${NgZone.isInAngularZone()}`); }

 set(shoppingCart: Product[]) {
  this.shoppingCart.next(shoppingCart);
  localStorage.setItem('shoppingCart', JSON.stringify(shoppingCart));

 }
 get() {
  return JSON.parse(localStorage.getItem('shoppingCart'));
  }

  }

Here is the HTML:

  <button (click)="checkOut()">

  </button>

  ×

 Shopping Cart

     Item

     Price
     Quantity
     Total
     Delete?

      {{cartItem.productName}}

      {{cartItem.description}}
      ${{cartItem.price}}
      {{cartItem.quantity}}
      ${{cartItem.price * cartItem.quantity}}
      <button></button>

      Estimated Total:

      ${{cartTotal}}

      <button id="checkoutBtn" (click)="confirmCheckout()"> Checkout
  </button>

The issue I am running into, is that my UI is not updating the
{{cartTotal}} when new items are added, deleted, or when localStorage (via cartService) is changed in any way. I thought it might be a zone issue, perhaps some changes had been processed outside the zone, and all instances of NgZone.isInAngularZone(), returned true. I subscribed to the cartService to see if that might solve the issue, and set off ChangeDetection, this did not give me desired results either. I then tried to enforce ChangeDetection manually on the subscription, this also doesn't update my {{cartTotal}}. I've been stuck on this for over a day, any advice would be greatly appreciated!

A: You call estimatedTotal ing ngOnInit, which is only called once once the component is initialised. So it's normal that cartTotal is never updated.
You should call it whenever the cart is updated, i.e. in the subscribe method of this.cartService.shoppingCart.subscribe
this.cartService.shoppingCart.subscribe((nextValue) => {
     this.estimatedTotal();
}

A: David's solution worked partially, the value would be updated, but was always one step behind. I had two components with a sibling relationship that relied on one another, I ended up recombining these components as alone, they didn't have too much functionality. This resolved the problem!


text:
Q: What are `/t.php` GET requests coming to production server? I have recently published welcome page on my new site hosted on DigitalOcean. I'm using Node JS and nginx.
These requests targeting /t.php, POST /wls-wsat/CoordinatorPortType, POST /user/register?.
Is this a hacking attempt?
Here are nginx logs -
80.123.42.103 - - [24/Apr/2018:16:38:54 +0000] "GET /t.php?c=%5B%7B%22k%22%3A%22%5Cb%22%2C%22t%22%3A9874541096%7D%5D HTTP/1.1" 404 144 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0"
80.123.42.103 - - [24/Apr/2018:16:38:54 +0000] "GET /t.php?c=%5B%7B%22k%22%3A%22%5Cb%22%2C%22t%22%3A9874541264%7D%5D HTTP/1.1" 404 144 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0"

80.13.73.224 - - [24/Apr/2018:08:47:10 +0000] "POST /wls-wsat/CoordinatorPortType HTTP/1.1" 400 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
80.13.73.224 - - [24/Apr/2018:08:47:10 +0000] "POST /user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax HTTP/1.1" 404 153 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
80.13.73.224 - - [24/Apr/2018:08:47:10 +0000] "GET / HTTP/1.1" 200 3508 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
80.13.73.224 - - [24/Apr/2018:08:47:10 +0000] "GET / HTTP/1.1" 200 3508 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
80.13.73.224 - - [24/Apr/2018:08:47:11 +0000] "GET /rss.php?mode=recent HTTP/1.1" 404 146 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"

A: You're absolutely correct!
Someone was scanning for possible vulnerabilities on your system. For instance, the /user/register line is related to vulnerability CVE-2018-7600, which allows remote execution of arbitrary code if you're using certain versions of Drupal. The /wls-wsat/CoordinatorPortType line is likely related to vulnerability CVE-2017-10271 which allows for takeover of certain Oracle WebLogic servers. As for /t.php, I'm unfortunately unable to find any information due to the garbage indexing of modern search engines, but we can reasonably assume that it's related to yet another vulnerability that provides unrestricted root access.
It could be a targeted scan, but it could also be a script kiddie casting a wide net and hoping something sticks. I would assume it's the latter as they appear to be taking a shotgun approach to gaining root access to different kinds of systems.
You probably don't have anything to worry about, but just to be safe I would encourage you to validate that your software is up to date with all security patches and to ensure that none of those requests could be impacting any part of your system (e.g. make sure that if you're running Drupal, it's at least a properly patched version).


text:
Q: Apply validation for few sections in the same view in mvc I am developing MVC project using c#. I have one model called EmployeeEducationDetails. Lets have a look at what I have created
public class EducationList
{
  public List<EmployeeEducationDetailTable> employeeEducationList { get; set; }

  public EducationList()
  {
    employeeEducationList = new List<EmployeeEducationDetailTable>();
  }

  public virtual EmployeeMainTable employee_MainTable { get; set; }
  public ICollection<EmployeeQualificationTypeTable> employee_QualficationTypeTable { get; set; }
}

public class EmployeeEducationDetailTable
{
  public int EmployeeId { get; set; }

  public int EmployeeEducationDetailId { get; set; }

  [Required(ErrorMessage = "Select qualification")]
  public int? EmployeeQualificationTypeId { get; set; }

  [Required(ErrorMessage = "Enter institute name")]
  public string EmployeeInstituteName { get; set; }

  [Required(ErrorMessage = "Enter year of pass")]
  public DateTime? EmployeeYearOfPass { get; set; }

  [Required(ErrorMessage = "Enter percentage")]
  public string EmployeePercentage { get; set; }
}

Until now I am not facing any problem. Our requirement needs to satisfy these conditions

*

*I have to design 4 division on same view like SSLC, PUC, DEGree,
Post Degree using same model.

*Need to validate any one section among 4 divisions because education
is mandatory for employee.

*If any data entered to any division then only it has to validate.

Please give me the idea about this. Your help would be greatly appreciated.
NOTE:here am passing List.Count to create 4 division dynamically and we have to use same model i.e. EducationList

A: If your design permits, you may provide a checkbox against each division and then use 'RequiredIf' Conditional Validation approach.
Please visit the following links to know more on this:
RequiredIf Conditional Validation Attribute
Flexible Conditional Validation ASP.NET MVC with Sample Code
Hope this help you.


text:
Q: Need CSS Box/Grid layout advice UPDATED  ... Here is my latest code.

*

*Now need some way to place the Button MIDDLE or BOTTOM (vertically).

*As a complete newbie, I would welcome any other comments about the
code used here.
:) ...  cheers

*  html {
 font:   2em Georgia, sans-serif;
 color:  #7b7b7b;
 clear:  both;
 float:  justify;
}

body {
 margin: 0.5em 4.0em 0.5em 4.0em;
 padding: 1.0em 4.0em 1.0em 4.0em;
 width: 55.0em;
 height: auto;
 background-color: tan;
}
.imgclass {
 border: 0.15em solid yellow;
 margin-left: 0;
 padding-left: 0;
}
.wrapper {
    display: grid;
    grid-gap: 1.0em;
    grid-template-columns: 75% 25%;
    grid-template-areas:
   "header  header"
   "picture  button"
   "article  article"
   "footer  footer";
    background: tan;
 margin-top: 2.0em;
 margin-left: 1.0em;
    color: teal;
 width: 100%;
    }

.box {
 color: white;
 border-radius: 0.5em;
 padding: 0 2.0em 0 2.0em;
 margin: 0 0 0 1.0em;
}

.header {
 grid-area: header;
 position: relative;
 margin-left: 1.0em;
 padding-left: 1.0em;
 border: 1.0em;
 border-color: white;
 height: auto;
}

.picholder {
 grid-template-columns: 1 -1;
 grid-template-rows: 2 3;
 margin: 0;
}

.picture {
 grid-area: picture;
 grid-template-columns: 2;
 grid-template-rows: 3;
 position: relative;
 margin-left: 0;
 border-left: 0;
}

.button {
 grid-area: button;
 position: relative;
 margin-left: 1.0em;
 background: #3498db;
 background-image: -webkit-linear-gradient(top, #3498db, #11828a);
 background-image: -moz-linear-gradient(top, #3498db, #11828a);
 background-image: -ms-linear-gradient(top, #3498db, #11828a);
 background-image: -o-linear-gradient(top, #3498db, #11828a);
 background-image: linear-gradient(to bottom, #3498db, #11828a);
 -webkit-border-radius: 1.0em;
 -moz-border-radius: 1.0em;
 width: 12.0em;
 border-radius: 1.0em;
 font-family: Georgia;
 color: #c4db14;
 font-size: 1.0em;
 padding: 0.7em 1.0em 0.7em 1,0em;
 border: solid #96d60b 0.2em;
 text-decoration: none;
}
.button:hover {
 background: #fc3c63;
 background-image: -webkit-linear-gradient(top, #fc3c63, #91092b);
 background-image: -moz-linear-gradient(top, #fc3c63, #91092b);
 background-image: -ms-linear-gradient(top, #fc3c63, #91092b);
 background-image: -o-linear-gradient(top, #fc3c63, #91092b);
 background-image: linear-gradient(to bottom, #fc3c63, #91092b);
 text-decoration: none;
}
.button:active {
 background-color: #3e8e41;
 box-shadow: 0 0.1em #666;
 transform: translateY(0.2em);
}

.article {
 grid-area: article;
   grid-template-columns: 1 -1;
 grid-template-rows: 4;
 position: relative;
 background: coral;
 margin: 0 0 0 2.0em;;
 padding:1.0em 1.0em 1.0em 2.0em;
}

.footer {
 grid-area: footer;
 background-color: maroon;
 text-align: center;
 padding: 0 0 0 0;
 height: 2.0em;
}

h1 {
 font-size: 1.0em;
 color: blue;
 margin: 0;
}
h2 {
 font-size: 0.75em;
 color: white;
 margin: 1.0em;
}
h3 {
 font-size: 1.2em;
 text-align: center;
 color: white;
 margin: 0;
}
t1 { font: 400 100px/1.3 'Berkshire Swash', sans-serif;
 color: red;
 text-shadow: 1px 1px 0 #fdfdfd 4px 4px 0 rgba(0,0,0,0.15);
 font-style: italic;
 font-weight: 600;
 background: grey;
}
t2 {
font-family: 'Georgia', sans-serif;
color: black;
text-align: center;
font-size: 0.6em;
margin: 0.2em;
padding: 0.2em;
}

a { color: #dc8100; text-decoration: none;
}
a:hover { color: #333; text-decoration: none;
}

<title>TestSite >>> ProPokerUK ... testIndex.html ... testCSS.css</title>
<link href='http://fonts.googleapis.com/css?family=Berkshire+Swash' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Georgia' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="Styles/reset.css" >
<link rel="stylesheet" type="text/css" href="Styles/testCSS.css" >
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <t1> ProPokerUK  </t1>

Change Picture

Under Construction

If you need to you can    contact us   by email.
      Otherwise we shall be online soon !

  <t2>   copyright   &#169ProPokerUK, 2017  </t2>


text:
Q: mongoose: How to insert a single subdocument - not an array In mongoose you are able to declare a schema for a subdocument as per:
        var childSchema = new mongoose.Schema({ name: String, age: String });
        var parentSchema = new mongoose.Schema({
            children: [childSchema]
        });
        var Parent = mongoose.model('Parent', parentSchema);
        var Child = mongoose.model('Child', childSchema);

        var child = new Child({name:'Joe', age: '21'});
        var parent = new Parent();

        parent.children = [child];

        parent.save(function(err, saved) {
            if(err) console.error(err);
        });

Seems the subdocument type needs to be an array. I need to be able to save the subdocument as a single instance, not an array ie:
        var childSchema = new mongoose.Schema({ name: String, age: String });
        var parentSchema = new mongoose.Schema({
            children: childSchema // not an array
        });
        var Parent = mongoose.model('Parent', parentSchema);
        var Child = mongoose.model('Child', childSchema);

        var child = new Child({name:'Joe', age: '21'});
        var parent = new Parent();

        parent.children = child; // not an array

        parent.save(function(err, saved) {
            if(err) console.error(err);
        });

So not an array or a ref, just a single instance subdocument. Is this possible? If not should I use:
var childInstance = child.toObject();

A: Sometimes it is hard to see obvious. You do not need another schema to achieve what you want. You can simply define your sub document within your parent schema like this:
    var parentSchema = new mongoose.Schema({
        child: { 'name' : String, 'age' : Number }  // not an array, just a sub document
    });
    var Parent = mongoose.model('Parent', parentSchema);

    var parent = new Parent();
    parent.child.name = "Joe";
    parent.child.age  = 13;

    parent.save(function(err, saved) {
        if(err) console.error(err);
    });

A: OOPS! Edit:
I totally misread your question.. So you want to store a single subdocument? Then why you had the property named as children..
You can use:
var ParentSchema    =   new schema({
    name : String,
    child: Object
});

// etc.

john.child = new Child({name: 'kiki'});
// which is actually the same as: john.child = {name:'kiki'};
john.save();

This way, mongoose converts the document into a simple object and stores it. But i don't see the use of doing it this way? It doesn't have the benefit of a Schema and is used a default object. Not putting it in an array also blocks you from adding more nested items.
Old:
Instead of injecting the child schema's directly to the parent schema, you need to link them first (and you want to store them separately right?).
So we get two collections: parents and children (=Parent && Child). All documents of collection children are linked to a specific parents collection. And one parent document has zero, one or multiple children documents linked.
In this way you maintain the ability to modify the schema (like attaching methods or statics) and keep the documents neatly separated AND you can have the 'child' effect you wanted:
//  get mongoose.
var mongoose = require('mongoose');

//  connect to your local pc on database myDB.
mongoose.connect('mongodb://localhost:27017/myDB');

//  parent schema.
var parentSchema = new mongoose.Schema({
  name     : String,
  //  the ObjectId's of the children links the two schema's.
  children   : [{type:mongoose.Schema.Types.ObjectId, ref:'Child'}]
});

//  child schema.
var childSchema = new mongoose.Schema({
  name   : String,
  //  the parent's ObjectId links to the owner.
  parent : {type:mongoose.Schema.Types.ObjectId, ref:'Parent'}
});

//  model the schema's.
var Child   = mongoose.model('Child', childSchema),
    Parent  = mongoose.model('Parent', parentSchema);

//  create a 'parent'.
//  we are not assigning the children yet.
var john     = new Parent({name:'John'});

//  create two children and save them. Link them to john.
var child1   = new Child({name:'Mimi', parent:john._id}),
    child2   = new Child({name:'Kiki', parent:john._id});

//  push child to children property of john.
john.children.push(child1);
john.children.push(child2);

//  save everything.
john.save();
child1.save();
child2.save();

This will return the following:
/**
Children:
[ { name: 'Mimi',
    parent: 537258f63eb92b3201b65e56,
    _id: 537258f63eb92b3201b65e57,
    __v: 0 },
  { name: 'Kiki',
    parent: 537258f63eb92b3201b65e56,
    _id: 537258f63eb92b3201b65e58,
    __v: 0 } ]

Parent:
[ { name: 'John',
    _id: 537258f63eb92b3201b65e56,
    __v: 0,
    children: [ 537258f63eb92b3201b65e57, 537258f63eb92b3201b65e58 ] } ]
*/

You can also make a static function to collection parents: addChild(child, callback), so the code looks more clean (javaísh style).
pseudo-code:
// add custom static method.
parentSchema.statics.addChild = function(child, callback) {
   // implementation.
}

// the way you call this method:
parentModel.addChild(new Child.etc..);

Hope this helps and good luck (:

A: if the relationship of 2 collections is 1 to 1.
you can use 'ref'
var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

source: http://mongoosejs.com/docs/populate.html


text:
Q: Is "I will never know what makes the rain to fall?" correct?
I'll never know what makes the rain to fall.

I have read a post about make something to+verb /make something+verb?
The answers shows the above sentence is correct, but when I paste it to a grammar checker website, it prompts to delete the infinite "to". So it becomes the following:

I'll never know what makes the rain fall.

A: The usual construction with "make" has the bare infinitive "makes the rain fall".
The construction with a "to" infinitive is old fashioned and now seems a little poetic.  It is used, for example, in the long poem "the rime of the ancient mariner"

For all averred, I had killed the bird
That made the breeze to blow.

In modern English, you would not use "to".

I'll never know what makes the rain fall.

A: As James K says, you would not normally use "makes ... to ...".
However, without changing the meaning you could say "I'll never know what causes the rain to fall." Following "causes", the "to" is necessary.

A: Pretty sure I've seen constructions like "maketh the mountains to tremble" in the Bible.  The proper KJV one, I mean.


text:
Q: Want to view the data with less null values I have joined a new project which is quite complex. We are using SQL Server 2012 and has many databases(15+). Each table in each database has many columns(more than 25 - 50).
There are thousands of records in each table. I want to view the data in the best possible manner. However, there are nulls for some columns. It has become quite difficult for me to get an idea on the data exists in each table.
Here is my question for sample data.
Id |Column1 |Column2   | Column3 |Column4 |............|ColumnNth
1  |  sam   |*NULL*    |   2     | *NULL* |............|mike
2  |  jack  |2014-02-03| *NULL*  |   6    |............|*NULL*
3  |  Rav   | *NULL*   | *NULL*  |  *NULL*|............|Jim
4  | *NULL* |2013-09-08|   7     |  922   |............|Rocky
5  |  Tom   |2014-10-08|   11    |  212   |............|Mary

...
...
so on...
For example, below is the count of NULLs of all the columns for each rows. [It is not a table in the database.
"Count of NULLs" is not a column of the initial table. I have shown this just for easy explanation]
ID| Count of NULLs
1 | 5
2 |2
3 |10
4 |1
5 |0
6 | 1
7 | 2
8 | 3

...
...
and so on..
Now I want to view the data with less number of NULLs in the top. The order of data should be in the below order. I have shown only the order of IDs so that not to type all the data(columns) again.
ID
5
4
6
2
7
8
1

...
...
3
...
so on...
Explanation of output:
1. The total number of nulls for all the columns for row(ID = 5) is ZERO. This should be first.
2. The total number of nulls for all the columns for row(ID = 4) and row(ID = 6) is ONE. Rows with ID = 4 and ID = 6 should be followed by ID = 5.
...  so on...
In the output, I don't want NULL to be replaced by other value like 0 or 1 or blank value etc. So NULL should be displayed as it is in the output if it exists in the initial table.
I want to view all the columns
Please give me a stored procedure or query or set of queries which is generic. As the number of columns are more than 25-40, the SP or query should work without specifying the column names. If it is Stored procedure, then the Table name would be the input for it.
I assume that it is quite complex to write the SP for this requirement. But what I have asked is a real time situation where a new developer faces when he/she joins a support/maintanence project with complex and huge databases that was already built and contains huge data. Thanks

A: Below is an example you can extend as needed for you actual table.
SELECT
      Id
    , (SELECT COUNT(*)
       FROM (VALUES(Column1), (Column2), (Column3), (Column4)) AS AllColumns(ColumnValue)
       WHERE AllColumns.ColumnValue IS NULL) AS NullCount
FROM dbo.SampleTable
ORDER BY NullCount;

If the source table schema may vary, you'll need to use dynamic SQL:
DECLARE @ColumnList nvarchar(MAX) =
    (SELECT
    STUFF((SELECT ',(' + name + ')'
    FROM sys.columns
    WHERE
        object_id = OBJECT_ID(N'dbo.SampleTable')
        AND name <> 'Id'
    FOR XML PATH('')),1 ,1, '')
    );

DECLARE @SQL nvarchar(MAX) = N'
    SELECT
          Id
        , (SELECT COUNT(*)
           FROM (VALUES' + @ColumnList + ') AS AllColumns(ColumnValue)
           WHERE AllColumns.ColumnValue IS NULL) AS NullCount
    FROM dbo.SampleTable
    ORDER BY NullCount;';

EXEC sp_executesql @SQL;

EDIT (added explanation and SQL 2005 method):
The column list is generated by querying the sys.columns catalog view for all columns in the specified table, except for Id (you can omit other columns as needed using this same technique).  Each included column is enclosed in parenthesis and delimited by a comma to build the string needed for the VALUES clause.  The FOR XML clause returns this list a single string and the extraneous leading comma is removed with the STUFF function so that the @ColumnList variable contains the string needed for the VALUES clause.  The final SQL statement is built by concatenating the rest of the SELECT statement.
Table-valued row constructors (http://msdn.microsoft.com/en-us/library/dd776382.aspx) allow one to specify one or more rows via a VALUES clause.  This is used in the final query to pivot the column list of each source row into rows in order to use the COUNT aggregate function.
The techniques used here (row constructors and initializing variables on the DECLARE statement) were introduced in SQL Server 2008 so this will not work in earlier SQL Server versions.  The version below uses a derived table instead of table-valued row constructor, which will work with SQL 2005.
DECLARE @ColumnList nvarchar(MAX) =
    (SELECT
    STUFF((SELECT ' UNION ALL SELECT ' + name
    FROM sys.columns
    WHERE
        object_id = OBJECT_ID(N'dbo.SampleTable')
        AND name <> 'Id'
    FOR XML PATH('')),1 ,11, '')
    );

DECLARE @SQL nvarchar(MAX) = N'
    SELECT
          Id
        , (SELECT COUNT(*)
           FROM (' + @ColumnList + ') AS AllColumns(ColumnValue)
           WHERE AllColumns.ColumnValue IS NULL) AS NullCount
    FROM dbo.SampleTable
    ORDER BY NullCount;';

EXEC sp_executesql @SQL;

A: There is no pure SQL query that will count the NULL columns in your table, without stating the name of the columns.
If you can use procedures, you can get the column names and dynamically build a query by taking column names from INFORMATION_SCHEMA.COLUMNS and concatenating them like the below query (or other alternatives stated here):
SELECT A.*,
  ( (CASE WHEN Column1 IS NULL THEN 1 ELSE 0 END)
  + (CASE WHEN Column2 IS NULL THEN 1 ELSE 0 END)
  + (CASE WHEN Column3 IS NULL THEN 1 ELSE 0 END)
  .
  .
  .
  + (CASE WHEN ColumnN IS NULL THEN 1 ELSE 0 END)) AS NULL_CNT
FROM MYTABLE A
ORDER BY NULL_CNT DESC


text:
Q: Facebook Login Window hangs after logging in When the user logs in successfully the window hangs up and it's title changes to: XD Proxy
There is a similar question that was supposedly solved but instead of posting the solution the user said: "I solved it. It was to do with my settings in Facebook's page." So I ended up knowing I have to change the settings page but no idea what.
My url in the settings page is: http://chusmix.com/ and my domain is chusmix.com. I'm currently trying the login button at http://www.chusmix.com/game
I don't need it to refresh since the login button refreshes to logged in by itself, I only need the window to close.
This is my code:

  <fb:login-button length="long" onlogin="signface_login();" autologoutlink="true"></fb:login-button>

Any info on how to fix this will be tremendously welcomed. I have been trying to fix it for the last 2 hours and I haven't been able to start anything else.
Thanks

A: Btw one of the solution i can think of is to set next url in fb login page to some page where you call window.close()
let me know if this is working fine....


text:
Q: Change text color of SVG when clicked on it I am using d3.js to build a stacked bar graph. I am referring to this graph http://bl.ocks.org/mbostock/3886208
I have functionality that if you click on any legend that age group population will hide on all states bar. What i want is when I click to hide any age group population from the graph I want to change the text color of that legend in "red" color. Here is my code
              legend.append("text")
              .attr("id", "legd-text")
              .attr("x", width-10)
              .attr("y", 40)
              .attr("dy", ".15em")
              .style("text-anchor", "end")
              .on("click", function(){
                   var changeTextColor = document.getElementById('legd-text');
                   changeTextColor.setAttribute("fill", "red");
              })
              .text(function(d) {
                  return d; });

But this is not working. Please help me.
Thanks a lot.

A: have you tried using jQuery to do this?
$("#legd-text").attr("fill", "red");

or try
$("#legd-text").css("background-color", "red");

A: Are you setting all of your legend labels to have the same id?  They should all have different id values so you can query for them individually.
For your particular case, though, you can maybe take advantage of the fact that the this reference inside a d3 event listener function refers to the current DOM node (as with most d3 callbacks):
    .on("click", function() {
         d3.select(this).attr("fill", "red");
    })


text:
Q: JavaScript count 1, 2, 3 and redirect I want to count on my site from 3 to 1 (3, 2, 1, <redirect>), like on sh.st or adf.ly. I'm really new to JavaScript, can anyone help me?

A: Here's a quick and dirty way to creat a countdown
//Calls countdown function
var count = 3;
countdown(count);

//counts and redirect
function countdown(timer) {
    //Keeps the interval ID for later clear
    var intervalID;
    intervalID = setInterval(function () {

        display(timer);
        timer = timer - 1;

        if (timer < 0) {
            //Clears the timeout
            clearTimeout(intervalID);
            // You can redirect the user after it
            // window.location.assign("YourURL");
        }
    }, 1000);

}

//Modifies the countdown display
function display(timer) {
    //Execute your diplay modification logic
}

You can check it here


text:
Q: How to use template matching to identify different size of objects in opencv/javacv? I went through couple of template matching tutorials and I had noticed that most of the tutorials try to match the template which crop from original image. But I would like to know whether is it possible to identify similar objects with different widths and heights ?
In my project I have following type of image which I generated.

and I need to identify following components from it.

How can I archive this using opencv or javacv?? Is it possible to use template matching for this? Because this objects can be in different sizes so is it possible to use it? Please can some one give simple code example to identify this objects ?

A: I'm not sure that it helps you in real situation, but simple threshold did the trick on your input image:

Code:
Mat src = imread("input.jpg"), tmp;
cvtColor(src, tmp, CV_BGR2GRAY);
threshold(tmp, tmp, 200, 255, THRESH_BINARY);

A: Template matching/pattern recognition would work for this. However, as far as i know, openCV's template matching does not use scaling or rotation. It just finds the most likely position by "sliding" the template over the image and looking for the smallest difference.
Personally i'd use HALCON for this, but that's a pretty expensive program/package.


text:
Q: Excel SUMIF based on array using text string Is there a way to substitute the cell address containing a text string as the array criteria in the following formula?
=SUM(SUMIF(A5:A10,{1,22,3},E5:E10))
So instead of {1,22,3}, "1, 22, 3" is entered in cell A2 the formula becomes
=SUM(SUMIF(A5:A10,A2,E5:E10))
I have tried but get 0 as a result (refer C16)
    A   B   C   D   E   F   G   H
1   Tree
2   {1,22,3}                1
3                   22
4   Tree    Profit          3
5   1   105
6   2   96
7   1   105
8   1   75
9   2   76.8
10  1   45
11
12          330 =SUM(SUMIF(A5:A10,{1,22,3},B5:B10))
13
14          330 =SUMPRODUCT(SUMIF(A5:A10,E2:E3,B5:B10))
15
16          0   =SUM(SUMIF(A5:A10,A2,B5:B10))
17              NB: Custom Format "{"@"}" on Cell A2 I enter 1,22,3 so it displays {1,22,3}

A: Ok so after some further searching (see Excel string to criteria) and trial and error I have come up with the following solution.
Using Name Manager I created UDF called GetList which Refers to:
=EVALUATE(Sheet1!$A$3) NB: Cell A3 has this formula in it =TEXT(A2,"{@}")
I then used the following formula:
=SUMPRODUCT(SUMIF($A$5:$A$12,GetList,$B$5:$B$12))
which gives the desired result of 321 as per the other two formulas (see D12 below).
If anyone can suggest a better solution then feel free to do so.
Thanks to Dennis to my original post regarding table
        A        B          C        D          E
    1   Tree
    2   1,22,3                       1
    3  {1,22,3} =TEXT(A2,"{@}")      22
    4   Tree    Profit               3
    5   11      105
    6   22      96
    7   1       105
    8   3       75
    9   2       76.8
    10  1       45
    11
    12                              321 =SUMPRODUCT(SUMIF($A$5:$A$12,GetList,$B$5:$B$12))
    13
    14                              321 =SUM(SUMIF(A5:A10,{1,22,3},B5:B10))
    15
    16                              321 =SUMPRODUCT(SUMIF(A5:A10,E2:E3,B5:B10))
    17
    18                              0   =SUM(SUMIF(A5:A10,A2,B5:B10))
    19                      NB: Custom Format "{"@"}" on Cell A2 I enter 1,22,3 so it displays {1,22,3}


text:
Q: Play framework with Scala and Hadoop doesn't return result to browser I'm trying to write an API to select data from our Hadoop cluster. I'm using play framework but I'm having some problems. My problem is that I don't get back the result to the browser.
My function:
def trends(year:Int  , month:Int  , day:Int ,hour:Int ) =
Action {
var df:org.apache.spark.sql.Dataset[String] = null
val data= spark.sql("select * from trends.books")
  .filter(col("year")===year)
  .filter(col("month")===month)
  .filter(col("day")===day)
  .filter(col("query").contains("co.il"))
if(hour != -1)
   df = data.filter(col("hour")===hour).orderBy(desc("ratio")).toJSON
else
   df = data.orderBy(desc("ratio")).toJSON

var final_json=""
df.collect().foreach(final_json+=_.toString()+"\n")
println(final_json)
  println("After print json before ok")
 Ok(final_json)
}

the routes file :
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# An example controller showing a sample home page
GET     /                           controllers.HomeController.index
# An example controller showing how to use dependency injection
GET     /trends                          controllers.CountController.trends(year:Int,month:Int,day:Int,hour:Int?=-1)
# An example controller showing how to write asynchronous code
GET     /message                    controllers.AsyncController.message

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.versioned(file)

Now,I'm trying to return the user all the jsons of all the rows in a specific table filtered by the parameters that the user pass to the function. As you can see I put some prints in the code for debuging. When I run play with sbt.run I get the output but it seems very weird.
The output looks like that :
("query":"aa","author":"bb","year":2018,"month":4,"day":10,"hour":20)
("query":"bb","author":"bb","year":2018,"month":4,"day":10,"hour":20)
("query":"cc","author":"bb","year":2018,"month":4,"day":10,"hour":20)
After print json before ok

Now because Chrome doesn't get any result back it refreshes the pages and then again:
("query":"aa","author":"bb","year":2018,"month":4,"day":10,"hour":20)
("query":"bb","author":"bb","year":2018,"month":4,"day":10,"hour":20)
("query":"cc","author":"bb","year":2018,"month":4,"day":10,"hour":20)
After print json before ok

and again..
("query":"aa","author":"bb","year":2018,"month":4,"day":10,"hour":20)
("query":"bb","author":"bb","year":2018,"month":4,"day":10,"hour":20)
("query":"cc","author":"bb","year":2018,"month":4,"day":10,"hour":20)
After print json before ok

and so on..

Why don't I get anything back ?

A: I once ran through the similar issue. Making it asynchronous fixed the issue for me.

A: It seems that the browser keep refreshing itself and therefore I got this recursive loop. I used the curl in cmd and it worked.


text:
Q: Memory/Efficiency with Linq and large data sets So you know the background I'm coming from, I've been a professional programmer for over twelve years. My best language by far is C# but I've done C, C++, and most recently objectiveC. I've done a lot of work accessing data in databases but I haven't done as much UI work as most people (Except in IOS).
Recently I've begun using the Entity framework in C# for a job and I must say I wish I'd discovered it sooner. I wouldn't say it's the best thing since sliced bread but it's pretty damned close. After using it for a while it got me thinking about best practices and usage as compared to the old school method of using IDBConnections and IDBCommands for everything.
I was coding for a situation where I was going to be listing the contents of a table of users from a database in a bound data grid with the intention of giving the user the ability to do standard CRUD stuff. I started off by making an User class and a IUserManager interface with a corresponding implementation. Each user is assigned to a department and naturally there'd need to be a way to perform CRUD on departments too so I added a Department class, an IDepartmentManager interface and an implementation for that too. I set it up so that the grid bound on the results of the .GetAll() method on the IUserManager interface. Then I started filling in the guts.
I don't have the code in front of me any more but I basically used IDBConnection to tap into the datastore with an IDBCommand using a SQL query. Then I called command.ExecuteReader() and iterated the .Read() method on the IDataReader object. Using the ordinal for each column I pulled out the data, validated it and slipped it into a User class and added the class to a Dictionary that the method would then return. All the DB classes are of course IDisposable so wrapping them in a using takes care of cleaning up the mess.
Pretty standard stuff, I've done it a bazillion times.
That's when I realized that the departmentId I was pulling from the DB wasn't what I wanted to display in my grid. Telling someone 'this guy is in department 7' isn't as useful as saying 'this guy is in accounting'. So I first toyed with modding my query to get both the departmentId and name, and storing the name on the user object for display later. Then I decided to give the user a Department class instance that it would hang onto during it's lifetime that would be populated. That's when I converted the guts to linq.
   public Dictionary<int, User> GetAll()
    {
        var result = new Dictionary<int, User>();

        using (var datastore = new myEntities())
        {
            result = (from user in datastore.userInfoes
                       join department in datastore.userDepartmentInfoes on user.departmentID equals department.departmentID
                    select new User()
                    {
                        UserIndex = user.id,
                        FirstName = user.firstName,
                        LastName =  user.lastName,
                        Department = new Department()
                        {
                            DepartmentId = user.departmentID.Value,
                            DepartmentName = department.departmentName,
                                                                                },
                        Username =  user.userName,
                    }
                ).ToDictionary(x => x.UserIndex, x => x);
        }

        return result;
    }

That's where I started thinking (read: over-analysing probably)
The implementation I had would work just fine. It would even work pretty well for a small dataset. It'll even work fine for a largish dataset (say 10,000). Even if you counted every person in the company I currently work for five times over you'd have less than a thousand people.
But what if for a second I worked for a really big honking company that had 10 million employees? That would result in the departmentName strings being duplicated potentially millions of times.
That also got me thinking that unlike IOS's MVC implementation this particular situation wasn't going to query just enough users to fill the screen and then handle paging and stuff. As soon as the calling code refresh the data binding it was going to pull all 10 million users all at once and pass back the collection. That's going to be slow.
So that leaves me with the idea in my head that this method is both slow and inefficient with larger data sets. Not only that but the fact that there might be 2 million instances of 'Accounting' held with this data set it is going to be a major memory hog. We're also kind of defeating the purpose of a relational database here because of the Department class inside the User. In the DB you just have a departmentId int foreign key referencing an entry in another table. The link only occurs when you cross reference to the other table and even then there's really only one 'Accounting' string at any one time. In the above code you're going to have a whole lot of 'Accounting' strings floating around waiting to be cleaned up.
An MVC scenario would basically 'know' that it takes X number of entries to fill the grid's viewable area. It would only query X at a time starting from index Y and as the user navigated it would query and display additional records as needed. That's a heck of a lot better than querying all 10 million and letting them hang out somewhere whether they're displayed or not.
Like I said, I may very well be over-analysing this. I might also be incorrect in some of my assumptions with the way linq works. But in the interest of learning I figured I had to ask: What is the best way to do something like this? Is this sort of thing ok for small datasets? Would the whole thing be better off as an MCV implementation rather than pulling in the entire dataset to be displayed in the grid?

A: If you need the whole set of data in memory - you will have to load it anyway. I am sure you will not list 10kk users in a grid, right? The techniques that comes up is paging. Check this article from msdn with examples.
As for departments objects, does your UserInfo has a foreign key to the department? If so you should just have userInfo.Department available to you and no joins are needed.
If you bind the department data to the grid columns, why having the property of Department type? I assume your User class is something you bind to UI. Flatten it out into:
class User
{
 Username
 UserIndex
 FirstName
 LastName
 DepartmentId
 DepartmentName
}

What is the purpose of GetAll()? You return a dictionary and it feels like you need to enable lookups by id. Or do you use the result to enumerate the users?
For lookups, consider talking to the database to get you a single user data when needed. Implement caching if makes sense next.
For enumeration, do not return dictionary - that is all-in-memory object, return IEnumerable with yielded (paged?) results  or even better IQueryable so that calling GetAll() doesn't execute the sql call right away, and the calling code can scope the call down by adding necessary filters


text:
Q: Generate points efficiently between unit circle and unit square I'd like generate samples from the blue region defined here:

The naive solution is to use rejection sampling in the unit square, but this provides only a $1-\pi/4$ (~21.4%) efficiency.
Is there some way I can sample more efficiently?

A: Well, more efficiently can be done, but I sure hope you are not looking for faster.
The idea would be to sample an $x$ value first, with a density proportional to the length of the vertical blue slice above each $x$ value:
$$ f(x) = 1-\sqrt{1-x^2}. $$
Wolfram helps you to integrate that:
$$ \int_0^x f(y)dy = -\frac{1}{2}x\sqrt{1-x^2}+x-\frac{1}{2}\arcsin x.$$
So the cumulative distribution function $F$ would be this expression, scaled to integrate to 1 (i.e., divided by $ \int_0^1 f(y)dy$).
Now, to generate your $x$ value, pick a random number $t$, uniformly distributed between $0$ and $1$. Then find $x$ such that $F(x)=t$. That is, we need to invert the CDF (inverse transform sampling). This can be done, but it's not easy. Nor fast.
Finally, given $x$, pick a random $y$ that is uniformly distributed between $\sqrt{1-x^2}$ and $1$.
Below is R code. Note that I am pre-evaluating the CDF at a grid of $x$ values, and even then this takes quite a few minutes.
You can probably speed the CDF inversion up quite a bit if you invest some thinking. Then again, thinking hurts. I personally would go for rejection sampling, which is faster and far less error-prone, unless I had very good reasons not to.
epsilon <- 1e-6
xx <- seq(0,1,by=epsilon)
x.cdf <- function(x) x-(x*sqrt(1-x^2)+asin(x))/2
xx.cdf <- x.cdf(xx)/x.cdf(1)

nn <- 1e4
rr <- matrix(nrow=nn,ncol=2)
set.seed(1)
pb <- winProgressBar(max=nn)
for ( ii in 1:nn ) {
    setWinProgressBar(pb,ii,paste(ii,"of",nn))
    x <- max(xx[xx.cdf<runif(1)])
    y <- runif(1,sqrt(1-x^2),1)
    rr[ii,] <- c(x,y)
}
close(pb)

plot(rr,pch=19,cex=.3,xlab="",ylab="")

A: I propose the following solution, that should be simpler, more efficient and/or computationally cheaper than other soutions by @cardinal, @whuber and @stephan-kolassa so far.
It involves the following simple steps:
1) Draw two standard uniform samples:
$$
    u_1 \sim Unif(0,1)\\
    u_2 \sim Unif(0,1).
$$
2a) Apply the following shear transformation to the point $\min\{u_1,u_2\}, \max\{u_1,u_2\}$  (points in the lower right triangle are reflected to the upper left triangle and they will be "un-reflected" in 2b):
$$
   \begin{bmatrix}
   x\\y
   \end{bmatrix}
   =
   \begin{bmatrix}
   1\\1
   \end{bmatrix}
   +
   \begin{bmatrix}
   \frac{\sqrt{2}}{2} & -1\\
   \frac{\sqrt{2}}{2} - 1 & 0\\
   \end{bmatrix}
   \,
   \begin{bmatrix}
   \min\{u_1,u_2\}\\
   \max\{u_1,u_2\}\\
   \end{bmatrix}.
$$
2b) Swap $x$ and $y$ if $u_1 > u_2$.
3) Reject the sample if inside the unit circle (acceptance should be around 72%), i.e.:
$$
   x^2 + y^2 < 1.
$$
The intuition behind this algorithm is shown in the figure.

Steps 2a and 2b can be merged into a single step:
2) Apply shear transformation and swap
$$
  x = 1 + \frac{\sqrt{2}}{2}  \min(u_1, u_2) - u_2\\
  y = 1 + \frac{\sqrt{2}}{2}  \min(u_1, u_2) - u_1
$$
The following code implements the algorithm above (and tests it using @whuber's code).
n.sim <- 1e6
x.time <- system.time({
    # Draw two standard uniform samples
    u_1 <- runif(n.sim)
    u_2 <- runif(n.sim)
    # Apply shear transformation and swap
    tmp <- 1 + sqrt(2)/2 * pmin(u_1, u_2)
    x <- tmp - u_2
    y <- tmp - u_1
    # Reject if inside circle
    accept <- x^2 + y^2 > 1
    x <- x[accept]
    y <- y[accept]
    n <- length(x)
})
message(signif(x.time[3] * 1e6/n, 2), " seconds per million points.")
#
# Plot the result to confirm.
#
plot(c(0,1), c(0,1), type="n", bty="n", asp=1, xlab="x", ylab="y")
rect(-1, -1, 1, 1, col="White", border="#00000040")
m <- sample.int(n, min(n, 1e4))
points(x[m],y[m], pch=19, cex=1/2, col="#0000e010")

Some quick tests yield the following results.
Algorithm https://stats.stackexchange.com/a/258349 . Best of 3: 0.33 seconds per million points.
This algorithm. Best of 3: 0.18 seconds per million points.

A: Will two million points per second do?
The distribution is symmetric: we only need work out the distribution for one-eighth of the full circle and then copy it around the other octants.  In polar coordinates $(r,\theta)$, the cumulative distribution of the angle $\Theta$ for the random location $(X,Y)$ at the value $\theta$ is given by the area between the triangle $(0,0), (1,0), (1,\tan\theta)$ and the arc of the circle extending from $(1,0)$ to $(\cos\theta,\sin\theta)$.  It is thereby proportional to
$$F_\Theta(\theta) = \Pr(\Theta \le \theta) \propto \frac{1}{2}\tan(\theta) - \frac{\theta}{2},$$
whence its density is
$$f_\Theta(\theta) = \frac{d}{d\theta} F_\Theta(\theta) \propto \tan^2(\theta).$$
We may sample from this density using, say, a rejection method (which has efficiency $8/\pi-2 \approx 54.6479\%$).
The conditional density of the radial coordinate $R$ is proportional to $rdr$ between $r=1$ and $r=\sec\theta$.  That can be sampled with an easy inversion of the CDF.
If we generate independent samples $(r_i,\theta_i)$, conversion back to Cartesian coordinates $(x_i,y_i)$ samples this octant.  Because the samples are independent, randomly swapping the coordinates produces an independent random sample from the first quadrant, as desired.  (The random swaps require generating only a single Binomial variable to determine how many of the realizations to swap.)
Each such realization of $(X,Y)$ requires, on average, one uniform variate (for $R$) plus $1/(8\pi-2)$ times two uniform variates (for $\Theta$) and a small amount of (fast) calculation.  That's $4/(\pi-4) \approx 4.66$ variates per point (which, of course, has two coordinates).  Full details are in the code example below.  This figure plots 10,000 out of more than a half million points generated.

Here is the R code that produced this simulation and timed it.
n.sim <- 1e6
x.time <- system.time({
  # Generate trial angles `theta`
  theta <- sqrt(runif(n.sim)) * pi/4
  # Rejection step.
  theta <- theta[runif(n.sim) * 4 * theta <= pi * tan(theta)^2]
  # Generate radial coordinates `r`.
  n <- length(theta)
  r <- sqrt(1 + runif(n) * tan(theta)^2)
  # Convert to Cartesian coordinates.
  # (The products will generate a full circle)
  x <- r * cos(theta) #* c(1,1,-1,-1)
  y <- r * sin(theta) #* c(1,-1,1,-1)
  # Swap approximately half the coordinates.
  k <- rbinom(1, n, 1/2)
  if (k > 0) {
    z <- y[1:k]
    y[1:k] <- x[1:k]
    x[1:k] <- z
  }
})
message(signif(x.time[3] * 1e6/n, 2), " seconds per million points.")
#
# Plot the result to confirm.
#
plot(c(0,1), c(0,1), type="n", bty="n", asp=1, xlab="x", ylab="y")
rect(-1, -1, 1, 1, col="White", border="#00000040")
m <- sample.int(n, min(n, 1e4))
points(x[m],y[m], pch=19, cex=1/2, col="#0000e010")


text:
Q: Can't send mail through php in html I'm trying to develope a personal website as a projecet to one of my classes.
I don't understand much of html so i actually can't make my php work.
Please Help.
I've already tried copying and changing php codes from other fonts but nothing works...
This is the html code:

   <form action="" method="POST">
      <input type="text" id="name" name="name" placeholder="Name">
      <input type="text" id="email" name="email" placeholder="Email">
      <textarea id="message" name="message" placeholder="Message" style="height:100px"></textarea>
      <input type="submit" value="Send">
   </form>

A: <form action="" method="POST">
      <input type="text" id="name" name="name" placeholder="Name">
      <input type="text" id="email" name="email" placeholder="Email">
      <textarea id="message" name="message" placeholder="Message" style="height:100px"></textarea>
      <input type="submit" name="submit" value="Send">
</form>

<?php
   if(isset($_POST['submit'])){
      $name = $_POST['name'];
      $email = $_POST['email'];
      $message = $_POST['message'];

      $to_email = $email; // mail whom you want to send
      $subject = ''; // your subject for sending email
      $message = $name.' sent you message.

'.$message;
      $headers = 'From: noreply@company.com'; // your mail id

      mail($to_email,$subject,$message,$headers);

      echo "This email is sent using PHP Mail";
   }
?>

Use this above code, this will pass the name, email, message to mail function.
Hope this helps you.


text:
Q: Why are Mealy's number of states less than Moore's number of states in finite state machines? I was doing an assigment for my digital logic design course.  One of the questions was to design a circuit using Moore's state machine and another one doing the same function using Mealy's state machine.
The function of the circuit was to detect the input of 000 by outputting 1.  The weird thing I noticed about the answer is that Mealy's state machine contains only 3 states while Moore's contains 4 states. I know the difference between them that one of them depends on the input and current state while the other depends on only the current state but I still don't understand why Mealy's machine contain less states.

A: Because you don't need a separate state for the third zero.
If you already had two zeroes coming in, the output "1" can be created by the input only, without changing to a new state. The Moore machine can't do that, it has to transition to an additional state for the third zero in row.