Q:

Help with a natural deduction proof

Does anyone have any idea how to prove this?
/[P ⊃ (Q ⊃ R)] ⊃ [(P ⊃ Q) ⊃ (P ⊃ R)]

So far I have
1' P ⊃ (Q ⊃ R)         AcP

 2' P ⊃ Q              AcP

  3' ~P                AIP

Thanks

A:

Standard notation is "$\to$" for "implies" because "$\supset$" denotes "[strict] superset". Also, "$\neg$" is standard for "not".

If $P \to ( Q \to R )$:
  If $P \to Q$:
    If $P$:
      $Q \to R$.
      $Q$.
      $R$.
$\cdots$

I'll leave you to fill in the final steps and the justification for each step.


Q:

New-PSSession across domain boundaries

I am trying to bring up a virtual machine that needs to be able to create new sessions (with New-PSSession). The highly engaging about_Remote_Troubleshooting is my constant companion, of course!
After bringing up a basic machine (Win 8.1 Enterprise):

My company's primary domain is, say, mycompany.com.
We have a development domain dev.mycompany.com so that developers have a sandbox to play with.
I added the new VM (named my-vm) to the development domain dev.mycompany.com.
I have a local account on the new VM, my-vm\msorens which is in the Administrators group on the local machine.

First Hurdle:
Attempting to run just New-PSSession failed with access denied because of cross-domain issues.
Per the troubleshooting page referenced above:

When a user in another domain is a member of the Administrators group
  on the local computer, the user cannot connect to the local computer
  remotely with Administrator privileges.

I am not convinced this is true (due to my inexperience in domain issues) but applying the recipe for that remedy allowed the basic New-PSSession to work:
New-ItemProperty `
-Name LocalAccountTokenFilterPolicy `
-Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System `
-PropertyType DWord `
-Value 1

(And that, while less secure, is fine, as it is just a sandbox VM.)
Second Hurdle:
With the above patch in place I could successfully do any of these:
PS> New-PSSession
PS> New-PSSession -ComputerName localhost
PS> New-PSSession -ComputerName my-vm

However, my actual need is to give the FQDN of the machine:
PS> New-PSSession -ComputerName my-vm.dev.mycompany.com

That fails because of missing credentials. Which brings us to this:
PS> New-PSSession -ComputerName my-vm.dev.mycompany.com -Credential (Get-Credential)

I have tried my local (my-vm) credentials, which resulted in WinRM cannot process the request; no logon servers available.
I have tried my company domain credentials (note that is mycompany.com not the domain the VM is actually on dev.mycompany.com), which resulted in Access is denied.
Is there a way to make this work?

A:

At work we have the same situation. Here a some steps we do at new coworker computers so they are able to connect to these server how are outside our domain.
On client side
winrm quickconfig
winrm set winrm/config/client '@{TrustedHosts="Computer1,Computer2"}'

On server side
Enable-PSRemoting -Force
winrm quickconfig

For HTTPS
winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="_";CertificateThumbprint="_"}

For HTTP
winrm create winrm/config/Listener?Address=*+Transport=HTTP

Test with
Test-WsMan ComputerName
Test-WsMan ComputerName -UseSSL

Create a session with
New-PSSession -ComputerName Computer1 -Credential (Get-Credential)

Of course you need to configure your firewall to let the server listen on the powershell remoting port.
Edit: Set TrustedHosts with PowerShell
Or with PowerShell (as Admin)
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value "Computer1,Computer2"

And check (don't need Admin for that)
Get-Item WSMan:\localhost\Client\TrustedHosts


Q:

List button doesn't see Visualforce page

I have the parent object Contract__c and the child object Risk__c. I have created a visualforce page for Risk__c and now I want to create a list button, which shows up on the related list on Contract__c, that opens this visualforce page. The Visualforce page shows up when I select Detail button, but when I try to create a list button, it doesn't show up.
So, to explain in more detail. The Visualforce page called testpage has Risk__c as the standard controller.
I want to create a List Button, but I don't have the option to select a visualforce page:

When I select Detail Button though, I have the option to select that visualforce page:

I am confused, and I have no idea how I can invoke that visualforce page from the related list on Contract__c otherwise.
I am not sure what I am doing wrong...
Tia.

A:

I ran into the same issue and here's the answer:
A visualforce page can be available for either a page view (that gets passed one ID) or a list view (that gets passed a list of 0 or more records).
Here's what you have, and it works for the page view, and the ID of the individual record is passed as the page's id parameter. This doesn't make sense on the list view, because you'd have a list of many different IDs, so they can't all be the id parameter:
<apex:page standardController="Risk__c">

Here's what you can add to change it to be available on a list, :
<apex:page standardController="Risk__c" recordSetVar="risks">

From Salesforce:

The component also has a recordSetVar attribute. We use this attribute
  to change the standardcontroller so that it accommodates a set of
  records rather than a single record.

In other words, it will pass a list of records, that's why you can select "Display Checkboxes (for Multi-Record Selection)" when you're configuring the button.
So if you want to use the visualforce page exclusively for the page view button/link or exclusively for the list view button, that's your solution.
Another solution is to use a button with URL as the type, and link to your page, but then you won't get the list of IDs, but you could pass the ID (or another value) from your parent object, Contract__c.
Here's an example of building out a page for a list button from Salesforce


Q:

git hook flake8: error: input not specified

Flake8's pre-commit hook for git raises flake8: error: input not specified whenever I do git commit.
The hook file is identical to the official example :
#!/usr/bin/python
import sys
from flake8.run import git_hook

COMPLEXITY = 10
STRICT = False

if __name__ == '__main__':
    sys.exit(git_hook(complexity=COMPLEXITY, strict=STRICT, ignore='E501'))

A:

Yes, this is due to a bug in flake8 2.1.0.  To work around this, create an empty setup.cfg or tox.ini file in your project directory.  I just created a bug ticket for this: https://bitbucket.org/tarek/flake8/issue/133/git_hook-broken-when-setupcfg-and-toxini


Q:

Calculating Scale for a UIView

Suppose the current scale of my UIView is x. Suppose I apply a scale transformation to my UIView of the amount y ie:
view.transform = CGAffineTransformScale(view.transform, y, y);

. How do I determine what the value of the scale of the UIView after the scale transformation occurs (in terms of x and y?).

A:

The scale transform multiplies the current scale with your scale y.
if the scale was 2.0 for retina, it is y* 2.0 afterwards.
So x*y is the answer. but dont forget x.achsis scale and y achsis can be different.
x, and y for scale is confusing, better use s1 and s2, or sx, sy if you have different scale on y and x achsis, in your code.


Q:

Why Anonymous User can't vote more than once from different browsers / machines on Poll?

I created a Poll in my Drupal 8 website which happened without any issue. I have enabled anonymous voting too. But when I open this node in different browsers / machines, the poll results appear and anonymous users are unable to vote.
Please tell me where is the issue.

A:

Seems like that was the issue because of same IP address. But in case of  local network with hundreds of machines, how will that be taken care of, is still a question.
Right resource: Does poll not allow multiple anonymous votes?


Q:

jquery .next() not working properly

Im using the js shortcut plugin shortcut.js to enable keyboard shortcuts for the up and down arrows to select tabs. When a tab is clicked, it is selected. Click a tab and use the up and down arrows to choose a neighboring tab. I'm using .prev() and .next() to control the selection, but something is wrong with .next(). When a tab is selected, the selection just skips to the last tab.
JSBIN: http://jsbin.com/maqiheja/3/edit?html,css,js,output
JS:
shortcut.add("up",function() {
  $('.tab').each(function(){
    var selected = $(this).hasClass('selected');
    var end = $('.tab:first-of-type').hasClass('selected');
    if((selected === true) && (end === false)){
      $(this).removeClass('activeTab selected');
      $(this).prev().addClass('activeTab selected');
    }
  });
});

shortcut.add("down",function() {
  $('.tab').each(function(){
    var selected = $(this).hasClass('selected');
    var end = $('.tab:last-of-type').hasClass('selected');
    if((selected === true) && (end === false)){
      $(this).removeClass('activeTab selected');
      $(this).next().addClass('activeTab selected');
    }
  });
});

A:

You don't need to loop. Just move the selected tab to the next tab once.
shortcut.add("down", function() {
    var selected = $('.tab.selected');
    var end = $('.tab:last-of-type').hasClass('selected');
    if (selected.length && !end) {
        selected.removeClass('activeTab selected');
        selected.next().addClass('activeTab selected');
    }
});

shortcut.add("up", function() {
    var selected = $('.tab.selected');
    var end = $('.tab:first-of-type').hasClass('selected');
    if (selected.length && !end) {
        selected.removeClass('activeTab selected');
        selected.prev().addClass('activeTab selected');
    }
});


Q:

definition of $T_0$-space in Dshalalow’s book

From the book “Real analysis: An introduction to the theory of real functions and integration” by Jewgeni H. Dshalalow (CRC Press, 2001, ISBN 1584880732, Chapter “10. Separation”, p. 182):

10.1 Definitions. Let $(X, \tau)$ be a topological space.
(i) $(X, \tau)$ is called a $T_0$ space if for each pair of points
  $x\not=y\in X$, there is a neighborhood of $x$, $U_x$ such that $y\in U^c_x$

(For a subset $A$, $A^c$ denotes the complement of $A$ (Ibid., p. 6).) Am I understanding it right that this definition is equivalent to axiom  $T_1$ and therefore is incorrect?

A:

You are correct. I recall the following definitions and explanations from [Eng].

References
[Eng]  Ryszard Engelking, General Topology, 2nd ed., Heldermann, Berlin, 1989.


Q:

Hide icon of working process in TaskBar

how to hide icon of working process in Taskbar in vb.net?
Dim startInfo As New ProcessStartInfo("Some Process")
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden 'he hide only window of process
'startInfo.ShowInTaskbar = False 'don't work with System.Diagnostics and ProcessStartInfo
Pr = System.Diagnostics.Process.Start(startInfo)

I need to hide a window and a icon on taskbar.
Please help.

A:

I found this post which was trying to solve the same problem:
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Module Module1

    Public GWL_EXSTYLE As Integer = -20
    Public WS_EX_APPWINDOW As Integer = &H40000

    <DllImport("user32.dll")> _
    Public Function GetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As Integer) As Integer
    End Function

    <DllImport("user32.dll")> _
    Public Function SetWindowLong(ByVal hWnd As IntPtr, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer
    End Function

    <DllImport("user32.dll", SetLastError:=True)> _
    Public Function SetParent(ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As IntPtr
    End Function

    Sub Main()

        ' Start your process
        Dim startInfo As New ProcessStartInfo("YourProcessName")
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
        Dim p as Process = System.Diagnostics.Process.Start(startInfo)

        ' Hide the process from the task bar
        Dim style As Integer = (GetWindowLong(p.MainWindowHandle, GWL_EXSTYLE) And Not WS_EX_APPWINDOW)
        SetWindowLong(p.MainWindowHandle, GWL_EXSTYLE, style)
        SetParent(p.MainWindowHandle, New Form().Handle)

    End Sub

End Module


Q:

AC current measurement - input protection circuit

Hi  there
I am developing a AC current measurement device based on Current  transformer.
I was taking a look to many questions related with this subject  but in this case I would need some help
regarding the microcontroller chip input circuitry. As you can see from the attached schematics Fig.1 and fig. 2 were taken from other questions, so these ones inspired me partially to implement the input protection for my circuit. As reference I am using a SOC chip MCU,  precisely PSoC 5LP from Cypress.
As  CT, I am using 2000:1-  30 A/15 ma  -  R burden :10 ohm.
The following link is the data sheet for the CT.
  (https://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Current/ECS1030-L72-SPEC.pdf )
In fig 3 ( dash lines are a issue I have with the editor), I'm showing  a resistor divider 560k / 560k and  a couple of capacitors for decoupling the central point of the voltage divider.
My question is regarding the value that should have the resistor R_4 that limit the current after the burden resistor_3.
Looking at the PSoC 5LP data sheet regarding the absolute maximum ratings for a input pin, in this case is the OP-AmP_1 input,  the min current should be -30 ma  and max  should be  41 ma.
The maximum input voltage for the pin should be  3.3 V + 0.5 V.  I'm using one of two option 3.3v or 5V as VDD.
I would like some hint about how calculate that  resistor value.
My other question is if 1N4148 can protect  the input , I am not sure . Should I use Shottky diodes?
Thank you very much for some  help.

A:

For those currents the burden voltage is in the +0.5 to -0.5V range resulting in an input voltage between 1V - 2V. If the current exceeds those limits you want a clamping device with a forward voltage of less than 0.5V, so the 1N4148 wont work. Shottky diodes have a lower forward voltage. Use R4 to limit the current flowing trough the clamping device. Look at the V-I plot of a diode to determine at which current you get the desired forward voltage.


Q:

Get max and min dates from an array

I have sample data as:
data = [
  [1, 622, 782, 783, "2015-04-21"],
  [2, 622, 782, 783, "2015-04-21"],
  [3, 622, 782, 783, "2015-04-22"],
  [4, 622, 782, 783, "2015-04-23"],
  [5, 622, 782, 783, "2015-04-24"],
  [6, 622, 782, 783, "2015-04-28"],
  [7, 622, 782, 783, "2015-04-28"],
  [8, 622, 782, 783, "2015-04-29"],
  [9, 622, 782, 783, "2015-05-04"],
  [10, 622, 782, 783, "2015-05-05"]
]

How can I get the max date value and min date value from the above data? The data may be not in sorted order.

A:

1) Use map to extract the dates:
var dates = data.map(function(x) { return new Date(x[4]); })

2) Use Math.max / Math.min to get the highest / lowest dates:
var latest = new Date(Math.max.apply(null,dates));
var earliest = new Date(Math.min.apply(null,dates));


Q:

$\sum_{k=-200}^{202}2^{2k+4}$

$$\sum_{k=-200}^{202}2^{2k+4}$$
I know I can try putting it in the online calculators and they would give me the answer, but I would like to keep that as my last resort. I am supposed to give an exact answer while showing each step. I have tried putting in $k$ values, for example
$s=2^{-396}$ when $k=-200$.
This pattern stays constant until you reach $k=-2$ where $s=1$. Then it's $2^2$, $2^4$, etc.
I do get the pattern, but how can I use what I know to find the exact sum.
I need help finding the answer and show each step I take.

A:

Hint: easier task:
$$\sum_{k=-2}^{2}2^{2k+4}=2^4\sum_{k=-2}^{2}2^{2k}=2^4\sum_{k=-2}^{2}4^{k}=2^4(4^{-2}+4^{-1}+4^0+4^1+4^2)= \\ 16\cdot \frac{4^{-2}(4^5-1)}{4-1}=341.$$
Now you can use the same method for your sum.


Q:

How to find list of attached data-sets in R?

Is there any method in R to find out what data-sets have been attached.  In my work flow i use the console and build a script.  I try out the lines of code in console and once i am satisfied with the results, i add them to a script so that I can reproduce the results later.  For past week i have been playing with a few data-sets.  I think I attached and detached a number of them over time.  But now I need to know what data-sets are current attached, so that I can detach them.

A:

I guess you are searching for the search() command. This should show the attached dataframes and packages you have included.
also type help(search) and check what it is doing.

A:

Use search() to find out which objects are attached.
Since this will also tell you about all packages that are attached, you can use a regular expression to remove the packages from the search results:
Attach mtcars:
attach(mtcars)
The following object(s) are masked from 'package:ggplot2':

    mpg

Now use search() and a regexp:
attached <- search()
attached[!grepl("package", attached)]
[1] ".GlobalEnv"    "mtcars"        "tools:rstudio" "Autoloads"

A:

To bring the answer in line with the suggestions in the comments, I am separating the code into three parts. The first simply produces a list of attached datasets. The second removes a single instance of attached datasets. The third handles situations where a dataset has been attached multiple times:
1. Output List of Attached Datasets
This code will produce a list of attached datasets for the user to examine:
intersect(search(), objects())
if you get "character(0)" - there are no data objects attached in the global env
2. Automatically "Cleanup" & Detach All Attached Datasets
This code will take that list of attached dataset and detach all attached objects (datasets). It should leave non-objects alone. So, it is a fairly simple, safe, and reliable way to "clean-up" the Global Environment:
Note: this will only work if each object is attached only once, otherwise you will have to run the command again. The next portion of the answer handles this case also.
#works if only attached each object once
lapply(X = intersect(search(), objects()),
FUN = function(X){detach(name = X, character.only = TRUE)})

3. Detach All Even When Objects Are Attached Multiple Times
3(a) Multiple attachments
This code will detach all attached objects (datasets) even if they have been attached multiple times. The above operation cannot handle this because R will not include the name of the object twice, even if it has been attached twice by the user.
So:
attach(data.df)
intersect(search(), objects())

And,
attach(data.df)
attach(data.df)
attach(data.df)
intersect(search(), objects())

Will produce the same output: [1] "data.df"
Even though the latter case needs detach(data.df) to be called three times to clear the Global Environment. As a result, we need to put the answer from Part 2 in a loop.
3(b) Produce output for user
In addition, the clean-up will output a list of dataset names for each successful "detach()" operation. This lets the user know which datasets were detached and how many times.
Note: I am sure this could be cleaned up a little, but this piece of code gets the job done reliably.
# the repeat handles cases where objects of identical name were
# attached (or, object was attached twice by mistake).
# It also outputs the name of objects as they are detached.

repeat{
  x <- lapply(X = intersect(search(), objects()),
         FUN = function(X){detach(name = X, character.only = TRUE)})

  y <- lapply(x, function(X){cat(attr(X,"name"), "\n")})

  if(identical(x, list())){break}
}


Q:

many elements of a listbox to another

This is the first time I use this medium to ask for help. I wanted to know how , in my code , include two listbox . One that makes querying the database and , through a button , send it to the other, and to do so with more than one option , and then , as in the php code to put the data from the second listbox on a table database. Thank you.
<?php
include("server.php");
$conexion = mysql_connect($server,$user, $pass) or die ("
 No se puede conectar con la base de datos");
$conectarbase = mysql_select_db ($bd);

$consulta = mysql_query("SELECT * FROM modalidad")

?>

    <meta charset = "iso-8859-1"/>
    <meta name = "description" content = "Ejemplo de HTML5"/>
    <meta name = "keywords" content = "HTML5, CSS3, Javascript"/>
    <title>PRECEPTORÍA</title>
    <link rel="shortcut icon" href="./style/favicon.png" />
    <link rel = "stylesheet" href = "./style/style.css">

        <form>
          <fieldset id = "fieldsetalum">
            <legend id = "legendalum">Registro de nuevos alumnos</legend>
            <select name="combo1" multiple size="8">
              <?php
while ($fila = mysql_fetch_row($consulta))
{
echo "<option value='".$fila['0']."'>".$fila['1']."</option>";
}
?>
            </select>
            <select name="combo2" multiple size=></select>
          </fieldset>
        </form>

A:

Your form needs an action to submit to itself:
     <form name="form" id="form" action="<?php echo echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>" method="post">

You could add an onChange(); event to your select1 dropdown
     <select name="combo1" multiple size="8" onChange="submit_this();">

and have a JavaScript script in your

Then you would have to use php to collect the values from the submitted page
      $combo1 =  mysqli_real_escape_string( $_POST['combo1'] );

and then you could return the page with the second dropdown, constructed in much the same way as you made the first one, using the data you get back from the first one to set up the second one. You could wrap the first dropdown in an isset():
        if( !isset( $combo1 ) ){
        // make your first select boxes
        }

and the second one in
        if( isset( $combo1 ) ){
        // make your second select boxes if combo1 returned a value
        }

so that they will only appear when needed.
As @NanaPartykar says, mysqli is the only way to go.
It will be dependent on JavaScript, so, if you prefer, you could have a submit button instead of the JavaScript function:
     <input type="submit" name="submit" value="Pick Sizes" />

This looks a handy referenc e for how to use select boxes: PHP code to get selected text of a combo box
I hope this will give you an idea of how it could be done - the SESSION variables remain to be properly defined in the loop for the second dropdown but they will probably come directly from your database at that point rather than from the session array used for demo purposes.
All values are set as numbers;
intval(); converts whatever is submitted to an integer to clean it up.
Then you can get back the corresponding value of what was submitted from the session variable you set from your database originally.
That way you will only be getting a single number value from your dropdowns which you can use to look up to get the answer you want
  <?php session_start(); ?>
  <!DOCTYPE html>

  <title>PRECEPTORÍA</title>

    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
    <?php
    $main_opt = array();
    $_SESSION['opt_vals'] = array();
    $main_opt[0] = "Select Item";
    $main_opt[1] = "Ice Cream";
    $main_opt[2] = "Trousers";
    $main_opt[3] = "Tee Shirts";
    $_SESSION['opt_vals'][1][0] = "Select Flavour";
    $_SESSION['opt_vals'][1][1] = "Vanilla";
    $_SESSION['opt_vals'][1][2] = "Chocolate";
    $_SESSION['opt_vals'][1][3] = "Strawberry";
    $_SESSION['opt_vals'][1][4] = "Tuttifrutti";
    $_SESSION['opt_vals'][2][0] = "Select Colour";
    $_SESSION['opt_vals'][2][1] = "Black";
    $_SESSION['opt_vals'][2][2] = "Red";
    $_SESSION['opt_vals'][2][3] = "Green";
    $_SESSION['opt_vals'][2][4] = "Blue";
    $_SESSION['opt_vals'][3][0] = "Select Size";
    $_SESSION['opt_vals'][3][1] = "Small";
    $_SESSION['opt_vals'][3][2] = "Medium";
    $_SESSION['opt_vals'][3][3] = "Large";
    $_SESSION['opt_vals'][3][4] = "X Large";
    $i = 0;
    if(!isset($_POST['combo1']) && !isset($_POST['combo2'])){
        echo '<select name="combo1" onChange="submit();">' . "\n";
        //while ($fila = mysqli_fetch_row($consulta)){
        while($i < count($main_opt)){
        echo "<option value='".$i."'>".$main_opt[$i]."</option>\n";
             $o = 0;
             // load your sub options array here
             if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
             while($i < count($_SESSION['opt_vals'][$i])){
             $_SESSION['opt_vals'][$i] = $o;
             if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
             $_SESSION['opt_vals'][$i][$o] = $_SESSION['opt_vals'][$i][$o];
             $o++;
             }
         $i++;
         }
     echo '</select>'  . "\n";
     }else{
         if(intval($_POST['combo1']) >= 1) $_SESSION['combo1_val'] = $combo1_val =intval($_POST['combo1']);
         if(intval($_POST['combo1']) >=1){
             $i = 0;
             echo '<select name="combo2" onChange="submit();">' . "\n";
             while($i < count($_SESSION['opt_vals'][$combo1_val])){
             echo "<option value='".$i."'>".$_SESSION['opt_vals'][$combo1_val][$i]."</option>\n";
             $i++;
             }
         }
     echo '</select>'  . "\n";
     }
     if(intval($_POST['combo2']) >= 1) $_SESSION['combo2_val'] = $combo2_val =intval($_POST['combo2']);
     if($_SESSION['combo1_val'] >=1 && $_SESSION['combo2_val'] >=1){
     // use the result to do  whatever you want
     echo 'Thank you! You have selected ' . $_SESSION['opt_vals'][$_SESSION['combo1_val']][$_SESSION['combo2_val']] . " " . $main_opt[$_SESSION['combo1_val']] . '.';
     }
     // Do any mysqli adjustments to your database here
     // reset to go again
     if($_SESSION['combo2_val'] >= 1){
     $_SESSION['combo1_val'] = 0;
     $_SESSION['combo2_val'] = 0;
     }
     ?>
             </form>
             <a href="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">Click to start a new selection

You could remove onChange="submit();" and replace it with a normal submit button on the form if you prefer.


Q:

Meaning of the phrase "I am all ears"

I was going through Stack Overflow and I noticed this phrase.

I am all ears

Is it some spelling error of "I am all yours" or does it mean something like "I am eager to listen"?
What is meant by this phrase & what do you call this type of phrase?

A:

It is a casual idiom that simply means "I am listening," or "I want to hear what you have to say."


Q:

Customize text for invalid fields in HTML

I am trying to display a customized message when the text entered does not match the pattern.
Following is the code I have used.
<input pattern="[a-zA-Z0-9]" name="firstName" id="firstname" required="" type="text" />

When I enter a valid text like 'akshay'; it is showing me the invalid message 'Please match the requested format'
Also, I want to change this message to a customized one. I tried using the code given above but its is not working. Below is the code I have used below:
<script>
document.getElementById("firstname").addEventListener("invalid", function (e) {
var elem = e.target;

if (elem.value != "") {
    e.target.setCustomValidity('Cannot contain special characters');
}
});
</script>

Please help me with this code.

A:

Try to use oninvalid method in the input tag
<input pattern="[a-zA-Z0-9]*" name="firstName" id="firstname" required="required"
type="text" oninvalid="oninvalid="this.setCustomValidity(this.willValidate?'':'Cannot contain special characters')" />


Q:

Syntax error in CShell Script

Write Script to read a positive integer number then it computes the following sequence:
If the number is even, halve it
If it is odd multiply it by 3 and add1
You should repeat this process until the value is 1, printing out each value and how many of these operations you performed.
#! bin\csh

echo "please enter any integer number :) "

set count=0

set number=$<

while($number != 1)

   if($number % 2) then

       @ number = number * 3 + 1

   else

       @ number = number / 2

   endif

   echo " $number "

   @ count = count ++

end

echo I performed these operations $count times

When I run the script I get the following error:
@: Expression Syntax.

A:

I believe its $variable to obtain its value
$
    Obtains the value of the variable.

@ var = $a + $x * $z

source  http://www.eng.hawaii.edu/Tutor/csh.html
So that would be
@count = $count +1

And the line
#!bin\csh

makes me shiver


Q:

How is the Arqade spaceship supposed to work in the new design?

Previously a mouse over on the spaceship would cause it to launch the lazer weapons. But in the new design, this is no longer the case.
But I do see it launch the lazer weapons sometimes, just not sure what triggered it.
How is the Arqade spaceship supposed to work in the new design?

A:

As Catija mentioned in an edit of this answer,

The ship only fires once per page load after a five second delay.


Q:

Should I "Compile .py Files to Byte Code after Installation"?

I'm installing Python 3.2 32bit on Win7 machine, there is the following option:

Compile .py Files to Byte Code after Installation

Should I leave option unchecked or is the compilation recommended?

A:

Since the bytecode is unlikely to change regardless of how many times it is compiled, the interpreter can take advantage of the small speedup gain. Unless you are very short of hard drive space, you should select this option.


Q:

Get impersonated user name

I have a class that needs to know name of a user currently in effect. Environment.UserName or WindowsIdentity.GetCurrent().Name is for that. But when impersonation is enabled, they return LocalUser name not the ImpersonatedUser name.
How to get name of currently impersonated user?
The app is C# console application, I know that impersonation is in effect since I get priviledges of ImpersonatedUser. Sure I can make impersonation code save impersonated username to some global variable, but it would be wrong.
UPDATE:
Impersonation code:
if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS/*=9*/, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
  if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
  {
    WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
    _impersonationContext = tempWindowsIdentity.Impersonate();

    // WindowsIdentity.GetCurrent().Name equals "LocalUser"
    // while userName equals "ImpersonatedUser"
    ...

I have control over impersonation code, but I would prefer to keep it independant from other parts of solution.

A:

Just this (instance member)
WindowsIdentity.Name

http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx
You don't even have to have called Impersonate().
EDIT
Without access or knowledge of the impersonation,
WindowsIdentity.GetCurrent(false).Name
(same as)
WindowsIdentity.GetCurrent().Name

should work.  http://msdn.microsoft.com/en-us/library/x22bbxz6.aspx

false to return the WindowsIdentity of the thread if it is impersonating or the WindowsIdentity of the process if the thread is not currently impersonating.

If you were using LOGON32_LOGON_NEW_CREDENTIALS, bear in mind that (http://www.pcreview.co.uk/forums/logonuser-issues-t1385578.html) the logged in context remains unchanged while a second token is created for remote resources - this is why your WindowsIdentity.Name remains unchanged - in effect it is still correct, because you have not actually impersonated the identity, all you have is a token to access resources as the secondary identity while the entire program/thread is still running under the original Windows Identity.

A:

Ok, it appears that problem was in propert impersonalization logon type.
If in impersonalization code replace LOGON32_LOGON_NEW_CREDENTIALS (9) with LOGON32_LOGON_INTERACTIVE (2) everything works fine - WindowsIdentity.GetCurrent().Name and Environment.UserName both return ImpersonatedUser as expected.


Q:

Help me spot the error in my solution to the equation $25^x=6+5^x$

I would use some help in figuring out where my math went wrong in solving the equation
$$25^x=6+5^x $$
My Approach:
$$ 5^{2x}-5^x = 6 $$
$$ 5^x(5^{2}-1) = 6 $$
$$ \ln(5^x(5^{2}-1)) = \ln(6) $$
$$ \ln(5^x) +\ln(5^{2}-1) = \ln(6) $$
$$ x\ln(5) +\ln(24) = \ln(6) $$
$$ x  = \frac {\ln(6)-\ln(24)} {\ln(5)} $$
$$ x  = \frac {\ln \frac{6}{24}} {\ln(5)} $$
$$ x  = \frac {\ln \frac{3}{12}} {\ln(5)} =\log_5 \frac {3}{12}$$
The textbook solution of  $25^x = 5^x + 6$ is but taking $25 = 5^2$
then noticing that we have a ‘quadratic in disguise’.
Letting $u = 5^x$ we get $u^2 − u − 6 = 0$ which gives $u = −2$ or $u = 3$. Since $u = 5^x$ , we have $5^x = −2$ or $5^x = 3$. Since
$5^x = −2$ has no real solution, we take natural logs and get $\ln (5^x
) = \ln(3)$ so that $x \ln(5) = \ln(3)$
or $x=\frac{\ln(3)}{\ln(5)}$.
Please note that I am not disputing the textbook solution. I just can't seem to figure out where I went wrong.

A:

The second line is not true. Try expanding it. You would notice it doesn't reproduce the first line.
Rather, you can rewrite it in terms of base $5$ and rename $5^x$ as another variable which will lead to a quadratic equation.

A:

$5^{2x}-5^x\neq 5^x(5^2-1)$
We can see this quickly by letting $x=0$


Q:

Cannot convert a char value to money in SQL

I have a table called 'companyInfo' and the data type of 'Amount' is nvarchar and sample data looks like:
companyInfo
IDs | company   | year | Amount
----+-----------+------+-------
1   | Company A | 2011 | 40.00
2   | Company B | 2011 | Null
2   | Company C | 2011 | 100.00
4   | Company D | 2011 | 205.11
5   | Company E | 2011 | 0
6   | Company F | 2011 | Null

I wrote Query like below:
select IDs
  , company
  , sum(ISNULL(CAST(Amount AS MONEY), 0)) Amount
  , year
from companyInfo
where Amount is not null
  and year(cast(year as date)) = '2018'
group by IDs
  , company
  , Amount
  , year

got below Error:

Error:
  Msg 235, Level 16, State 0, Line 27
  Cannot convert a char value to money. The char value has incorrect syntax.

A:

This is what you want..Both queries provide same results
Style 1
SELECT IDs
    ,Company
    ,FORMAT(YearFormed, 'yyyy') AS YearFormed
    ,Amount

FROM
(SELECT C.IDs, C.Company, CONVERT(DATE, C.YearFormed) AS YearFormed, CONVERT(MONEY, C.Amount) AS Amount FROM temp.dbo.CompanyInfo AS C) AS RC
WHERE Amount IS NOT NULL

Style 2
WITH RESULT AS --3-I named this query with the intention to formart the Year in which the companies were formed
(
SELECT IDs --1-Started from here
    ,Company
    ,CONVERT(DATE, C.YearFormed) AS YearFormed --2-I converted to Date here so I couldnt run format too so
    ,CONVERT(MONEY, C.AMOUNT) AS Amount
FROM temp.dbo.CompanyInfo AS C
WHERE C.AMOUNT IS NOT NULL
)
SELECT R.IDs
    ,R.Company
    ,FORMAT(R.YearFormed, 'yyyy') AS YearFormed --4-I used this SELECT statement only to format this column
    ,R.Amount
FROM RESULT AS R

This is what it gets as a result


Q:

How to download all jars for an old Spring version (3.0.7)

I am performing a server upgrade for some pretty old portlets developed with Spring. Developers no longer in the team used Spring version 3.0RC1 and I want to upgrade those Spring framework jars to last 3.0 version (I believe it is 3.0.7) but I cannot find any "previous versions" repository anywhere.
In Spring official site the oldest available is 3.1.4 but as quite a lot of code is developed for 3.0RC1 I don't find a good idea to do a major/minor version change.
Are older jars available anywhere? I've dedicated some time googling and can't find them anywhere.
http://grepcode.com has some of the files but not all. Files in the project are:
org.springframework.asm-3.0.0.RC1.jar
org.springframework.beans-3.0.0.RC1.jar
org.springframework.context-3.0.0.RC1.jar
org.springframework.context.support-3.0.0.RC1.jar
org.springframework.core-3.0.0.RC1.jar
org.springframework.expression-3.0.0.RC1.jar
org.springframework.web-3.0.0.RC1.jar
org.springframework.web.portlet-3.0.0.RC1.jar
org.springframework.web.servlet-3.0.0.RC1.jar
spring-aop-1.2.6.jar
spring-jdbc-2.5.4.jar
spring-tx-2.5.4.jar

Thanks

A:

Spring makes its releases available in Maven central: http://search.maven.org/#browse|528292745


Q:

Why not all data traffic is going through the 3GDT in 3G data network

What is the reason for only part of the 3G data traffic to be going through the 3G Direct Tunnel and another part is going through the SGSN. There are counters for traffic in IuPS interface which still show there is data traffic in the SGSN. The greater part of the traffic is going through the Direct Tunnel, but not all.
The Iu user plane traffic should go through the Direct tunnel and the Iu control plane traffic should go to the SGSN. And counters still show user pane traffic going through the SGSN. There must be a reason for this.

A:

Yes, there is a reason to it.
Be advised that even if the 3GDT is set up between RNC and GGSN, the "2G non home public" users , ie "2G roamer users" only use IuPS on your picture, and don't use 3GDT.
We both know that 2G users can access 3G Core network depending on the policy of authorization mode based on IMSI or based on algorithm mode in SGSN.

The SGSN does not enable 3GDT for 2G Data user: for 2G data subscriber, the SGSN sends a RAB message request information containing user-plane IP address and TEID of the SGSN, not GGSN to the RNC.

To do:

Please export the number of 2G Data Subscriber in your
  network and
  export also the number of 2G PDP Context,
  there are chances they will correspond.


Q:

Infinite product $\prod\limits_{n=1}^\infty\cos( 1/n)$

Infinite product $\prod\limits_{n=1}^\infty\cos( 1/n)$

My attempt is to use the complex representation and the Maclaurin Series of $\cos(1/n)$ but I could not find the formula
$$\prod_{n=0}^\infty (1 + {b_n})$$
Any hints please.

A:

$\prod_{n=1} ^{\infty } (1+b_n)$ converges if $\sum_{n=1} ^{\infty } |b_n| <\infty$. If $b_n=\cos (\frac 1 n) -1$ then   $\sum_{n=1} ^{\infty } |b_n| \leq \sum_{n=1} ^{\infty }\frac 1 {2n^{2}} <\infty$ so the product converges. [I have used the inequality $0\leq 1-\cos x \leq \frac {x^{2}} 2$].


Q:

Serverless Framework - Switch existing application from REST to HTTP in AWS API Gateway

AWS just announced HTTP API support for Amazon API Gateway. There are some very impressive pricing and performance numbers coming in with this new release. Off the top, AWS says that the general cost of using v2 will be 70% cheaper and have 50% lower latency than v1. I'd love to try this out in my existing projects.
I use Serverless framework in my application. How do I convert my existing API to use this new feature? This is what my serverless.yml file looks like:
service: amitsn-blog-api

# Use the serverless-webpack plugin to transpile ES6
plugins:
  - serverless-webpack
  - serverless-offline

# serverless-webpack configuration
# Enable auto-packing of external modules
custom:
  webpack:
    webpackConfig: ./webpack.config.js
    includeModules: true

provider:
  name: aws
  runtime: nodejs10.x
  stage: prod
  region: ap-south-1

  # 'iamRoleStatements' defines the permission policy for the Lambda function.
  # In this case Lambda functions are granted with permissions to access DynamoDB.
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
      Resource: "arn:aws:dynamodb:ap-south-1:*:*"
    - Effect: Deny
      Action:
        - logs:CreateLogGroup
        - logs:CreateLogStream
        - logs:PutLogEvents
      Resource: "*"

functions:
  # Defines an HTTP API endpoint that calls the main function in create.js
  # - path: url path is /posts
  # - method: POST request
  # - cors: enabled CORS (Cross-Origin Resource Sharing) for browser cross
  #     domain api call
  # - authorizer: authenticate using the AWS IAM role
  options:
    handler: options.main
    events:
      - http:
          path: posts
          method: options
          cors: true
  create:
    handler: create.main
    events:
      - http:
          path: posts
          method: post
          cors: true
          authorizer: aws_iam
  get:
  # Defines an HTTP API endpoint that calls the main function in get.js
  # - path: url path is /posts/{id}
  # - method: GET request
    handler: get.main
    events:
      - http:
          path: posts/{id}
          method: get
          cors: true
  list:
    # Defines an HTTP API endpoint that calls the main function in list.js
    # - path: url path is /posts
    # - method: GET request
    handler: list.main
    events:
      - http:
          path: posts
          method: get
          cors: true
          integration: lambda
          request:
            template:
              application/json: '{ "postType" : "$input.params(''postType'')" }'
  update:
    # Defines an HTTP API endpoint that calls the main function in update.js
    # - path: url path is /posts/{id}
    # - method: PUT request
    handler: update.main
    events:
      - http:
          path: posts/{id}
          method: put
          cors: true
          authorizer: aws_iam
  delete:
    # Defines an HTTP API endpoint that calls the main function in delete.js
    # - path: url path is /posts/{id}
    # - method: DELETE request
    handler: delete.main
    events:
      - http:
          path: posts/{id}
          method: delete
          cors: true
          authorizer: aws_iam

# Create our resources with separate CloudFormation templates
resources:
  # API Gateway Errors
  - ${file(resources/api-gateway-errors.yml)}

A:

The HTTP API is not yet supported by the Serverless Framework, although we are currently working on it! You can track the effort here: https://github.com/serverless/serverless/issues/7052


Q:

Consolidating procedural code to an associative array object

I have 5 functions that check user input against regular expressions...these regular expressions have been abstracted out and put here as suggested in previous post.
Now I want to abstract out the functionality and put the code into an associative array per the previous post as well..however their seemed to be some contention as to whether this is best practice? Is this O.K to do?
Is it good practice to put these functions into an associative array of functions?  The previous post doing this is not up..as I'm guessing they decided against it.
But basically how to do you group similar methods together properly.
EDIT 1: // consolidated regular expressions

var patterns = {
  name: /^[a-zA-Z-\s]{1,20}$/,
  email: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/,
  pass: /.{6,40}/,
  url:  /^[-\w&:\/\.=\?,#+]{1,}$/,
  aml:  /<(.+)_([a-z]){1}>$/
};

// checks full name which allows characters and dashes

function check_name(text,id,res)
  {
  for(var d=0;d<=0;d++)
    {
    if(!patterns["name"].exec(text.value))
      {
      o2(id,res);
      return 0;
      }
    }
    return 1;
  }

// checks for valid email form

function check_email(text,id,res)
  {
  if(!patterns["email"].exec(text.value))
    {
    o2(id,res);
    return 0;
    }
  return 1;
  }

// checks for password length

function check_pass(text,id,res)
  {
  if(!patterns["pass"];.exec(text.value))
    {
    o2(id,res);
    return 0;
    }
  return 1;
  }

// checks for valid url form

function check_url(text,id,res)
  {
  if(!patterns["url"].exec(text.value))
    {
    o2(id,res);
    return 0;
    }
  return 1;
  }

// checks for aml form

function check_aml(text)
  {
  if(a=patterns["aml"].exec(text))
    {
    if(a[2]=='p')
      {
      return 0;
      }
    else if (a[2]=='f')
      {
      return 1;
      }
    }
  else
    {
    return 2;
    }
  }

A:

I don't think there are any issues with creating a common place to store your patterns.  This in fact seems like a good approach.  However I don't see the need to have your individual checking functions be made aware of the global storage.  They should instead be made simply aware of the pattern they are checking and the source against which they check.  If you take this approach your checking code can be dramatically simplified
var make_check = function (pattern) {
  return function (text, id, res) {
    if(!pattern.exec(text.value)) {
      o2(id,res);
      return 0;
    }

    return 1;
  };
};

var check_name = make_check(patterns.name);
var check_email = make_check(patterns.email);
var check_pass = make_check(patterns.pass);
var check_url = make_check(patterns.url);

Here I've removed the notion of the global storage from the checking function.  Since the rest of the code is so similar it can be abstracted out to a single method which is passed the pattern it's looking to match.


Q:

Using rsync to copy directory structure only keeping certain files

I am using this code
find  /path/to/directories/ -d  -iname "*modified.tif" -type f -exec rsync -R --relative -v {} test/ \;

to copy the directories within orig_images and only keeping *modified.tif files. However, my result looks like
test/path/to/directories

whereas I want it to look like
test/directories

It's trivial to move the directories into test/ but I'd like to be able to do this in the future without having to add that extra step. How can I accomplish this? Cheers.

A:

Change the directory properly:
cd /path/to/; find  directories/ -d  -iname "*modified.tif" -type f -exec rsync -R --relative -v {} test/ \;
You may adapt the target by set the test/ to the directory you want.


Q:

/usr/bin/mail freezes and never sends. permissions?

I'm trying to send mail through shell and it freezes. the script seems fine and i'm really confused. here it is in PHP:
$mail = '/usr/bin/mail -a
    "Content-type: '.$header_content_type.';"
    -a "Reply-to: '.$header_reply_to.';"
    -a "List-Unsubscribe: '.$header_unsub.';"
    -s "'.$header_subject.'" "'.$email.'" < '.$myFile.'';
    exec($mail);

i echo'd everything to make sure it was pulling data into the variables and it was. when it executes, it freezes and does nothing. could this be a permissions error?
** EDIT **
i checked the mail log and saw an issue with virtual_alias_maps in the postfix main.cf
i made the necessary adjustments and it seems to work great. thanks to all!

A:

Question #1:
Can you execute the same command from the command line? Let's say instead of executing the command, what happens if you echoed $mail to the console. Then, copy the command, and then pasted it to a command prompt and hit enter?
Question #2:
Why in the heck are you using the mail command and not the PHP mailing function and modules. I'm just a dabbler in PHP, but I know that you can have PHP send mail out in a machine independent manner.


Q:

How to overcome 'Differing war philosophy' to create an alliance in Stellaris?

The Empire found a true friend, the trade is good, Science is exchanged, dependency is guarantied and all the rest.
Our governor wish to create an alliance with them - all is good beside 'Differing war philosophy' which is the only obstacle.
How can our government change policy accordingly, to overcome this last obstacle?

A:

You can't get rid of the differing war philosophy penalty, because that is based on your empire ethics. Instead, you need to get enough bonuses to offset the penalty.
I'd have to do some testing to ensure that this is the case, but here are some things that I believe would help:

Increase their opinion of you. You're already getting a +21 bonus. There should still be some levels higher than that, though.
Some things, like a Non-Aggression Pact, will help not only your opinion, but give a direct buff to the Alliance negotiations. I think Migration Access may help in this way as well. You may not be able to get migration access, depending on your mutual ethics, but one-way is probably better than neither.
You don't appear to be trading with the empire. Trading improves their opinion of you by +5, and may directly impact the alliance negotiations. I often just trade a few minerals a month for a few energy a month.
Common rivals improve relations. Determine who their rival is from the Empire Contacts screen, and declare the same rival.
Common threats improve relations. If they're at war with somebody, go to war with them as well.
If you become significantly more powerful, you can increase the "relative power of empires" modifier.


Q:

cosine_similarity returns matrix instead of single value

I am using below code to compute cosine similarity between the 2 vectors. It returns a matrix instead of a single value 0.8660254.

[[ 1.         0.8660254]
[ 0.8660254  1.       ]]

from sklearn.metrics.pairwise import cosine_similarity
vec1 = [1,1,0,1,1]
vec2 = [0,1,0,1,1]
print(cosine_similarity([vec1, vec2]))

A:

Based on the documentation cosine_similarity(X, Y=None, dense_output=True) returns an array with shape (n_samples_X, n_samples_Y). Your mistake is that you are passing [vec1, vec2] as the first input to the method. Also your vectors should be numpy arrays:
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
vec1 = np.array([[1,1,0,1,1]])
vec2 = np.array([[0,1,0,1,1]])
#print(cosine_similarity([vec1, vec2]))
print(cosine_similarity(vec1, vec2))

X : ndarray or sparse array, shape: (n_samples_X, n_features)
      Input data.

So you have to specify the dimension.
np.array([1, 2]).shape

has funny shape:

(2, )


Q:

How to construct a dataset with lists as columns

So I know this should be pretty easy, but I cannot seem to find a solution anywhere, so thanks in advance for your help:
I have three Lists (with numbers as elements) named lista, listb and listc and I want to construct adataset with columns "a" to "c", where column "a" contains all elements from "lista" and so on. I then want to be able to use the data in other dataset operations (like Select or LinearModelFit etc.). And, while I don't know if it makes a difference, each list has 1000 elements and all lists are therefore equally long.
Thanks again for inputs!

A:

Let's take some example lists:
lis1 = {1, 2, 3, 4, 5};
lis2 = {6, 7, 8, 9, 0};
lis3 = {2, 4, 6, 8, 9};

Now you can combine your lists into one list and your headers into a different list:
data = {lis1, lis2, lis3};
header = {"a", "b", "c"};

To create a dataset just do:
Dataset@Map[AssociationThread[header, #] &]@Transpose[data]

A:

If using Mathematica version 10.1 or later, we can write:
lista = {1, 2, 3, 4, 5};
listb = {6, 7, 8, 9, 0};
listc = {2, 4, 6, 8, 9};

<| "a" -> lista, "b" -> listb, "c" -> listc |> // Query[Transpose] // Dataset

We can also write:
<| "a" -> lista, "b" -> listb, "c" -> listc |> // Dataset // Transpose

... but version 10.4 introduced a regression where the resulting dataset loses its type information (the expression works fine in versions 10.1, 10.2 and 10.3).


Q:

Facebook SDK: How to correct initialize FBSessionTokenCachingStrategy with old token?

How to correct initialize FBSessionTokenCachingStrategy?
I have: facebook-ios-sdk (not new, but 3.0).
Also, i have an iOS-project, thtat must run under iOS 5.*
And i have a trouble:
How to correct initialize session, if it must be reopen (not open)?
I have a token from last session and i want to login with this token.
But for this i need to create a FBSessionTokenCachingStrategy instance.
How to do this?
Thanks for help!

A:

As i said before, i need this to create session and open it.
Let's see, what i want:

load TOKEN from my server. (and misc info about user).
create session
open session

NOTE:
It can be, that FBSessionTokenCachingStrategy instance was not saved on device.
And i need to create it.
And this is my algorithm: (code will be posted later)

load TOKEN, expirationDate, userID from my server.
create FBSessionTokenCachingStrategy instance manually, input in it's settings dictionary all fields, loaded in first step and(!) PERMISSIONS (it predefined in my app).
init session.
open session.

Success!


Q:

Azure DevOps: Restrict pull requests to subset of team

Suppose I have a team with 10 developers, but I want all pull requests to be completed by a senior developer of which I have 2 on my team. In my branch policy I can automatically add teams, individual users, and groups as reviewers.
Teams - As mentioned I don't want the whole team to be able to approve the review.
Individuals - I don't want to add individual senior devs to the policy because if those
Sr Devs change role, move to a different team, etc I have to go update all the policies.
Groups - Would be ideal, but there's a caveat. Pull requests assigned to groups don't
show as assigned to the user when reviewing "My pull requests". PRs only show if assigned
to an individual or a team.
Broken? Working as designed? Future functionality?

A:

The way I've managed this in the past is to have two teams:
Developers:

Matt
Mark
Bill
[project]\Senior Developers

Senior Developers:

Sue
Pam

Most privileges you define on Developers.  Additional privileges like PR permsissions you assign to Senior Developers.
One could also add the Senior Developers team as "required" on the branch policy, and keep the Developers team rights to pull requests, allowing other devs to still approve requests and comment etc. but the request can't be completed until a senior dev approves it.


Q:

Search a Custom DataClass for Results

I have built a custom Data Class that stores IP Address Details.
        Public Class IPAddressDataItem

        Private _ID As Integer
        Private _IP As String
        Private _Name As String

        Public Property ID() As Integer
            Get
                Return _ID
            End Get
            Set(ByVal value As Integer)
                _ID = value
            End Set
        End Property
        Public Property IP() As String
            Get
                Return _IP
            End Get
            Set(ByVal value As String)
                _IP = value
            End Set
        End Property
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(ByVal value As String)
                _Name = value
            End Set
        End Property\

        Public Sub New(ByVal id As Integer, ByVal ip As String, ByVal name As String)
            _ID = id
            _IP = ip
            _Name = name
        End Sub

    End Class

What I'm trying to figure out how to do is search it for specific data.
Example.. I send it an IP address and it will return the name to me.
Does anyone know how I would do this?

A:

First of all, you need to put the object in a collection.  To do this, you need to choose a data structure (i.e. List, ArrayList, etc)
Dim Items as List(Of IPAddressDataItem)

Then, you can iterate through the collection, find the item based on the search criteria and return the data required.
Function GetName(ByVal IP As String) As String
    For Each Item As IPAddressDataItem In Items
        If Item.IP.CompareTo(IP) = 0 Then
             Return Item.Name
        End If
    Next
End Function

Right now, if you have an instance of the object, you can just access the property directly.


Q:

Golang multipart uploads with chunked `http.GET` and Goamz `multi.PutAll`

I'm using the Goamz package and could use some help getting bucket.Multi to stream an HTTP GET response to S3.
I'll be downloading a 2+ GB file via chunked HTTP and I'd like to stream it directly into an S3 bucket.
It appears that I need to wrap the resp.Body with something so I can pass an implementation of s3.ReaderAtSeeker to multi.PutAll
// set up s3
auth, _ := aws.EnvAuth()
s3Con := s3.New(auth, aws.USEast)
bucket := s3Con.Bucket("bucket-name")

// make http request to URL
resp, err := http.Get(export_url)
if err != nil {
    fmt.Printf("Get error %v\n", err)
    return
}

defer resp.Body.Close()

// set up multi-part
multi, err := bucket.InitMulti(s3Path, "text/plain", s3.Private, s3.Options{})
if err != nil {
    fmt.Printf("InitMulti error %v\n", err)
    return
}

// Need struct that implements: s3.ReaderAtSeeker
// type ReaderAtSeeker interface {
//  io.ReaderAt
//  io.ReadSeeker
// }

rs := // Question: what can i wrap `resp.Body` in?

parts, err := multi.PutAll(rs, 5120)
if err != nil {
    fmt.Printf("PutAll error %v\n", err)
    return
}

err = multi.Complete(parts)
if err != nil {
    fmt.Printf("Complete error %v\n", err)
    return
}

Currently I get the following (expected) error when trying to run my program:
./main.go:50: cannot use resp.Body (type io.ReadCloser) as type s3.ReaderAtSeeker in argument to multi.PutAll:
    io.ReadCloser does not implement s3.ReaderAtSeeker (missing ReadAt method)

A:

You haven't indicated which package you're using to access the S3 api but I'm assuming it's this one https://github.com/mitchellh/goamz/.
Since your file is of a significant in size, a possible solution might be to use the multi.PutPart. This will give you more control than multi.PutAll. Using the Reader from the standard library, your approach would be:

Get the Content-Length from the response header
Get the number of parts needed based on Content-Length and partSize
Loop over number of part and read []byte from response.Body into bytes.Reader and call multi.PutPart
Get parts from multi.ListParts
call multi.Complete with parts.

I don't have access to S3 so I can't test my hypothesis but the above could be worth exploring if you haven't already.


Q:

forloops inside for loops in Django python

I have a question about Python Django.
this is my views
def index(request):
    contacts = Contact.objects.all()
    threeboxs = Threeboxes.objects.all()
    return render(request, 'home/index.html', {'threeboxs': threeboxs, 'contacts': contacts})

way we display in PHP
for(k=0; k<3; k++){
some css class, i will add the K value eg:someclass_0
echo threeboxs[k].title;
echo threeboxs[k].description;
}

I can display Python Code like this.
{% for threebox in threeboxs%}

{{ threebox.title }}

{{ threebox.description|linebreaks }}

{% endfor %}

But doing it this way I cannot update the css class with loops. Then I tried this way but that did not work.
{% context['loop_times'] = range(0, 3)
     for n in loop_times: %}
      {{ threebox[n].title }}
{% endfor %}

Can someone give me a suggestion about how I should do this?

A:

You are trying to cycle through some specified values as you iterate through the list, fortunately Django has you covered with the cycle templatetag.
{% for threebox in threeboxs%}

{{ threebox.title }}

{{ threebox.description|linebreaks }}

{% endfor %}

This would give you:

Title 1

Body 1

Title 2

Body 2

Title 3

Body 3

Title 4

Body 4

Title 5

Body 5

And so on...


Q:

Call some plug-in/function inside an object

The goal
Call Isotope inside an object.
The problem
By Google Chrome: Uncaught TypeError: Object [object Object] has no method 'isotope'.
The code
var mainResources = {
    // Execute this when the document is ready to go
    whenDocumentReady: function () {
        this.calculateResponsiveMeasures();

        jQuery("ul.products-list").isotope({
            itemSelector: "li",
            masonry: {
                gutterWidth: 15
            }
        });
    }
    [...]
}

I do not know what I have to do. By the way, thanks in advance. Cheers!

A:

The problem here is the fact that your object is initialized, before isotope.. Just make sure you include the isotope.js file, before the file where your object is loaded.


Q:

HTML5 style Audio tag with pure CSS

I have to questions here:
First - is there any way to style firefox audio tag like -webkit browsers. For example: I can use audio::-webkit-media-controls-panel to change background color.
Second - Is there any way to differ -webkit audio tag from -moz audio tag.
Now I will show you my problem:
http://jsfiddle.net/WB7yT/
this is how I style my audio tag for now.
I want to use this, but with firefox audio { height: 50px; } is a problem, which is needed for -webkit browsers.
any ideas?
P.S. please don't suggest javascript solutions

A:

Sorry, you can't. Chrome is the best browser for using experimental features such as the web audio api or new CSS3 pseudo selectors and other new styling elements.'
adit: you didn't want to use javascript but that is the only way to make a completely stylable player.


Q:

Visualize Hierarchical Data

I have a data visualization application in node and backbone.  My data is in a hierarchical form, so I have done my R&D but couldn't find a useful tool.  What are the best tool libraries that I can easily integrate into my application, to usefully visualize hierarchical data?
I have checked these links:
http://gephi.org/features/
http://wiki.pentaho.com/display/COM/Treemap
http://thewhyaxis.info/bubble-tree/

A:

You should be choosing D3.js or rapheal.js for this task.
There are a lot of examples on the web from which you may be able to to tweak your stuff.
Examples of visualizations built on D3:

http://biovisualize.github.io/d3visualization/
http://bost.ocks.org/mike/example/
http://christopheviau.com/d3list/

Note:
If you would like to compare D3 and raphealjs check:
D3.js vs Raphael.js
D3 rocks in terms of the amount of documentation, tutorials, and the demos that are out there on the web. IMHO you should go with D3, if support for earlier versions of IE is not a concern for you.

A:

In your scenario what i think D3 JS is the best tool yet . I think it will fulfill your needs . cheers :-)


Q:

Regular Expression for Ruby Integer

Ruby integers are written as using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string. The letters mentioned in the above description may be either upper or lower case and the underscore characters can only occur strictly within the digit string.
I need to create regular expression to check for Ruby integers in java string with the specification mentioned above.

A:

I assume the substrings that may represent integers are separated by spaces or begin or end the string. If so, I suggest you split the string on whitespace and then the use the method Kernel#Integer to determine if each element of the resulting array represents an integer.
def str_to_int(str)
  str.split.each_with_object([]) do |s,a|
    val = Integer(s) rescue nil
    a << [s, val] unless val.nil?
  end
end

str_to_int "22 -22 077     0xAB 0xA_B 0b101 -0b101 cat _3 4_"
  #=> [["22", 22], ["-22", -22], ["077", 63], ["0xAB", 171],
  #    ["0xA_B", 171], ["0b101", 5], ["-0b101", -5]]

Integer raises a TypeError exception is the number cannot be converted to an integer. I've dealt with that with an in-line rescue that returns nil, but you may wish to write it so that only that exception is rescued. It may be prudent remove punctuation from the string before executing the above method.


Q:

kubernetes configmaps for binary file

My kubernetes version is 1.10.4.
I am trying to create a ConfigMap for java keystore files:
kubectl create configmap key-config --from-file=server-keystore=/home/ubuntu/ssl/server.keystore.jks --from-file=server-truststore=/home/ubuntu/ssl/server.truststore.jks --from-file=client--truststore=/home/ubuntu/ssl/client.truststore.jks --append-hash=false

It says configmap "key-config" created.
But when I describe the configmap I am getting null value:
$ kubectl describe configmaps key-config
Name:         key-config
Namespace:    prod-es
Labels:       <none>
Annotations:  <none>

Data
====
Events:  <none>

I know my version kubernetes support binary data as configmaps or secrets but I am not sure what is wrong with my approach.
Any input on this is highly appreciated.

A:

kubectl describe does not show binary data in ConfigMaps at the moment (kubectl version v1.10.4); also the DATA column of the kubectl get configmap output does not include the binary elements:
$ kubectl get cm
NAME           DATA      AGE
key-config     0         1m

But the data is there, it's just a poor UI experience at the moment. You can verify that with:
kubectl get cm key-config -o json

Or you can use this friendly command to check that the ConfigMap can be mounted and the projected contents matches your original files:
kubectl run cm-test --image=busybox --rm --attach --restart=Never --overrides='{"spec":{"volumes":[{"name":"cm", "configMap":{"name":"key-config"}}], "containers":[{"name":"cm-test", "image":"busybox", "command":["sh","-c","md5sum /cm/*"], "volumeMounts":[{"name":"cm", "mountPath":"/cm"}]}]}}'


Q:

Looking for a material so I can make ABS parts with rubber grips and feet

Looking for something that offers a lot of friction in contact with human skin or when sitting on the surface of a table.
I was curious if any of the rubber/soft materials would be compatible with ABS so I could print them together using a dual-head setup?

A:

Ninjaflex dual-extrudes great with ABS. I've done a fair amount of NF/ABS dualstrusion. Frankly, any TPU will probably work, since molten polyurethane sticks to practically anything.
The main challenge is ooze control since TPUs tend to ooze a lot. You're going to want to use a printing temp on the low end of the range for the flexible filament, and use some sort of wiper wall structure.
Another issue you might run into is re-priming the flexible filament after an extended idle time. It helps to use a large purge structure to ensure the nozzle gets re-primed fully. Don't use an excessively large toolchange retraction distance -- this will make it more likely that the flexible filament jams during reprime.
The best way to accomplish the above will depend on your slicer. Simplify3D is a good choice since it has good dualstrusion wiper and purge functions. Other slicers can be made to work as well.


Q:

JQuery Dialog doesn't work

It's for 3 hours i try to work a JQuery Dialog.
My code is this and it is very simple:

        JQuery Dialog Test

content

JQuery works: if i write for example     $('#finestra').css('color','blue');   this works.
Whats is the problem? :(

A:

You have not loaded jQuery UI library. You need to simply add the relevant library and its CSS file.

$(document).ready(function() {
  $('#finestra').dialog();
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />

    JQuery Dialog Test

content


Q:

Using preg_replace and regex with varying formats

I have three types of strings that I encounter. My goal is to cycle through all of them and just get name.
page_1.name
page_2.name.text
page_1.name.something

The only way I can figure out doing this is to first remove the page_# with the following:
$remove_page = preg_replace("/(page_\d+\.)(\w+)/", "$2", $string);

Then remove the last bit like so:
$get_name = preg_replace("/(\w+)(\.\w+)/", "$1", $remove_page);

Is there a more efficient way to do this? This works, but I feel like I'm only slightly grasping the power of regex.

A:

You can use this regex:
preg_match('/(?<=page_\d\.)[^.]+/', $input, $matches);

(?<=page_\d\.) is a lookbehind that makes sure our match is preceded by page_ and a digit. [^.]+ will match 1 or more characters that are not DOT.
RegEx Demo
Otherwise split by DOT and take 1st element:
$arr = explode('.', $input);
$name = $arr[1];


Q:

Clearing/resetting displayed values. Clearing answer variables in Javascript/HTML. Clearing displayed output

I have created a simple Cost Estimator in HTML Javascript. It does a simple calculation and displays the answer. I do not know how to reset the answer output when pressing the Reset button.
Here is codepen : http://codepen.io/FredHair/pen/FgJAd
The reset button resets the form but I do not no how to reset answer. I know it because of how I have displayed the answer, but do not know the correct process to clear the output.
HTML:

Cost Estimator

 <form>
 <input type= "numbers" id="x" placeholder = "Length" />

 <input type= "numbers" id="y" placeholder = "Width"/>

  <input type= "numbers" id="z" placeholder = "Height"/>

  <select id="choice" >
    <option value = "1">option 1</option>
    <option value = "2">0ption 2</option>
    <option value = "3">option 3</option>
</select>

<input id= "est" type="button" value = "Estimate" onclick= "calculator()"/>
<input id= "reset" type="reset" value = "Reset"/>
</form>

 =

JS:
function calculator(){
    var x = Number(document.getElementById("x").value);
    var y = Number(document.getElementById("y").value);
    var z = Number(document.getElementById("z").value);
    var p = Number(30);
    var result;
 var calc = document.getElementById("choice").value
    switch(calc){
        case"1" : result = z * p;
    break;
        case"2" : result = x * p + 50;
    break;
        case"3" : result = x * p + 30;
    break;

}
document.getElementById("result").innerHTML = " =  £  " + result;
}

http://codepen.io/FredHair/pen/FgJAd
Any help is greatly appreciated.

A:

Add an event listener to your form's reset event:
// document.forms[0] assumes your form is the first in the DOM
document.forms[0].addEventListener('reset', function() {
    document.getElementById('result').innerHTML = '';
});


Q:

Dump TEB/PEB in immunitydbg

I am trying to learn actually how to get to the PEB inside of TEB. I have tried this with windbg but could not manage to dump the PEB with stuff like:
!peb

or
dt nt!_PEB_LDR_DATA

And others. But, I could not manage to get the PEB dumped. So also my favorite debugger is still immunitydbg. So, I was trying to get to the information using immunitydbg CLI. But the nearest thing I have managed to get to PEB is dumping the TEB.
d fs:[0]

So, I there anyhow someway inside of immunity do get the contents of TEB/PEB? I also tried to use the Ollysdbg PE Dump plugin but that only gave me another exe file with different contents. And also i am not sure if the PE Plugin does the right thing for me.

A:

Open the Memory Map window in OllyDbg/ImmunityDbg, scroll down to the bottom, and double click on the entry that contains Process Environment Block. This will open a dump of the PEB in OllyDbg/ImmunityDbg:

A:

alt + f1 d fs:[30] ollydbg 1.10  raw peb

with stolly plugin for 1.10 select the first byte in dump->right click->sructure
select _peb  from drop down box for decoded peb .
al+g fs:[30] in ollydbg 2.01 fully decoded _peb in dump / disasm window


Q:

Find all iFrames in HTML page and replace them

I'm wanting to use jQuery to find all iFrames in a page, then replace it's source.
I'm doing this from a chrome extension, so any way to replace it, then load the iframe (So that the iframe is active on the page view), is what I'm looking for.
Any help is appreciated.

A:

You can all instances of an element by calling a jquery selector on the element name:
$('iframe')

And you can set the attribute of any element with the jquery attr() method. To replace all the iframes on a page with google.com you would do this:
$('iframe').attr('src','http://google.com');

--Disclaimer: The following code is an example of something referenced in the comments and is not an anwser to the Original question:
This is how you would iterate each iframe and check it's width:
$('iframe').each(function(){
    var currentIframeWidth = $(this).width();
    //do something with width here
});


Q:

Pandas: select only the first row of a column

I have a problem with the pandas dataframe. I have this df:
       ID                     type
28030  LVE-188599             PPC
28031  LVE-188599             PPC
28032  LVE-188599             PPC
28033  LVE-188599       Affiliate
28034  LVE-188599             PPC
28035  LVE-188599             PPC
28036  LVE-188599             PPC

and I want to select only the unique values of the column "type" inside the same group of ID ( I want to obtain a dataframe with two columns as result):
       ID                     type
28030  LVE-188599             PPC
28033  LVE-188599       Affiliate
28034  LVE-188599             PPC

Do you know how can I do this?
I used to work with SAS and this can be easily solved doing a
data out;
set in;
by ID;
if first.type;
run;

Thanks!

A:

df.loc[(df.id != df.id.shift(1)) | (df.type != df.type.shift(1))]

it works!


Q:

Consistent drop in performance on SQL Server 2016 SP2

Recently upgraded from 2008R2 to 2016SP2. Have a slow process that I can't change. Application contacts the server back and forth constantly and runs tiny queries, including doing an update 30K+ times serially.
I've tried any suggested indexes, etc...to try to help since it's a sticking point for completing the upgrade to production. The new server is loaded with twice as many procs, double the memory, etc..
The interesting thing about the process is that in testing it, using the same process and parameters, every time the server is restarted, it runs fast, then each subsequent run is about 2 minutes slower. It steadies about about the 5th or 6th run, but it's this same pattern every time. I would expect it to get better as it stores the plans and reuses them, but it's consistently the same behavior. I know that the underlying process needs to be corrected, but I don't have any control over that atm, and I find the pattern very odd, since nothing else is running on the server.
Testing has consisted of running the process from the app several times after each change. Started in 2008 compatibility mode, reindexed and updated, stats, applied missing indexes based on cache info., updated to use current 2016 Query Optimizer and Cardinality Estimator, added Optimize for adhoc queries, moved to full 2016 compatibility mode. With each change, the same pattern ensues.
The baseline runs against a 2008DB and is consistently somewhere in the middle of the times I get for 2016. It is run from the same application and workstation.
VMs for the app server and DB server. No AGs yet. The queries are all trivial in time. There's tons, but the queries themselves aren't slowing down. Max memory around 64GBs (and nothing else is hitting this server right now),
*Update:
I'm sorting through some Extended Event logs now to see if I can pare down specifics as to what runs longer. Even sorting out the query hash = 0, each run executes 13602 executions (ad hoc sql statements + rpc completed), so it's a lengthy process. Was hoping for some insight as to why a SQL Server restart would have a 10 minute difference on the duration of the process since nothing else is running on this server. I would think a restart would make it slower the first few runs, but it's exactly the opposite. Even things like sp_setapp role are taking longer on subsequent runs.
Any ideas why I would have query hash plans all equal to "0" on queries over 20 secs? Is this telling me these are compilation timeout queries?

A:

Solved: Not sure it will help anyone else, but just in case it will, what I found was the serial nature of the process (one command per connection) was causing the process to send 143,000+ sp_setapprole calls during the process. This was bloating the TokenAndPermUserStore cache by 1GB each time it ran. This is why a restart of the service saw it run quickly and subsequent runs got slower as it took longer to search through the security cache. Long term fix is, of course, to have the process rewritten correctly with aggregate inserts and updates, but as a temporary solution, I have a job monitoring the size of the cache and flushing it with DBCC FREESYSTEMCACHE ('TokenAndPermUserStore'). This will add some IO to other calls, but sometimes we're forced to do what we can with the code we're given.


Q:

CUDA Thrust: Finding the index of the first element in a vector satisfying a predicate (e.g., zero or negative) [Matlab's syntax min(find(x<=0))]

I am attempting to find the the index of the first zero or negative value of an array using CUDA Thrust. The serial CPU code I am attempting to write using CUDA Thrust is the following:
for (int i = StartIndex; i <= ArrayLimitIndex; i++)
{
    if (Array[i] <= 0) { DesiredIndex = i; break; }
}

I am thinking that the easiest way to do this on the GPU will be using the find_if function within the Thrust library.
The array is already on the GPU and I am attempting to search for the index on this array using Thrust as such:
struct less_than_or_eq_zero
{
__host__ __device__
bool operator() (double x)
{
    return x <= 0;
}
};

thrust::device_vector<double>::iterator iter;
thrust::device_ptr<double> dev_ptr_Col46 = thrust::device_pointer_cast(dev_Col46);
iter = thrust::find_if(thrust::device, dev_ptr_Col46, dev_ptr_Col46 + size,less_than_or_eq_zero());

Now I would like to use the value of iter as an argument for my next kernel:
newKernel<<<size, 1>>>(*dev_array, iter)

where the newKernel definition is of the form:
__global__ void newKernel(double *dev_array, iter)
{
     int x = blockIdx.x;
     if(x <= iter)
     {
         //process data here...
     }
}

I know that the code I have here is incorrect and I have a few questions regarding the use of iter. First, iter is a device_vector. Is there any way I can make iter just one value and not a vector? Also, when I have executed the find_if how can I use the value of iter in my next kernel call?
Any help with this be greatly appreciated.
Thanks

A:

I'm summarizing the comments by talonmies and Jared Hoberock above as well as the answer by Sebastian Dressler in a fully compilable and executable example. The code calculates, by CUDA Thrust, the index of the first element of a vector satisfying a predicate (x<=0. in this case), I hope it will be helpful for future readers.
#include <thrust/device_vector.h>
#include <stdio.h>

struct less_than_or_eq_zero
{
    __host__ __device__ bool operator() (double x) { return x <= 0.; }
};

int main(void)
{
    int N = 6;

    thrust::device_vector<float> D(N);

    D[0] = 3.;
    D[1] = 2.3;
    D[2] = -1.3;
    D[3] = 0.;
    D[4] = 3.;
    D[5] = -44.;

    thrust::device_vector<float>::iterator iter1    = D.begin();
    thrust::device_vector<float>::iterator iter2    = thrust::find_if(D.begin(), D.begin() + N, less_than_or_eq_zero());
    int d = thrust::distance(iter1, iter2);

    printf("Index = %i\n",d);

    getchar();

    return 0;
}


Q:

If statement or while loop failing on me in php

I am fairly new to coding in php and have come accross a bit of a problem which I think is very simple. I am trying to capture the IP address of anybody that visits my website and stores that in my database. The code is as follows, I am not even sure the code will work but I do get the following error Parse error: syntax error, unexpected T_INC on line 29 which I will highlight in the code:
$ip = $_SERVER['HTTP_CLIENT_IP'];
                $query="SELECT * FROM ip";
                $result = mysql_query($query);
                $num = mysql_numrows($result);
                $i = 1;
                $found=false;
                while(($i - 1) < $num){
                    $selection = mysql_query("SELECT ip FROM ip WHERE id=$i");
                    $tip = mysql_fetch_assoc($selection);
                    if($tip == $ip){
                        $found = true;
                    }
                i++; //This is line 29
                }
                if($found == false){
                    $sql = "INSERT INTO `rowley_blog`.`ip` (`ip`) VALUES ('$ip');";
                    mysql_query($sql);
                    mysql_close();
                }

A:

You need to prefix variables with $, so it's $i++.


Q:

How to zip together lists of unequal length into a dictionary?

I have three lists.
import pandas as pd

author = ['mccoy.robert']
coauthors = [
    'hola.lubica', 'kundu.subiman', 'ntantu.ibula',
    'fletcher.peter', 'jain.tanvi', 'jindal.varun', 'bankston.paul',
    'di-maio.giuseppe', 'dickman.raymond-f-jun', 'holy.dusan',
    'slover.rebecca', 'curtis.douglas-w', 'duvall.paul-f', 'fogelgren.j-r',
    'hammer.s-t', 'haworth.r-c', 'lutzer.david-j', 'okuyama.akihiro',
    'pelant.jan', 'porter.jack-ray', 'raha.asit-baran', 'rubin.leonard-roy',
    'santoro.grazia', 'smith.jerome-c', 'todd.aaron-r'
]
frequency = [
    '10', '8', '6', '5', '3', '3', '2', '2', '2', '2', '2',
    '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'
]

I'd like to make these lists into a dataframe in which each row is the author paired with each coauthor and the frequency of collaborations.  Basically if I could zip these three lists together, with the list 'author' replicated over and over in each row, this would be great.
This seems like a fairly simple pandas task... but I'd love some help on it!

A:

You can do this with nested for loop, looping over the authors and the zipped coauthors and frequencies. Like so:
authors = ['mccoy.robert']
coauthors = [
    'hola.lubica', 'kundu.subiman', 'ntantu.ibula',
    'fletcher.peter', 'jain.tanvi', 'jindal.varun', 'bankston.paul',
    'di-maio.giuseppe', 'dickman.raymond-f-jun', 'holy.dusan',
    'slover.rebecca', 'curtis.douglas-w', 'duvall.paul-f', 'fogelgren.j-r',
    'hammer.s-t', 'haworth.r-c', 'lutzer.david-j', 'okuyama.akihiro',
    'pelant.jan', 'porter.jack-ray', 'raha.asit-baran', 'rubin.leonard-roy',
    'santoro.grazia', 'smith.jerome-c', 'todd.aaron-r'
]
frequencies = [
    '10', '8', '6', '5', '3', '3', '2', '2', '2', '2', '2',
    '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'
]

combined = []

for author in authors:
    for coauthor, frequency in zip(coauthors, frequencies):
        combined.append((author, coauthor, frequency))

With Output:
[
    ('mccoy.robert', 'hola.lubica', '10'), ('mccoy.robert', 'kundu.subiman', '8'), ('mccoy.robert', 'ntantu.ibula', '6'),
    ('mccoy.robert', 'fletcher.peter', '5'), ('mccoy.robert', 'jain.tanvi', '3'), ('mccoy.robert', 'jindal.varun', '3'),
    ('mccoy.robert', 'bankston.paul', '2'), ('mccoy.robert', 'di-maio.giuseppe', '2'), ('mccoy.robert', 'dickman.raymond-f-jun', '2'),
    ('mccoy.robert', 'holy.dusan', '2'), ('mccoy.robert', 'slover.rebecca', '2'), ('mccoy.robert', 'curtis.douglas-w', '1'),
    ('mccoy.robert', 'duvall.paul-f', '1'), ('mccoy.robert', 'fogelgren.j-r', '1'), ('mccoy.robert', 'hammer.s-t', '1'),
    ('mccoy.robert', 'haworth.r-c', '1'), ('mccoy.robert', 'lutzer.david-j', '1'), ('mccoy.robert', 'okuyama.akihiro', '1'),
    ('mccoy.robert', 'pelant.jan', '1'), ('mccoy.robert', 'porter.jack-ray', '1'), ('mccoy.robert', 'raha.asit-baran', '1'),
    ('mccoy.robert', 'rubin.leonard-roy', '1'), ('mccoy.robert', 'santoro.grazia', '1'), ('mccoy.robert', 'smith.jerome-c', '1'),
    ('mccoy.robert', 'todd.aaron-r', '1')
]


Q:

Re-tagging Activity - 2013

Given our community has been growing, and we seem to have a fairly active base, several of us thought now might be a good time to do some house cleaning on the site.
Given cleaning is a never ending task, we thought we'd set the bar low, to start, and take up a re-tagging effort on some of our more popular tags (by use). These were the tags that were selected, per this discussion in the U&L chatroom.
NOTE: users in that conversation: @Gilles, @derobert, @MichaelMrozek, @terdon, @Braiam, & @slm.
The Plan
The outcome of this discussion was to do the following 3 things.

List the tags we're going after
Rewrite their excerpts and wiki entries
Focus on re-tagging Q&A's covered by these tags

Step 1 - the tags
This was the list of tags that were deemed our targets.

command-line vs. shell
shell-script vs. shell + scripting
linux-kernel vs. linux + kernel

Step 2 - Cleaning up the excerpts + descriptions
This one should be reviewed and discussed. I'm thinking these could be reviewed either on this meta Q or in the chatroom prior. Once we have consensus, one of us can make the changes to the actual excerpts and description entries.
One thing to keep in mind when working on this part. The tags should likely start with the following phrases:

excerpt should be: "Use this for..."
the description can be: "This is...".

In general tags should be viewed as categories with which a question falls into, however keep in mind that ...

"tags describe the question's topic" view leads to the same result as the "tags describe the expert who can answer" view 99% of the time.

So tagging can be something of an art, at times. If you're not sure, it's best to leave it alone, and consult a quorum in the chatroom, rather than guess!
Above all else remember this: WWGT - What Would Gilles Tag    8-)
Step 3 - retagging effort
This step, was not discussed at length, so I'd suggest we get through the first 2 steps and once we've got excerpts + descriptions locked, we'll focus on how to go about re-tagging things.
Additional Information
I'm providing links to additional resources within the meta site related to tagging & re-tagging below. They're broken up into 2 sections. Past re-tagging efforts, and references on tagging.
Past re-tagging efforts

Splitting the ports tag
router, routing, route
Polysemy of the /scheduling tag
On the shell, shell-script, command-line and terminal tags

Tagging Reference Material

Shall tags refer to the solution, too?
Tags for variant-agnostic questions
On the shell, shell-script, command-line and terminal tags
Redundancy between sub-tags: linux, kernel, linux-kernel?
Let's clean up the GRUB tags

A:

Suggestion for shell:
Let's limit this one to things only about the shell itself. Probably for Bourne-inspired shells, or maybe even only POSIX shell. Description (at least the long description) would also mention the shell-specific tags (bash, zsh, ksh, …)

Configuring shell variables (PS1, etc.)
Configuring shell options (shopt, set)
Redirection syntax (how to pipe, not what to pipe to)
Keybindings [overlaps with readline, at least in some shells]
Shell built-ins
Shell language syntax (if, while, for, etc.)

IOW, if it's not appropriate for man 1 bash (or similar), this isn't the tag for you. For example:

NOT what options some random command takes (tag with that command)
NOT which command you should pipe to (maybe command-line?)
NOT some random error from a command you invoked (tag with that command)
NOT solving that *** STOP: 0x000000EA (… error that shows up with a blue background (try SuperUser).

This needs to be written better to become a tag wiki. Not going through the effort of writing well unless you all agree with the direction.


Q:

YARN jobs getting stuck in ACCEPTED state despite memory available

Cluster goes into deadlock state and stops allocating containers even when GBs of RAM and Vcores are available.
This was happening only when we start a lot of jobs in parallel most of which were Oozie jobs with many forked actions.

A:

After a lot of search and reading related questions and articles, we came across a property called maxAMShare for YARN job scheduler (we are using Fair Scheduler).
What it means?
Percentage of memory and vcores from user's queue share that can be allotted to Application Masters. Default value: 0.5 (50%). Source
How it caused the deadlock?
When we will start multiple oozie jobs in parallel, each oozie job and the forked actions require couple of ApplicationMaster containers to be allotted first for oozie launchers which then start the other containers to do the actual action task.
In our case, we were actually starting around 20-30 oozie jobs in parallel, each with close to 20 forked actions. And with each action requiring 2 ApplicationMasters, close to 800 containers were getting blocked only by the Oozie ApplicationMasters.
Due to this, we were hitting the 50% default maxAMShare limit for our user queue. And YARN was not allowing to create new ApplicationMasters to run the actual job.
Solution?

One instant suggestion could be to disable the check by setting this property to -1.0. But this is not recommended. You can again end up allocating all or most of the resources to AMs and the real job that will get done will be very less.
Other option (which we went ahead with) is to specify a separate queue for AMs in the oozie configuration and then set maxAMShare property to 1.0. This way you can control how much resources can be allocated to AMs without affecting the other jobs. Reference

<global>
    <configuration>
        <property>
            <name>oozie.launcher.mapred.job.queue.name</name>
            <value>root.users.oozie_am_queue</value>
        </property>
    </configuration>
</global>

Hope this will be a major time saver for people facing the same issue. There could be many others reasons for deadlock too which are already discussed in other questions on SO.


Q:

How would I get an intuative idea of what this transformation does to the unit square?

$$T(x,y)= (ye^x,2x)$$
I seem to think that the unit square is mapped to something that looks like

Would this be correct?
The way I thought about this would be to fix $y$ then "trace" $x$. Does anyone have any other ways of doing this?

A:

Let us consider that the graphics you have provided is in the $(X,Y)$ image plane (uppercase X,Y versus lowercase $x,y$ for the initial space $[0,1] \times [0,1]$).
The relationships describing the transformation
$$\tag{1} \cases{X=ye^x & (a) \\ Y=2x & (b)}$$
can be interpreted thus: we look for those $(X,Y)$ having a preimage $(x,y)$, i.e., being such that $\exists x,y \in [0,1]$ such that :
$$\tag{1} \cases{X=ye^x & (a) \\ Y=2x & (b)}$$
Let us (partially) inverse these relationships.
(1) is equivalent by taking the logarithm of relationship (1a):
$$\tag{2}\cases{\ln(X)=\ln(y)+\frac{Y}{2} & (a) \\ x=\frac{Y}{2} & (b)}$$
But condition $y \in [0,1]$ is equivalent to condition $\ln(y) \leq 0$.
Thus equation (2a) is equivalent to say that $\ln(X)<\frac{Y}{2}$.
Otherwise said, it means that all the region described by inequality:
$$Y>2 \ln(X)$$
is convenient.
But we must take into account the constraint brought by (2b): $0 \leq Y \leq 2$.
We have thus proved that the region you have found is the good locus (see picture below with the images of $2000$ random points in $[0,1] \times [0,1]$.

Remark: A completly different approach would have been to consider that the different constituents of the boundary of the image are the images of the four sides of the initial square.
For example, the image of the vertical side along the $y$ axis, that can be parameterized as the set of points $(x,y)=(0,t), \ \ t \in [0,1]$ is the set of points $(te^0,2 \times 0)=(t,0)$, i.e, is the horizontal side. Whereas the upper horizontal side which is the set of points $(x,y)=(t,1), \ \ t \in [0,1]$ is mapped onto the set of points $(1 \times e^t,2t)$ which is a parametric representation of the arc of logarithm curve.
A drawback of this method is that the region enclosed by the frontier curve is not necessarily mapped onto the region delimited by the image of the frontier. This has not happened here, but for the sake of rigor, it is better to work on inequalities and equivalent inequalities, as we have done in the first part.


Q:

How can I implement a fixed size hashmap?

I want to implement a hashmap, but I am not allowed to let it expand. Since I do know that I need to store at most N elements, I could pre-allocate an array with N elements for each bucket of my hashtable, so that I can still store N elements in the worst case where all keys are hashed on the same bucket. But the elements that I need to store are rather big, so for large N this is very inefficient use of memory.
Is it possible to implement a hashmap efficiently (in terms of memory) with a fixed amount of memory, e.g. by implementing a smart hashing function?
(P.S.: the key is an unsigned 32-bit integer, and I have no prior knowledge about the keys except that the key values I will receive are in a fairly small subset of the range, and this subset moves very slowly up in the range.)

I now have an implementation where I have two arrays of length N, one with the elements, and one with the keys that correspond to the element at position i in both arrays. I use the modulo operation as a hash function to determine where the element should be inserted/present, and a linear probe to find the nearest empty spot in case of a collision. I think this is of complexity O(N), and I think this will work reasonably fast for the amounts of data that I am expecting. I asked the question to see if it can be done better.

A:

For hashing, you could use following snippet, which btw Linux kernel uses to hash PIDs:
unsigned long hash_long(unsigned long val, unsigned int bits)
{
unsigned long hash = val * 0x9e370001UL;
return hash >> (32 - bits);
}

The magic number 0x9e370001UL is a large prime number. Here's an extract from Understanding Linux Kernel explaining the magic number:

You might wonder where the 0x9e370001 constant (= 2,654,404,609) comes
  from.  This hash function is based on a multiplication of the index by
  a suitable  large number, so that the result overflows and the value
  remaining in the  32-bit variable can be considered as the result of a
  modulus operation. Knuth  suggested that good results are obtained
  when the large multiplier is a prime  approximately in golden ratio to
  232 (32 bit being the size of the 80×86’s  registers). Now,
  2,654,404,609 is a prime near to that can also be easily  multiplied
  by additions and bit shifts, because it is  equal to 2^31 + 2^29 -
  2^25 + 2^22 - 2^19 - 2^16 + 1.

The right shift hash >> (32 - bits); just says keep bits number of bits in the hash value. Other bits will be zeroed out. In your case, bits will be determined by the limit N. For this to work as it is, N needs to be such that all its bits after its most significant set bit are set too, e.g. for N = 7 (where last three bits are all set and all other bits are zero) and bits will be 3. Or N = 63 where the least significant six bits are all set and all other bits are zero. Here bits will be 6.
Value returned by hash_long function will form index into your array.
Handling Collisions
To handle collisions, keep just one array but make it an array of linked list nodes. So every element in the array points to a linked list. When there is a collision, just append the new entry to the end of the linked list corresponding to that slot in your array.
Handling Collisions (Update)
If you cannot allocate new memory dynamically then the solution you posted seems fine, although I'm not sure what's the purpose of array which contains just keys (shouldn't a key be a member of the element that it belongs to?). Here is suggestion towards your solution:
To have a 1-D array means that in case of a collision, we perform linear probe both when inserting as well as when retrieving. An alternative would be to have a 2-D array where inner array acts as a linked list. We will need to index of last element inserted in each of the inner arrays. The down side compared to 1-D array is that if too many collisions happen on the same index then we may run out of space in one of the inner arrays, unless we make each inner array of length N as well, which will lead to a lot of wasted space. The advantage is that when inserting, we don't need to perform a linear probe. We just check the index of last element in the inner array and increment it by one to get next slot to insert the new element in.


Q:

What is $(z_2-z_3)^2 = 4(z_3-z_1)(z_1-z_2) \sin^2\frac{\alpha}{2}$

I saw this formula used in quite a few places, with the following text:

If $A,B,C$ are the points $z_1,z_2,z_3$ and the angles $B$ and $C$ are each $\pi$ - $\frac{\alpha}{2}$ then
$$
(z_2-z_3)^2 = 4(z_3-z_1)(z_1-z_2) \sin^2\frac{\alpha}{2}
$$

Does anyone know what this means? Does it actually mean anything?
Thank you.
PS: I searched all over google for this formula, haven't found anything interesting.
PS2: I have no idea what tags I should put, help would be appreciated.
Trying to answer
Since angles B and C are both equal to $\pi$ - $\frac{\alpha}{2}$ this means that
angle A = 2$\pi$ - 2 ($\pi - \frac{\alpha}{2}$)
A = $\alpha$
After this, I'll use the Law of sines of a triangle, and tranform $sin (\pi - \frac{\alpha}{2}) = (-1)(cos(\frac{\alpha}{2})) $ :
$\frac{|z2-z3|}{\sin \alpha}  = \frac{|z1-z3|}{(cos(\frac{\alpha}{2})} = \frac{|z1-z2|}{(cos(\frac{\alpha}{2})}$
This is as far as I got. Any ideas on how to proceed ?

A:

Here is the picture you want to draw.

Now, the rest is not hard, but I must say that the use of $z$ variables throws you off, as I was expecting a complex variable result. In fact, as stated the problem is not right and should be interpreted in vector terms.
Also note that we know that this must be the sides AB and AC are equal in length.Let us write it as: $|\bf{r}_3-\bf{r}_2|^2 =4|\bf{r}_2-\bf{r}_1||\bf{r}_3-\bf{r}_1|$ $\sin^2{\alpha/2}$.
Since AB and AC are equal in length $|\bf{r}_3-\bf{r}_1|=|\bf{r}_2-\bf{r}_1|$.
For each one of the two right triangles shown we have hypotenuse $|\bf{r}_3-\bf{r}_1|$, and opposite side $(1/2)|\bf{r}_3-\bf{r}_2|$ and angle $\alpha/2$. Then:
$$ (1/2)|\bf{r}_3-\bf{r}_2|=|\bf{r}_3-\bf{r}_1|\sin\alpha/2$$.
Square this and rearrange:
$$ |\bf{r}_3-\bf{r}_2|^2=4\sin^2\alpha/2|\bf{r}_3-\bf{r}_1|^2$$
And substitute once the alternative expression for the hypotenuse:
$$ |\bf{r}_3-\bf{r}_2|^2=4\sin^2\alpha/2|\bf{r}_3-\bf{r}_1||\bf{r}_2-\bf{r}_1|$$.


Q:

How to thermodynamically understand process of burning a piece of coal?

Let's imagine that I have a match in hand and nugget of coal on my desk. Then I light up the match and place it for few seconds near the coal so a tiny piece of nugget catches fire.
Then another piece catches fire, then another and soon all the nugget is burnt down.
How did it happen? I gave the nugget just enough heat to burn the first piece. Where does come energy to burn the rest of nugget from?

A:

It is called combustion, and it happens in materials which have a lower energy content when their component molecules join with the oxygen in the atmosphere, than when  in a solid/liquid structure. When energy is given to start the fire the piece of coal burns  and releases energy  with excess enough to sustain the reaction and leave heat energy for use.

Combustion is a high-temperature exothermic chemical reaction between a fuel and an oxidant, usually atmospheric oxygen, that produces oxidized, often gaseous products, in a mixture termed as smoke.


Q:

Как запретить вводить числа

Как запретить вводить числа?
Например:
name = input('Введите имя')
number = input('Введите номер')

Чтобы где переменная name там запретить вводить числа, а где переменная number запретить вводить слова.

A:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import re

i=False
while not i: # Цикл будет выполняться пока i не станет True
    name = input('Введите имя ')
    if re.findall(r'\d', name)==[]: # re.findall(r'\d', name) вернет список из цифр которые используються в значении переменой name, если цифры не использовались вернеться пустой список
        i=True
        print("Данные введены верно")
    else: print("Данные введены неверно, попробуйте еще раз")
i=False
while not i:
    number = input('Введите номер ')
    if re.findall(r'\D', number)==[]: # re.findall(r'\D', name) вернет список из букв которые используються в значении переменой number, если цифры не использовались вернеться пустой список
        i=True
        print("Данные введены верно")
    else: print("Данные введены неверно, попробуйте еще раз")