text:
Q: Is this the correct hypothesis function for logistic regression? I was reading a popular article on adversarial training.  https://adversarial-ml-tutorial.org/linear_models/
It says,
In this case, rather than use multi-class cross entropy loss, we'll be adopting the more common approach and using the binary cross entropy, or logistic loss. In this setting, we have our hypothesis function, $h_\theta(x) = w^Tx + b$.
Is the hypothesis in logistic regression simply a linear function?
I feel like this violates the definition of hypothesis, which is a function that maps to the space containing the labels. Since the labels are $\{\pm 1\}$ for binary classification, therefore it should make sense to take the hypothesis function as $h_\theta(x) = \text{sigmoid}(w^Tx + b)$ or even better, $h_\theta(x) = \text{sign}(\text{sigmoid}(w^Tx + b) - 0.5)$.
Can someone chime in on whether the choice of hypothesis is correct in the article?

See Shwartz, Ben David Understanding Machine Learning


text:
Q: If I beat the Wall of Flesh does it place ALL worlds I have into hardmode? Does defeating the Wall of Flesh make every world I've created go into Hardmode?
If I create a world after defeating the WOF, will it be created in Hardmode?

A: No.  Hardmode is per world.  When hardmode starts after you defeat the Wall of Flesh, it will only affect the current world, and doesn't affect any others you may have saved or created.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I add custom html and styles using Vue Directives? Is it possible? The question:
How can I add custom html and styles using Vue Directives? Is it possible?
Or I have to use components?
Or using a directive to add a custom component on top of the parent component?
Description:
I'm using VueJs + splitpanes to make some resizable panes like this:
<splitpanes class="default-theme h-100">
  <pane min-size="30" size="30">
    <splitpanes horizontal>
      <pane min-size="20">
        <skyroom-users></skyroom-users>
      </pane>
      <pane min-size="30">
        <skyroom-chat></skyroom-chat>
      </pane>
    </splitpanes>
  </pane>
  <pane size="70">
    <splitpanes horizontal>
      <pane size="30">
        <skyroom-whiteboard></skyroom-whiteboard>
      </pane>
      <pane size="70">
        <skyroom-whiteboard2></skyroom-whiteboard2>
      </pane>
    </splitpanes>
  </pane>
</splitpanes>

- Now I want to extend this plugin and add window controls on top of each pane

Can I use direvctives? For example like this code:
<pane v-pane-coltrols min-size="20">
  <skyroom-users></skyroom-users>
</pane>
<pane v-pane-coltrols min-size="30">
  <skyroom-chat></skyroom-chat>
</pane>


text:
Q: Error when using `pst-circ` The code is shown as follows:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{pst-circ}

\begin{document}
  \begin{center}
    \begin{pspicture}[showgrid=true](3,2)
      \pnodes(0,1){A}(3,1){B}
      \resistor(A)(B){$R$}
    \end{pspicture}
  \end{center}
\end{document}
\usepackage{pst-circ}

and it shows "Undefined control sequence" at line 9 and 10.
How can I solve this?


text:
Q: how to get a value from array in bash In the below i am checking the exit status , if it is not zero(which is a failure) i am displaying it by echo statment
while read -r record
 reccount=$((reccount + 1 ))
/usr/bin/java -jar NSGalinaMail.jar "$email_text"  "$email_subject" "$contact_email" "billingdept@ups.com" $lang  $cny_cd $MY_WORK/"Notify_$2.pdf"
        if [ $? -ne 0 ]; then
            emailCountFailure[$reccount-1]="Failure: Email to $contact_email for $ref_nr"
            echo "$emailCountFailure"
        fi
        echo "record_count=$reccount" >> $MY_WORK/"raw_data_$2"
        echo "emailCountFailure=$emailCountFailure" >> $MY_WORK/"raw_data_$2"
done < fileName ## a file with 10 records##

what ia m expecting is at least a 0 value if there is no failure, but it displays blank
emailCountFailure=

any solution for this? Thank you

A: at least you forgot while ... ; do.
Here is my version doing what you may expect:
#!/bin/bash

# proposed
set -e
set -u
# disable in production code
#set -v
# disable in production code
set -x

reccount=0
declare -a emailCountFailure
while read -r record; do
    reccount=$((reccount + 1 ))

    # do not exit on non-zero status
    set +e
    # execute something
    perl -Mstrict -Mwarnings -E "say 1/$record" > /dev/null 2>&1
    # store exit code as `set` will exit, too
    _rc=$?
    # re-enable exit on non-zero status
    set -e

    idx=$[$reccount-1]
    if [ $_rc -eq 0 ]; then
        # I don't know if you need this
        emailCountFailure[$idx]=''
    else
        emailCountFailure[$idx]="Failure: division by $record"
        # do what you need
    fi
done < lines

echo "record_count=$reccount"
echo "emailCountFailure=$emailCountFailure"

The file lines contains just lines of numbers and chokes on 0.
Hope that helps.


text:
Q: Apache Virtual Hosts Override httpd.conf I'm confused as to how vhosts in Apache 2.4 work. I have enabled virtual hosts, and I have two websites set up on my server. I think that this means the default host (/var/www/html) doesn't work anymore. But which parts of httpd.conf are overrided by virtual hosts? Do the includes such as "conf.d" that are in httpd.conf apply to the virtual hosts or do I have to manually assign those? I have in httpd.conf a line which assigns a special header to RemoteIPHeader, do I have to include this line in each of my virtual host .conf files? Please help me understand how httpd.conf works when virtual hosts are enabled. Thanks!

A: Every Directive lists the context in which it is valid. In other words where it is allowed to be used.
The context can be any combination of:

s - server config This means that the directive may be used in the server
  configuration files (e.g., httpd.conf), but not within any
  <VirtualHost> or <Directory> containers. It is not allowed in
  .htaccess files at all.
v - virtual host This context means that the
  directive may appear inside <VirtualHost> containers in the server
  configuration files.
d - directory A directive marked as being valid in
  this context may be used inside <Directory>, <Location>, <Files>,
  <If>, and <Proxy> containers in the server configuration files,
  subject to the restrictions outlined in Configuration Sections.
h - .htaccess If a directive is valid in this context, it means that it
  can appear inside per-directory .htaccess files. It may not be
  processed, though depending upon the overrides currently active.

If a directive is used multiple times, both the context, the scope and the order the Directives are encountered determines which directive will have precedence.
With regards to VirtualHost entries the directives used there will override the default settings, but will only apply for that virtual host entry.
With name based virtual hosting the first <VirtualHost addr:port> becomes the default which will serve all requests that don't match any explicitly defined ServerName/ServerAlias names used in the other VirtualHost entries.


text:
Q: Escaping space in string - external command I'm trying to run an external command (wdsutil.exe) using PowerShell:
$parsePref = "--%"
$imageName = "Windows 7 Image"

& wdsutil.exe $parsePref "/Add-Image /Name:$($imageName) /FileName:WDSBoot.wim ..."

Returns the error: An invalid parameter (7) was specified for command /add-image
Changing $imageName to "Windows7Image" works (no spaces..) - but this is not desirable.
How can I handle spaces in the $imageName variable?

A: Enclose the argument in quotes:
& wdsutil.exe $parsePref "/Add-Image /Name:""$($imageName)"" /FileName:WDSBoot.wim ..."


text:
Q: unable to retrieve the visualforce page tab I want to retrieve and deploy the custom visualforce tab page from salesforce environment. I tried so far the following piece of the block in package.xml but could not retrieve the custom visualforce page.
 <types>
    <members>VOIP_Settings</members>
    <name>CustomTab</name>
</types>

This block allows to fetch custom tab but it seems it is not fetching the custom visualforce page tab. I tried to hunt a lot but could not find a way to retrieve the visualforce custom tab from the org.

A: You need to retrieve it like this:
<types>
  <members>TabName.tab</members>
  <name>CustomTab</name>
</types>

Documentation


text:
Q: "Urlencoded payload size is bigger than allowed (default: 256kB)" I have a small Rust program that formats MySQL queries, but I found it failing on bigger queries, returning

Urlencoded payload size is bigger than allowed (default: 256kB)

I'm using actix web, which looks like this
use actix_web::{
    web, App, HttpResponse, HttpServer, Result,
};

#[derive(Deserialize)]
pub struct MyParams {
    q: String,
}

fn index(params: web::Form<MyParams>) -> Result<HttpResponse> {
    Ok(HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body("test"))
        // .body(mysql_format2(&params.q[..])))
}

fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            web::resource("/")
                .route(web::post().to(index))
        )
    })
    .bind("127.0.0.1:48627")?
    .run()
}

And the PHP script calling this looks like
$this->FormattedMySQL = str_repeat("make a big query ", 1024*256);

$query =  http_build_query([
    'q' => $this->FormattedMySQL,
]);

// if I change this to 16385 (+1)
// then it breaks and returns that error
$query = substr($query, 0, 16384);

if ($this->FormatMySQL && strlen($query) <= 262144) {
    try {
        $this->VerbosePrint('formatting');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, MYSQL_FORMAT_ENDPOINT);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        $this->FormattedMySQL = curl_exec($ch);
        curl_close($ch);
    } catch (Exception $_) { }
}

What am I missing, or why does this seem to be throwing this error for 16kB instead of 256kB?
I see that it's also possible to set the Payload config but I'm not totally sure how/where to apply this in my existing code.

A: The quick answer is that there is a second config (FormConfig), which is what you're hitting your head against. It is unclear as it returns the same error type as PayloadConfig (there is a reason for that, which I will explain in the "longer version")
Change your actix server definition to this to change it to, say, 256kb:
HttpServer::new(|| {
    App::new().service(
        web::resource("/")
            .route(web::post()
                .to(index)
            )
            .data(web::Form::<MyParams>::configure(|cfg| cfg.limit(256 * 1024)))
    )
})
.bind("127.0.0.1:48627")?
.run()

You will also need to import actix_web::FromRequest, as this is where the object type change from a request to a urlencoded form happens and where the configure() method lives.
Now, for the explanation!
Actix, much like other frameworks, has multiple layers of limits in place. You've found one of them, this is another.
The one you found prevents denial of service through memory exhaustion (i.e. somebody sending a deliberately large payload to oom your server, as it will have to store the body somewhere to process). It governs the entire payload of the request.
The one you are hitting against is a much smaller limitation placed on each individual field, and it exists to prevent a different kind of exhaustion attack. Suppose your attacker knows you're parsing the input with something; let's pretend it's JSON. By sending an arbitrarily large and convoluted JSON, they can effectively lock your server down while processing a single request. Small data input, very large consequences.
For that reason, the two limits are typically independent of each other, and allow you to fine-tune the restrictions based on your requirements. Lots of small fields? No problem. One huge chunk? Also not a problem.
The effect of the FormConfig limit is located here in case you want to see the code itself. As the type return is the same as that of the PayloadConfig limit ( (the Overflow variant of this struct)[https://docs.rs/actix-web/1.0.7/actix_web/error/enum.UrlencodedError.html]), the message is unclear and you end up scratching your head as a result.
The main aim of the error being "similar" was, I think, to prevent the server from indicating to a potential attacker which limit they hit, and it seems to be what they had in mind. The user-facing error description is the problem, and that's something that may get adjusted with a well-placed PR.


text:
Q: How to append data from one CSV to another using Export-CSV I have a script like the following:
$in_file = "C:\Data\Need-Info.csv"
$out_file = "C:\Data\Need-Info_Updated.csv"
$list = Import-Csv $in_file
ForEach ( $user in $list ) {
    $zID = $user.zID
    ForEach-Object {
        Get-QADUser -Service 'domain.local' -SearchRoot 'OU=Users,DC=domain,DC=local' -SizeLimit 75000 -LdapFilter "(&(objectCategory=person)(objectClass=user)(PersonzID=$zID))" | Select-Object DisplayName,samAccountName,@{Name="zID";expression={$zID}} | Export-Csv $out_file -NoTypeInformation -Force
    }
}

However, I am not able to get it to output all of the results to the $out_file since it does not seem to append the data to the csv file.
Is there a way to make this append the data to a file?

A: -append is broken in PowerShell v2.0. You can use Dmitry Sotikovs workaround instead: http://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/
I would however recommend manojlds excellent solution!

A: As Sune mentioned, PowerShell v3's Export-Csv has an Append flag but no character encoding protection. manojlds is correct, since your code is writing all new data to a new CSV file.
Meanwhile, you can append data to a CSV by:

*

*Convert the objects to CSV with ConvertTo-Csv

*Strip the header —and type information if necessary— and collect the
CSV data only

*Append the new CSV data to the CSV file through Add-Content or
Out-File, be sure to use same character encoding

Here is a sample:
1..3 | ForEach-Object {
 New-Object PSObject -Property @{Number = $_; Cubed = $_ * $_ * $_}
} | Export-Csv -Path .\NumTest.csv -NoTypeInformation -Encoding UTF8

# create new data
$newData = 4..5 | ForEach-Object {
 New-Object PSObject -Property @{Number = $_; Cubed = $_ * $_ * $_}
} | ConvertTo-Csv -NoTypeInformation

# strip header (1st element) by assigning it to Null and collect new data
$null, $justData = $newData

# append just the new data
Add-Content -Path .\NumTest.csv -Value $justData -Encoding UTF8

# create more new data, strip header and collect just data
$null, $data = 6..9 | ForEach-Object {
 New-Object PSObject -Property @{Number = $_; Cubed = $_ * $_ * $_}
} | ConvertTo-Csv -NoTypeInformation

# append the new data
Add-Content -Path .\NumTest.csv -Value $data -Encoding UTF8

# verify
Import-Csv .\NumTest.csv

# clean up
Remove-Item .\NumTest.csv

A: After version 3 you can use:
Export-Csv $out_file -append -notypeinformation -encoding "unicode"

A: Convert the foreach loop into a foreach-object, and move the export-csv to outside the outer foreach object so that you can pipe all the objects to the export-csv.
Something like this (untested):
$list | ForEach {
    $zID = $_.zID
    ForEach-Object {
        Get-QADUser -Service 'domain.local' -SearchRoot 'OU=Users,DC=domain,DC=local' -SizeLimit 75000 -LdapFilter "(&(objectCategory=person)(objectClass=user)(PersonzID=$zID))" | Select-Object DisplayName,samAccountName,@{Name="zID";expression={$zID}}
    }
} | Export-Csv $out_file -NoTypeInformation -Force


text:
Q: useEffect is not invoking more then once based on the dependency I am making an expense tracker. I am trying to change the "total" amount everytime "totalIncome" and "totalExpense" is passed to the useEffect as dependency from the props. But the useEffect invoke only once.
const Main = ({ getData, totalIncome, totalExpense }) => {
  const [total, setTotal] = useState(parseInt(0))
  const [type, setType] = useState('income')
  const [date, setDate] = useState('')
  const [amount, setAmount] = useState('')
  const [category, setCategory] = useState('Rent')
  const [income, setIncome] = useState('')
  const [id, setId] = useState(Date.now())
    const changeType = (e) =>{
    setType(e.target.value)
  }

  const handleDate = (e) =>{
    setDate(e.target.value)
  }

  const handleAmount = (e) =>{
    setAmount(parseInt(e.target.value))
  }

  const handleCategory = (e) =>{
    setCategory(e.target.value)
  }

  const handleIncome = (e) =>{
    setIncome(e.target.value)
  }

  const handleSubmit = (e) =>{
       e.preventDefault()
       setId(Date.now())
       getData({total, type, date, amount, category , income, id})

       type === 'income' ? setTotal(parseInt(total + amount)) : setTotal(parseInt(total - amount))
       setAmount('')
       setIncome('')
       setDate('')
  }

  useEffect(()=>{
    if(!category){
      setCategory('Rent')
    }
  }, [category])

  useEffect(() => {
    setTotal(prev => prev + totalExpense)
  }, [totalExpense]);

  useEffect(() => {
    setTotal(prev => prev - totalIncome)
  }, [totalIncome]);

  return (

Expense Tracker

{total >= 0 ? Total Balance: ${total} : Your debt: ${total}}

        <form className={main.form} onSubmit={handleSubmit}>

                     Type:
                     <select id='type' name='type' value={type} onChange={changeType} >
                        <option value="expense">Expense</option>
                        <option value="income">Income</option>
                     </select>

                    {type === 'income' && (

                         Income:
                         <input type='text' value={income} onChange={handleIncome}/>

                    )}
                    {type === 'expense' && (

                         Category:
                         <select onChange={handleCategory}>
                            <option value='Rent'>Rent</option>
                            <option value='Food'>Food</option>
                            <option value='Transport'>Transport</option>
                            <option value='Health'>Health</option>
                            <option value='Utility'>Utility</option>
                            <option value='Other'>Other</option>
                         </select>

                    )}

            { /*
              Amount and date section
             */}

                    Amount:
                    <input type="number" value={amount} onChange={handleAmount} required/>

                    Date:
                    <input type="date" value={date} onChange={handleDate} required/>

            <button type='submit' className={main.create}>CREATE</button>
        </form>

  )
}

export default Main

How can i get the "total" amount change everytime the useEffect gets an update in the dependency ?

A: The useEffect hook only runs when the dependency array changes. If the dependency array contains numbers, then the number has to change for the hook to re-run. It will not re-run if the same numbers are passed in the following update.
Moreover, using the useEffect hook to change state based on props passed to it leads to very fragile components. I suggest that you calculate the total outside of this component and pass it into this component only for displaying. Alternatively, you can change total into a normal variable which will be recalculated on every render.
const Main = ({ getData, totalIncome, totalExpense }) => {
    ...
    const total = totalIncome - totalExpense;
    ...
}


text:
Q: Alter values in a column using a foreach before databind gridview i have written this much ...but how i assign the encryptedstatusid to the listDTO for databind?
protected void Page_Load(object sender, EventArgs e)
{
   List<DTO> listDto;
   IApplication engine;

   try
   {
      engine = new Engine();
      listDto = engine.ReadHistory(Session["UserID"].ToString());

      foreach (DTO iterDTO in listDto)
      {
         iterDTO.EncryptedStatusId = Triple.Encrypt(iterDTO.StatusId.ToString());

         //how i assign the encryptedstatusid to the listDTO for databind?????????????

      }

      this.dvHistory.DataSource = listDto;
      this.dvHistory.DataBind();

   }
   catch (Exception )
   {
      throw ;
   }
   finally
   {
      engine = null;
   }
}

Problem is i m getting the encryttedstatusid to the iterDTO , but the satasource is a list , i want to assign encry
pted status id to the listDto, then only it will show in grid

A: I think you should use another list to do this as an existing list can't be updated while iterating. Refer the following code:
  engine = new Engine();
  listDto = engine.ReadHistory(Session["UserID"].ToString());

  List<DTO> listDtoNew=new List<DTO>();

  foreach (DTO iterDTO in listDto)
  {
     iterDTO.EncryptedStatusId = Triple.Encrypt(iterDTO.StatusId.ToString());

     listDtoNew.add(iterDTO);

  }

  this.dvHistory.DataSource = listDtoNew;
  this.dvHistory.DataBind();

Hope this helps..


text:
Q: The faster way to do matrix multiplication between a matrix and a diagonal matrix? I am coding a computational package in python using numpy, in the package, I would do the matrix multiplication between an arbitrary large square matrix (e.g of size 100*100) and a diagonal matrix of same size frequently.
I have an O(n^2) method, but I think that further improvement could be made.
"""
A is of size 100*100
B is a diagonal matrix
want to do np.dot(A,B) quickly
"""
A=np.random.rand(100,100)
diag_elements=np.random.rand(100)
B=np.diag(diag_elements)

answer1= np.dot(A,B) ###O(n^3) method, quite slow

C=np.zeros((100,100))
C=C+diag_elements
answer2=np.multiply(A,C) ##O(n^2) method, 3times faster for n=100

The anwer2 is O(n^2) but I think it's not good enough, because the operation C+=diag_elements are wasting 1/3 time and could be avoided possibly.
I expect that some numpy function could do the matrix multiplication more elegently and faster. Could someone help me out?

A: Why don't you simply multiply A by the diagonal?
answer3 = np.multiply(A,diag_elements)


text:
Q: Register new PHP Handler clipath I need to install php 6.5 for an old project.
I register the new Handler in Plesk:
/usr/local/psa/bin/php_handler --add -id 6.5.6 -displayname 6.5.6 -path /usr/local/php65/bin/php-cgi -phpini /usr/local/php65/php.ini -type fastcgi

And I get this error message:
Required option -clipath is not set

A search provides no information about -clipath.

A: You are trying to use php on Plesk. You should be asking your question in Plesk's support forums or Plesk Support
The answer could be:
/usr/local/psa/bin/php_handler --add -id 6.5.6 -displayname 6.5.6 -path /usr/local/php65/bin/php-cgi -phpini /usr/local/php65/php.ini -type cgi -clipath /usr/local/php65/bin/php

If not ask Plesk support: What is my path to the PHP binary?
They are going to want to know if you are using Plesk Onyx for Linux or Plesk Obsidian for Linux.
Plesk PHP Management

*

*Installing PHP

*Configuring PHP Handlers

*PHP Extensions and Settings


text:
Q: Remove some default created fallback routes In CakePHP 3 the default behavour is DashedRoutes, which I am happy with. However, in some instances, I want to replace the routes with my own custom routes and remove the default created routes. My routes file looks like this:
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;

Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    $routes->applyMiddleware('csrf');

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    $routes->connect('/register', ['controller' => 'Users', 'action' => 'register']);
    $routes->connect('/login', ['controller' => 'Users', 'action' => 'login']);
    $routes->connect('/logout', ['controller' => 'Users', 'action' => 'logout']);

    $routes->fallbacks(DashedRoute::class);
});

In this case, I want the following routes to not work and basically return a 404 error:
/users/login
/users/logout
/users/register

How would I 'disconnect' these routes?

A: You probably can just set another route for /users/* that goes to a 404-redirect function, basically adding this to the route:
$routes->connect(
    '/users/*',
    ['controller' => 'Users', 'action' => 'serve404']
);

And then this to the UsersController (or if you want AppController for later reuse):
public function serve404(){
    throw NotFoundException();
}


text:
Q: The buttons in a repeat don't hide/show after refreshing the panel the repeat is in? I have a repeat that has buttons embedded in it.  The repeat is in a panel.  When the user clicks a button the button should hide/show (I partial refresh the panel).  The repeat is tied to a Domino view and I see the other values that I from that view get updated in the repeat, so, it does not seem like a view index issue (I refresh the view index in my code.)
If I use context.reloadPage() in my button onclick code then the buttons will hide/show like they should, but, that seems like I am using a sledge hammer!  Any suggestions on how to get the buttons to recompute the visible property when the panel that holds the repeat is rendered?  Another strange thing is that the visible property gets computed three times whenever I refresh the panel that holds the repeat.
thanks, Howard

A: I think your looking for
getComponent("<id>").setRendered(true / false);

A: Hi For Repeat control's entry is used to make our head hard. Because handling the entry by SSJS, we can get the value and set the value. But rendering part, id of the repeating component are same for all. So if we try to give reder as false. It hides all of our repeating component.
Try to use the following., [Put this in button onclick, and see the value of below]
var entryValue= getComponent("repeat1").getChildren().get(0).getValue()

getComponent("inputText1").setValue(entryValue)

But in client side we can easily handle. Because the id of the DOM object is unique for all repeating component.
var id1="view:_id1:repeat2:"+'2'+":button1"
document.getElementById(id1).style.display="none"

This will hide the third entry of your repeat control component.
Please see the post, You may get better idea

A: Found a solution.  My original solution was getting values from the repeat rows (using the collection object, which was a viewentrycollection and using getColumnValues) to compute the rendered property for the buttons.
Instead, I created a viewScope variable (a Vector) that holds the state of the buttons (which set of buttons to show).  This gets populated in the beforePageLoad event of the page.
The button onclick code updates this viewScope variable after performing its processing.  All works very nice now.  I guess it was something in the JSF lifecycle that kept the buttons from being properly updated.  Using the viewScope variable works fine.

A: With addition to what Ramkumar said, you can use the index variable in the repeat control to identify each and every occurrences inside the repeat control. You will get more idea, if you inspect with element from firefox[You might need firebug].  Usually the field mentioned inside a repeat control itself can be considered as an array


text:
Q: Creating File Directory from Worksheets Information I am trying to make a script to automatically create a file directory from information on forms I have created in excel.
What the file structure will look like

What the form looks like

I have a script that will create the file directory after i extract the information. I just need help with the script that will extract the information and copy it to column A on my File Directory sheet. A9 of the form will always be the name of the folder and sub folders will either be product data, shop drawings, samples, warranties, or material certificates. not all forms will have all of them though.
My thought would be to use a if function if the sheet has product data it would place A9/productdata to file directory. I need it to do this for each sheet in the workbook.
Sub FileDirectory()

    Dim ws As Worksheet
    Application.ScreenUpdating = False
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Name <> "File Directory" Then
            ws.Range("A9").Copy Sheets("File Directory").Cells(Rows.Count, "A").End(xlUp).Offset(1)
        End If
    Next
    Application.ScreenUpdating = True

End Sub

This is as far as i got to copy A9 from each worksheet to file directory. i cant figure out how to create the if to create the sub folders. any help would be appreciated!

A: The code below should work for you provided the subfolder names are in column A.
Sub FileDirectory()

Dim ws As Worksheet
Dim subfolders() As String
Dim cell As Range, i As Integer

subfolders = Split("PRODUCT DATA,SAMPLES,SHOP DRAWINGS,MATERIAL CERTIFICATES", ",")

Application.ScreenUpdating = False

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "File Directory" Then
        ws.Range("A9").Copy Sheets("File Directory").Cells(Rows.Count, "A").End(xlUp).Offset(1)
        For Each cell In ws.Range("A:A") 'Changing this cell range to a smaller, defined range will improve performance
            For i = LBound(subfolders) To UBound(subfolders)
                If cell.Value = subfolders(i) Then
                    Sheets("File Directory").Cells(Rows.Count, "A").End(xlUp).Offset(1) = ws.Range("A9").Value + "/" + cell.Value
                End If
            Next i
        Next cell
    End If
Next

Application.ScreenUpdating = True

End Sub


text:
Q: How to replace "leading zero" witin a string How can i replace or remove "0" from a string in bash
The string is based in [prefix][ID][suffix]
e.g. ZZZ00004500AA010 or ZZZ004500AA010
the result must be
ZZZ4500AA010
so i want to remove the leading 0's in the ID
At the moment i have this:
echo "ZZZ00004500AA010" | sed 's/0//'
echo "ZZZ004500AA010" | sed 's/0//'

which gives me : ZZZ0004500AA010 or ZZZ04500AA010

A: You can use a capture group to match the leading chars other than a digit, and then match 0 or more digits.
In the replacement use group 1.
^([^0-9]*)0+

Regex demo
echo "ZZZ00004500AA010" | sed -E 's/^([^0-9]*)0+/\1/'
echo "ZZZ004500AA010" | sed -E 's/^([^0-9]*)0+/\1/'

Output
ZZZ4500AA010
ZZZ4500AA010

If there have to be leading chars A-Z:
^([A-Z]+)0+

Regex demo

A: If you know there's always at least one zero, you don't need sed at all, you can use parameter expansion. You can use a regex match to check there is a zero after the initial non-digits:
#! /bin/bash
shopt -s extglob
for v in ZZZ00004500AA010 ZZZ004500AA010 ZZZ04500AA010 ZZZ4500AA010 ; do
    if [[ $v =~ ^[^0-9]+0 ]] ; then
        v=${v/+(0)/}
    fi
    echo "$v"
done

Output:
ZZZ4500AA010
ZZZ4500AA010
ZZZ4500AA010
ZZZ4500AA010

A: Use this Perl one-liner:
$ echo "ZZZ00004500AA010" | perl -pe 's{^([A-Za-z]+)0+}{$1}'
ZZZ4500AA010

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
s{PATTERN}{REPLACEMENT} : Change PATTERN to REPLACEMENT.
^ : Beginning of the string.
([A-Za-z]+) : Match any letter repeated 1 or more times. Capture into capture group 1 ($1).
0+ : zero, repeated 1 or more times.
SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick: Perl regular expressions quick start


text:
Q: Can't see the right pane in p4v After I created a new workspace I stopped being able to see the right pane (workspace area). I tried View->history, View->pending changelists....but is till see only the left pane taking all the space.
What am I doing wrong?


text:
Q: Confused about the phrase "as little as" I'm currently reading Demian and came across the following paragraph:

Novelists when they write novels tend to take an almost godlike
  attitude toward their subject, pretending to a total comprehension of
  the story, a man's life, which they can therefore recount as God
  Himself might, nothing standing between them and the naked truth, the
  entire story meaningful in every detail. I am as little able to do
  this as the novelist is, even though my story is more important to
  me than any novelist's is to him -- for this is my story; it is the
  story of a man, not of an invented, or possible, or idealized, or
  otherwise absent figure.

I'm finding it a little difficult to full understand what Hesse means. It seems like he's trying to say that novelists have a total comprehension of the story, but he does not. And then he says "I am as little able to do this as the novelist is," suggesting that novelists also have little comprehension of the story (much like Hesse)?
What does he actually mean?

A: "I am as X as Y is" means that the speaker and Y are both equally X. So "I am as little able to do this as the novelist is" means the speaker and the novelist are both equally little able to do this, just as "I am as tired as Jeff is" means that the speaker and Jeff are both equally tired.


text:
Q: Caching bitmap in android Kind of new to caching of bitmap for android. Would like to ask a few questions. Do you guys have sample code of caching an image and retriving an image from cache. How do the codes know once the cache is being overridden?

A: There is a question similar to this:
give it a look here Android image caching .
You will see there an elegant method to solve your problem :)


text:
Q: BoxStore DbMaxReadersExceededException: How to resolve for background RxJava threads? - Exception still occurs I know this subject has been discussed here before, and we have utilized past conversations to attempt to resolve the DbMaxReadersExceededException that we are still experiencing.  We are using version 2.5.1 of ObjectBox.  We are also, heavily, using RxJava threads while manipulating our BoxStore DB.  At any moment in time, potentially a handful of RxJava threads are running, accessing the DB.  Threads are constantly spawning, executing and terminating.
This is a very "non-standard" use of Android.  Our App is running on a non-cell phone device, that sits on a wall and is expected to be available 24x7.  95% of the RxJava threads that access the BoxStore DB are short lived, get in / get out threads, that retrieve information and present to the device user.  We do have a few longer lived background RxJava threads, that talk to an external DB over the internet to keep the local DB up to date.  But these threads to spawn, execute and terminate.  Theses threads run in the background at regular intervals.  These background threads are not associated with a Fragment nor Activity; therefore the common way of cleaning up, using a CompositeDisposable, is not utilized.
We are seeing that readers are accumulating, despite many attempts to resolve the situation.  We have also noticed that threads, that have run to termination, marked as isAlive and appear to be part of the RxJava thread pool, also accumulate.  We have observed this using Thread.getAllStackTraces() and printing out this information regularly.  Separate issue I am not trying to resolve with this post (I am concentrating on the DbMaxReadersExceededException issue, but they may be related).
The readers accumulate as the result of .find() calls on a Query that is build; based upon analysis of when a reader occurs.  That is not surprising, but sometimes a .find() causes a new reader and sometimes it does not.  I do not understand this behavior, and I am not sure if that is a telling sign or not.  But it does result in the accumlation of active readers everytime the RxJava thread that accessed a given Box is invoked.
Any help / assistance offered will be greatly appreciated.  Please ask any questions about anything that I may have accidental left out.
Things that we have tried, based upon other posts that I have read, include:

*

*Collect Disposables from RxJava background threads and dispose
We have tried collecting the Disposable generated by the .subscribe() from these background threads, and added a timer to .dispose() of them sometime (5 seconds) after the thread that was using this object terminates (run to completion).

*Utilized BoxStore.diagnose()
We have written code to utilize BoxStore.diagnose() to be able to periodically watch the reader accumulation.

*Tried BoxStore.closeThreadResources()
We have added BoxStore.closeThreadResources() calls when an RxJava thread terminates to cleanup any BoxStore resources that may be active.

*Tried Box.closeThreadResources()
We have tried adding Box.closeThreadResources() calls closer to when the Box is accessed in order to access and then clean up ASAP.

*Tried breaking down .method() sequence and added .close() calls to itermediate objects
We have tried breaking down the .method() call sequence that terminates with the .find() call and then .close() or .closeThreadResources() the intermediate objects along the way.

*Tried combinations of the above
We have tried a combination of all of the above.

*Wrote method to be able to monitor RxJava threads using Thread.getAllStackTraces() - RxJava threads seem to accumulate
We have written a method that helps us monitor RxJava threads using Thread.getAllStackTraces().

*We have tried to manually invoke the Garbage Collector
We added code, after the .dispose(), mentioned above, to cause a manual Garbage Collection (System.gc()).
As far as I know, we have tried every suggestion that I have seen posted on this and other forms, regarding this issue.  We are at a loss as to what to do or try next.  I did see something about a package called RxObjectBox, but I have not pursued this any further.
Should we:

*

*Look at restructuring our RxJava thread access?

*Do we need to look closer at RxObjectBox?

*Is there a known problem with ObjectBox 2.5.1 that we should be using a later version?

*What haven't we tried that we should?


text:
Q: Python 3 exception convertion and re-raise I have the following problem:
my application is a bridge between dbus and json-rpc.
I have a dbus library that in case of Dbus exception is raising a
DBusException("my err msg") exception.

My json-rpc library is catching all the Exception and convert it to a nice generic server error message
{"jsonrpc": "2.0", "error": {"code": -32000, "message": "Server error"}, "id": 2}

The problem is that i want to handle better those exceptions and I can distinguish between them only using the error message:
for example I need to convert the
DBusException("Invalid Parameters")

to
{"jsonrpc": "2.0", "error": {"code": -32001, "message": "Server error", data="Invalid Parameters" }, "id": 2}

that can be done raising in my library an ApiError(msg, code, data) exception.
So summarizing:
- I need to catch a DBusException
- based on the err_msg I need to switch between different exception types and re-raise a modified
  ApiError exception
How is the better approach to that? this needs to be done in at least 10 functions that have the same exceptions.
1) using a decorator?
def my_exception_catcher(fun, *args, **kwargv):
    try:
        fun(args, *argv)
    except DBusException as e
        err_msg = str(e)
        if err_msg == "Invalid Arguments":
            raise ApiError("Server Error", code=1, data=err_msg)
        else if err_msg == "Connect Error":
            raise ApiError("Server Error", code=2, data=err_msg)
        else:
            raise

@my_exception_catcher
my_fun(*args):
    do_something

2) using a function to determine the exception type?
def find_my_dbus_error(err_msg):
    if err_msg == "Invalid Arguments":
        return ApiError("Server Error", code=1, data=err_msg)
    else if err_msg == "Connect Error":
        return ApiError("Server Error", code=2, data=err_msg)
    else:
        return Exception(err_msg)

try:
    my_fun(params)
except DBusException as e
    raise find_my_dbus_error(err_msg)

3) something else?
Thanks
Nick


text:
Q: Searching a TableView of annotations I had no idea how to set up a database when i started so i have 80 annotations that all look like this
workingCoordinate.latitude = 50.795825;
workingCoordinate.longitude = -1.103139;
MainViewAnnotation *Levant = [[MainViewAnnotation alloc] initWithCoordinate:workingCoordinate];
[Levant setTitle:@"Levant"];
[Levant setSubtitle:@"Unit R09, Gunwharf Quays"];
[Levant setAnnotationType:MainViewAnnotationTypePortsmouth];

[mapView addAnnotation:Levant];

They are grouped into 22 cities through the MainViewAnnotationType, which is coded as follows:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 21;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == MainViewAnnotationTypeBirmingham)
    {
        return @"Birmingham";
    }

    else if(section == MainViewAnnotationTypePortsmouth)
    {
        return @"Portsmouth";
    }

    return nil;
}

The annotations are then put into a TableView like so;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    NSMutableArray *annotations = [[NSMutableArray alloc] init];

    if(indexPath.section == 0)
    {
        for(MainViewAnnotation *annotation in [mapView annotations])
        {
            if(![annotation isKindOfClass:[MKUserLocation class]])
            {
            if([annotation annotationType] == MainViewAnnotationTypeBirmingham)
            {
                [annotations addObject:annotation];
            }
            }
        }
        cell.textLabel.text = [[annotations objectAtIndex:indexPath.row] title];
    }
    ...
    else if(indexPath.section == 17)
    {
        for(MainViewAnnotation *annotation in [mapView annotations])
        {
            if(![annotation isKindOfClass:[MKUserLocation class]])
            {
                if([annotation annotationType] == MainViewAnnotationTypePortsmouth)
                {
                    [annotations addObject:annotation];
                }
            }
        }
        cell.textLabel.text = [[annotations objectAtIndex:indexPath.row] title];
    }

    return cell;

}

and then when a cell is clicked, will zoom in on the annotation.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    for(MainViewAnnotation *annotation in [mapView annotations])
    {
        if([[[[tableView cellForRowAtIndexPath:indexPath] textLabel] text] isEqualToString:[annotation title]])
        {
            [mapView setRegion:MKCoordinateRegionMake([annotation coordinate], MKCoordinateSpanMake(.003, .003)) animated:YES];
        }
    }
}

My question is, I would like to be able to search my annotations either through their city their in or by their annotation name. I have a search bar controller already in my interface and it has been connected to my tableview, just not written any code.
I would like the search to be hidden unless i click a search button then hide when i click on a cell.
New to Xcode, any help including some code examples would be much appreciated.

A: What I did is to create my UITableView not programmatically but using Interface Builder. Create your own custom ViewController and add inside an UITableView. Don't forget to set (by interface builder) delegate and datasource. Afterwards I think it might be easier for you to manage your hidden/show search bar.
Hope this can help.


text:
Q: Installing CentOS 6.3 via USB, cannot partition hard disk drives I'm currently attempting to install CentOS 6.3 on an IBM System x3650 M3 server using a 8GB USB boot drive that has been created using iso2usb for CentOS/RedHat.
During the installation process, when it comes time to setup partitioning, if any of the automated options are selected, an error occurs (could not find enough free space for automatic partitioning). If I instead choose a manual setup, then I find that the installer is attempting to partition the USB drive, and not the machine's virtual memory as desired.
I've attempted to Google the problem, and while I've found many with problems installing CentOS, I've yet to find any information that applies here.
Any help that you can give would be greatly appreciated.

A: Turns out, the previous owners of this system wiped the system's RAID configuration when they reformatted the machine.
Resetting the server to factory defaults in the BIOS, then booting in recovery mode recovered the lost RAID drivers, and allowed me to reconfigure the RAID to my liking.
I'd just like to thank Michael Hampton for his help, as it got me thinking about the machine's firmware, eventually leading me to the answer.


text:
Q: java.lang.IllegalStateException: Cannot forward after response has been committed while saving into mysql I am going through a tutorial and trying to build a very simple MVC web application with MySql. My IDE is Eclipse. I want to insert to database but I cannot tell where the problem is coming from either my Servlet or JSP
I am running out of ideas. What is not right?. Every thing seems fine too.
servlet.java
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    doGet(request, response);
    PrintWriter out = response.getWriter();
    UsersDAO dao =new UsersDAO(); // data access object
    String useraction = request.getParameter("useraction");

    String userId = request.getParameter("userId");
    String fullName =request.getParameter("fullName");
    String userName = request.getParameter("userName");
    String passWord = request.getParameter("passWord");
    String bankBranch = request.getParameter("bankBranch");
    String department = request.getParameter("department");
    String userPermission = request.getParameter("userPermission");
    String amtGroupID = request.getParameter("amtGroupID");
    String roleId = request.getParameter("roleId");
    String dateCreated = request.getParameter("dateCreated");

    if (useraction != null && useraction.equals("create")) {
        Users adduser =new Users(fullName,userName, passWord, bankBranch, department,0, dateCreated, 0);
        out.print("
User Added
");
        RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/registeruser.jsp");
        view.forward(request, response);
        dao.create(adduser);
    }else{
        out.print("
Sorry username or password error
");
        RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/registeruser.jsp");
        view.forward(request, response);
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        String path = request.getParameter("path");

        if (path != null && path.equals("register")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/registeruser.jsp");
            view.forward(request, response);
        } else if (path != null && path.equals("usermang")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/manageuser.jsp");
            view.forward(request, response);
        } else if (path != null && path.equals("return")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/grcon/grcon.jsp");
            view.forward(request, response);
        } else if (action != null && action.equals("Login")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/grcon/grcon.jsp");
            view.forward(request, response);
        } else if (path != null && path.equals("journal")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/grcon/ejournal.jsp");
            view.forward(request, response);
        }else if (path != null && path.equals("recon")) {
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/grcon/reconcil.jsp");
            view.forward(request, response);
        }
        else {
            PrintWriter out = response.getWriter();
            out.print("Served at: " + request.getContextPath());
            RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/views/system/index.jsp");
            view.forward(request, response);
        }
}

JSP code
<% UsersDAO dao = new UsersDAO();%>
  <form  action="System" method="post" class="form-horizontal form-label-left" novalidate  >
    User Info

    Full Name *

    <input id="fullName" class="form-control col-md-7 col-xs-12"
    data-validate-length-range="6" data-validate-words="2"
    name="fullName" placeholder="both name(s) e.g Jon Doe"
    required="required" type="text" />

    User Name *

    <input type="text" id="userName" name="userName"required="required" class="form-control col-md-7 col-xs-12" />

    Password

     <input id="passWord" type="password" name="passWord"data-validate-length="6,10"
    class="form-control col-md-7 col-xs-12" required="required" />

 </form>

Error log
SEVERE: Servlet.service() for servlet [controller.System] in context with path [/G-Recon] threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:327)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:317)
    at controller.System.doPost(System.java:92)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

A: Change
view.forward(request, response);
dao.create(adduser);

to
dao.create(adduser);//first create user
view.forward(request, response);//later forward the req

There is no need of calling doGet(request, response);.

A:
java.lang.IllegalStateException: Cannot forward after response has
  been committed

Remove your out.println() code as you want to actually forward to different url.
You cannot forward if you have already written something to response stream.


text:
Q: SIGSEGV error in pandas Series.rank(ascending=False) 1,I want to read a hdf5 file and rank it.
import pandas as pd
def test_df_ranks(f):
    df = pd.read_hdf(f, key="t")
    print (df.shape)
    print (type(df))
    print (df)
    s=df.non_current_asset_to_total_asset
    #s.rank()     # rank() work properly
    s.rank(ascending=False)  #rank(ascending=False) crash

Then I got an SIGSEGV error.
the follows is verison list:
numpy==1.11.0
pandas==0.17.1
pymongo==3.2.2
python-dateutil==2.5.3
pytz==2016.4
ricequant-utility==0.1.0
six==1.10.0
tables==3.2.2
os: 3.10.0-327.13.1.el7.x86_64 #1 SMP Thu Mar 31 16:04:38 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
gcc: 4.8.5

I try to go stack with gdb but various stack showing:
#1:
 ....
#7  OBJECT_compare (ip1=0x47a3ef4b2e420, ip2=0x7f5c5413f128, __NPY_UNUSED_TAGGEDap=0x7f5cd0100760) at numpy/core/src/multiarray/arraytypes.c.src:2753
#8  0x00007f5d0142c50e in npy_aquicksort (vv=vv@entry=0x7f5c5413f060, tosort=tosort@entry=0x7f5c5413cc80, num=num@entry=52, varr=varr@entry=0x7f5cd0100760) at numpy/core/src/npysort/quicksort.c.src:480
#9  0x00007f5d0139a78a in _new_argsortlike (op=op@entry=0x7f5cd0100760, axis=0, argsort=argsort@entry=0x7f5d0142c310 <npy_aquicksort>, argpart=argpart@entry=0x0, kth=kth@entry=0x0, nkth=nkth@entry=0)
at numpy/core/src/multiarray/item_selection.c:1035
#10 0x00007f5d0139dd7b in PyArray_ArgSort (op=op@entry=0x7f5cd0100760, axis=0, which=<optimized out>) at numpy/core/src/multiarray/item_selection.c:1309
#11 0x00007f5d013dd012 in array_argsort (self=0x7f5cd0100760, args=<optimized out>, kwds=<optimized out>) at numpy/core/src/multiarray/methods.c:1278
#12 0x00007f5cf4eef28f in __Pyx_PyObject_Call (func=0x7f5cd1a1acc8, arg=0x7f5d0f900048, kw=0x0) at pandas/algos.c:201388
#13 0x00007f5cf504e006 in __pyx_pf_6pandas_5algos_8rank_1d_generic (__pyx_v_in_arr=__pyx_v_in_arr@entry=0x7f5cd0100620, __pyx_v_retry=1, __pyx_v_ties_method=0x7f5cf6999768, __pyx_v_ascending=0x7f5d0f6bd700 <_Py_FalseStruct>,
__pyx_v_na_option=<optimized out>, __pyx_v_pct=0x7f5d0f6bd700 <_Py_FalseStruct>, __pyx_self=<optimized out>) at pandas/algos.c:14942
#14 0x00007f5cf5050481 in __pyx_pw_6pandas_5algos_9rank_1d_generic (__pyx_self=<optimized out>, __pyx_args=<optimized out>, __pyx_kwds=0x7f5cd8659488) at pandas/algos.c:14439
#15 0x00007f5d0f3b9477 in PyEval_EvalFrameEx () from /lib64/libpython3.4m.so.1.0
#16 0x00007f5d0f3b9f3e in PyEval_EvalCodeEx () from /lib64/libpython3.4m.so.1.0
#17 0x00007f5d0f3b7a12 in PyEval_EvalFrameEx () from /lib64/libpython3.4m.so.1.0
#18 0x00007f5d0f3b9f3e in PyEval_EvalCodeEx () from /lib64/libpython3.4m.so.1.0
#19 0x00007f5d0f3b7a12 in PyEval_EvalFrameEx () from /lib64/libpython3.4m.so.1.0
#20 0x00007f5d0f3b8e40 in PyEval_EvalFrameEx () from /lib64/libpython3.4m.so.1.0
#21 0x00007f5d0f3b9f3e in PyEval_EvalCodeEx () from /lib64/libpython3.4m.so.1.0
#22 0x00007f5d0f3b7a12 in PyEval_EvalFrameEx () from /lib64/libpython3.4m.so.1.0
#23 0x00007f5d0f3b9f3e in PyEval_EvalCodeEx () from /lib64/libpython3.4m.so.1.0
#24 0x00007f5d0f32a4b3 in function_call () from /lib64/libpython3.4m.so.1.0
#25 0x00007f5d0f301dcc in PyObject_Call () from /lib64/libpython3.4m.so.1.0
#26 0x00007f5d0f3b57c9 in PyEval_EvalFrameEx () from /lib64/libpython3.4m.so.1.0

...
now the stack is:
#0  0x00007ffff6c985f7 in raise () from /lib64/libc.so.6
#1  0x00007ffff6c99ce8 in abort () from /lib64/libc.so.6
#2  0x00007ffff6cd8317 in __libc_message () from /lib64/libc.so.6
#3  0x00007ffff6ce0023 in _int_free () from /lib64/libc.so.6
#4  0x00007fffd15785a9 in H5FL_reg_gc_list () from /lib64/libhdf5.so.8
#5  0x00007fffd1578626 in H5FL_reg_gc () from /lib64/libhdf5.so.8
#6  0x00007fffd157b0be in H5FL_garbage_coll () from /lib64/libhdf5.so.8
#7  0x00007fffd157b34e in H5FL_term_interface () from /lib64/libhdf5.so.8
#8  0x00007fffd14ae466 in H5_term_library () from /lib64/libhdf5.so.8
#9  0x00007ffff6c9be69 in __run_exit_handlers () from /lib64/libc.so.6
#10 0x00007ffff6c9beb5 in exit () from /lib64/libc.so.6
#11 0x00007ffff6c84b1c in __libc_start_main () from /lib64/libc.so.6
#12 0x0000000000400b89 in _start ()

2, I save my data to csv. and then get pd.Series by pd.read_csv()
   both series.rank(ascending=True) or series.rank(ascending=Flase) works well.
3, maybe  problems in tables? or hdf5? my hdf5 data:https://github.com/HaoXJ/codefail/blob/master/data/test.h5.
4, Need you guys's help.

A: First of all, your non_current_asset_to_total_asset column doesn't have any non-NaN value, but nevertheless it seems to be a numpy or pandas bug. You may want to check whether it's already been raised as a bug here. Or open a new issue...
In [1]: fn = r'D:\download\test.h5'

In [2]: df = pd.read_hdf(fn, key='t')

list rows where non_current_asset_to_total_asset is not NaN
In [3]: df[pd.notnull(df.non_current_asset_to_total_asset)]
Out[3]:
Empty DataFrame
Columns: [pb_ratio, pe_ratio_1, inc_operating_revenue, inc_total_asset, non_current_asset_to_total_asset]
Index: []

NOTE: there is NO rows where non_current_asset_to_total_asset is not NaN
In [4]: df.head()
Out[4]:
            pb_ratio pe_ratio_1 inc_operating_revenue inc_total_asset non_current_asset_to_total_asset
000022.XSHE   7.4091    14.9739               30.5996         13.1342                              NaN
000089.XSHE   1.7244    14.3574                7.5837          2.8343                              NaN
000099.XSHE   1.7782    23.6805                8.7495         -0.0933                              NaN
000429.XSHE   1.7264    17.5882               15.1496         -0.9485                              NaN
000507.XSHE   1.1563    46.9562               26.9032          4.4909                              NaN

rank(ascending=True) works:
In [10]: df.non_current_asset_to_total_asset.rank(ascending=True).head()
Out[10]:
000022.XSHE   NaN
000089.XSHE   NaN
000099.XSHE   NaN
000429.XSHE   NaN
000507.XSHE   NaN
Name: non_current_asset_to_total_asset, dtype: float64

but rank(ascending=False) crashes my iPython:
In [5]: df.non_current_asset_to_total_asset.rank(ascending=False)

Crash info:
<EXE NAME="multiarray.cp35-win_amd64.pyd" FILTER="CMI_FILTER_THISFILEONLY">
    <MATCHING_FILE NAME="multiarray.cp35-win_amd64.pyd" SIZE="1510912" CHECKSUM="0xD8B922AB" MODULE_TYPE="WIN32" PE_CHECKSUM="0x0" LINKER_VERSION="0x0" LINK_DATE="05/02/2016 21:19:46" UPTO_LINK_DATE="05/02/2016 21:19:46" EXPORT_NAME="multiarray.cp35-win_amd64.pyd" EXE_WRAPPER="0x0" />
</EXE>
<EXE NAME="kernel32.dll" FILTER="CMI_FILTER_THISFILEONLY">
    <MATCHING_FILE NAME="kernel32.dll" SIZE="1163264" CHECKSUM="0xADFC88B8" BIN_FILE_VERSION="6.1.7601.23418" BIN_PRODUCT_VERSION="6.1.7601.23418" PRODUCT_VERSION="6.1.7601.18015" FILE_DESCRIPTION="Windows NT BASE API Client DLL" COMPANY_NAME="Microsoft Corporation" PRODUCT_NAME="Microsoft® Windows® Operating System" FILE_VERSION="6.1.7601.18015 (win7sp1_gdr.121129-1432)" ORIGINAL_FILENAME="kernel32" INTERNAL_NAME="kernel32" LEGAL_COPYRIGHT="© Microsoft Corporation. All rights reserved." VERDATEHI="0x0" VERDATELO="0x0" VERFILEOS="0x40004" VERFILETYPE="0x2" MODULE_TYPE="WIN32" PE_CHECKSUM="0x122E58" LINKER_VERSION="0x60001" UPTO_BIN_FILE_VERSION="6.1.7601.23418" UPTO_BIN_PRODUCT_VERSION="6.1.7601.23418" LINK_DATE="04/09/2016 07:00:43" UPTO_LINK_DATE="04/09/2016 07:00:43" EXPORT_NAME="KERNEL32.dll" VER_LANGUAGE="English (United States) [0x409]" EXE_WRAPPER="0x0" />
</EXE>
</DATABASE>

my versions:
In [5]: pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.5.1.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en_US

pandas: 0.18.1
nose: 1.3.7
pip: 8.1.2
setuptools: 21.2.1
Cython: 0.23.4
numpy: 1.10.4
scipy: 0.17.0
statsmodels: None
xarray: None
IPython: 4.2.0
sphinx: 1.4
patsy: None
dateutil: 2.5.3
pytz: 2016.4
blosc: None
bottleneck: None
tables: 3.2.2
numexpr: 2.5.2
matplotlib: 1.5.1
openpyxl: 2.3.5
xlrd: 0.9.4
xlwt: None
xlsxwriter: 0.8.7
lxml: 3.6.0
bs4: 4.4.1
html5lib: 0.9999999
httplib2: None
apiclient: None
sqlalchemy: 1.0.13
pymysql: None
psycopg2: None
jinja2: 2.8
boto: None
pandas_datareader: 0.2.1


text:
Q: How do I zoom and extract box from webpage using webview? I am using the web view commands to display a webpage. My question is, "Is there a command to actually take only a box of the webpage with a declared size zoom too it and lock the screen around it?"
Basically I'm trying to remove a server status section of the webpage and display the zoomed portion on the phone on click. Below is my web view file calling to Google, but that will change to the rel site in the future.
If possible I would like to compress this box to fit to the size of the phone screen, landscape or otherwise.
EDIT: I have done a bit of research and reading. I'm going to try to work with Jsoup. Unfortunately after reading documentation and examples of webpage "scraping" I am unable to figure out how to load webpage HTML as document -> search document for target code -> display target code on layout.
As you can see I started to try to do this in webview, and I may in the future try to do the out to layout through webview.
Any help understanding this better would b appreciated!
EDIT 2: Added some more scrape code, this seems like it could do what I want but I'm unclear on how to reference the variables in the HTML code to display.
Here is the HTML that I am working with, followed by the code I'm using:

                Server Status

                This page lists all available Diablo III game and auction house servers, as well as the status of each – either available or undergoing maintenance.

Americas

                Game Server

Auction House

                Gold

                Hardcore

                USD

                AUD

                MXN

                BRL

                CLP

                ARS

    package d3.link;

import java.io.File;
import java.io.IOException;
import d3.link.R;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.widget.TextView;

public class ServerStatusActivity extends Activity
{

    //WebView webView;
    public static void main(String[] args) throws Exception
    {
        String url = "http://us.battle.net/d3/en/status";
        Document doc = Jsoup.connect(url).get();

        String serverstatus = Document.select().text();
        System.out.println("Server Status: " + serverstatus);

        Elements answerers = Document.select();
            for (Element answerer : answerers)
            {
                System.out.println("Answerer: " + answerer.text());
            }

    }

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ss);

        //webView = (WebView) findViewById(R.id.webView1);
        //webView.getSettings().setJavaScriptEnabled(true);
        //webView.getSettings().setSupportZoom(false);
        //webView.getSettings().setBuiltInZoomControls(false);
        //webView.getSettings().setLoadWithOverviewMode(true);
        //webView.getSettings().setUseWideViewPort(true);
        //webView.loadUrl("http://us.battle.net/d3/en/status");

    }

}

}

A: Use XPath to select the server status HTML (//div[@class="server-status"]) and then just render this part.


text:
Q: Data is not transferring from Client to Server in Meteor Main purpose of this code is, when we have data in database it should fetch and display on the browser. But i couldn't find it.
Problem is transferring data to the Server.
After running the meteor and enter some value from console of the browser,i am not able to see them back on the browser.But i am able to find them with in console by using the command "Tdos.find().fetch()",it is showing arrays that i have entered but if i am trying to find in mongodb console, we couldn't find it. Can Some one figure out my problem and where am i going wrong?

     <title>simpletodos</title>

     {{> todoList}}

  <template name="todoList">

Todos

  {{#each tdos}}
      {{> todo}}
  {{/each}}

     <button class="add-todo">Add todo</button>

  </template>
  <template name="todo">

       {{label}}

</template>

Client/Main.js
  if(Meteor.isClient) {

    Template.todoList.helpers({
     todos: function() {
     return Tdos.find();
    }
  });

    if(Meteor.isServer) {

    }
  }

Server/main.js
  import { Meteor } from 'meteor/meteor';

  Tdos = new Mongo.Collection("tdos");

 Meteor.startup(() => {
   // code to run on server at startup
  });

A: In your server, you define the collection like this:
Tdos = new Mongo.Collection("tdos");

Which means the collection in Mongo is todos, and you can list the contents with
db.todos.find()

You can insert a record in mongo using this:
db.todos.insert({label: "My first to do"})

In Meteor when you want to fetch or insert/update, you use Tdos, eg
Tdos.insert(...};

Your helper lets the data be available as an array within your code. I think you need to change that to be
todos: function() {
    return Tdos.find().fetch();
}


text:
Q: remove a column when the column name is empty in R I was running a procedure to make the first row as column names. Since one value is NA one column has become empty. Here is the example.
df <- data.frame(var1 = c("a","b","c","d",NA),
                 var2 = c(1,2,3,4,NA),
                 var3 = c(NA,7,8,9,10))

> df
  var1 var2 var3
1    a    1   NA
2    b    2    7
3    c    3    8
4    d    4    9
5 <NA>   NA   10

df1 <- df %>%
  janitor::row_to_names(row_number = 1)

> df1
     a  1 NA
2    b  2  7
3    c  3  8
4    d  4  9
5 <NA> NA 10

How can I remove when the column name is empty?
The desired output would be:
  > df2
         a  1
    2    b  2
    3    c  3
    4    d  4
    5 <NA> NA


text:
Q: System of differential equations depending on parameter This is the first time to get a question like this:
How to solve the system $y'=3by+(1-2b)z$, $z'=by+z+e^{4x}$, where $b\in\mathbb{R}$?
Any help is welcome.

A: Hint:
Substracting both differential equations gives us:
$$(y-z)'-2b(y-z)=-e^{4x}$$
This DE can easily be solved. It's a first linear DE.


text:
Q: Is it okay to use TextEditingController in StatelessWidget in Flutter? I don't need to do many things with TextEditingController but want to show the initial text. And I feel like creating StatefulWidget is too much for that.
Here's what I want my code looks like
// In StatelessWidget
TextField(
    controller: TextEditingController(),
)

But every tutorials and blog posts I've seen use TextEditingController in StatefulWidget and dispose them in the dispose method. But I can't dispose them if I use like the above

A: If you want to use TextEditingController, there is no way around except to use a StatefulWidget if you want to avoid memory leaks.
However, if you see alot of boilerplate in this approach, you can use HookWidget (flutter_hooks) which gives you access to TextEditingController in a simple way and disposes it for you,here is a comparison:
using StatefulWidget:
class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  TextEditingController controller;
  FocusNode focusNode;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.red,
          child: TextField(
            focusNode: focusNode,
            controller: controller,
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    controller = TextEditingController();
    focusNode = FocusNode();
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    focusNode.dispose();
    super.dispose();
  }
}

using HookWidget:
class Test extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final focusNode = useFocusNode();
    final controller = useTextEditingController();
      return Scaffold(
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.red,
          child: TextField(
            focusNode: focusNode,
            controller: controller,
          ),
        ),
      ),
    );
  }
}


text:
Q: How to insert text in smart textbox in selenium webdriver? I am trying to automate the code of submit resume page, it consists on smart textboxes, which gives suggestions below as soon as you type few text in it. you need to select and input into the textbox from the suggestions given. Below is the code and the url:
WebDriver w= new FirefoxDriver();
w.get("https://www.hrmantra.com/LetsLead/18_Recruitment/SubmittResume.aspx?cn=LetsLead");
w.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
w.findElement(By.id("StCityName_txtSpeedName")).sendKeys("Mumbai");

Only sendkeys command is not working as the entered value has to be selected and the control needs to be closed.

A: The text box has a select drop down box which appears dynamically on entering the city from it the user selects his city but this select box is inside an iframe (iframe id : SpeedTyperFrameID)so we need to switch to it and then access the select box
Below is the code
    WebElement city = driver.findElement(By.xpath("//*[@id='StCityName_txtSpeedName']"));

    city.click();

    city.sendKeys("chennai");

   //wait for the iframe to load and then switch to it

    new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("SpeedTyperFrameID")));

    Thread,sleep(3000);//added just to show u the effect remove it
    WebElement byValue = driver.findElement(By.id("SelectList"));

    //using select class to select the element by its text
    Select select = new Select(byValue);

    select.selectByVisibleText("Chennai");

    //switch back to default content inorder to access other elements outside the iframe

    driver.switchTo().defaultContent();

I have tested the above code it is working fine
Kindly get back if you have any queries.

A: It's because there is no ID of id=StCityName_txtSpeedName on the page. You don't use id=... for the ID, you just type the ID.
See below.
w.findElement(By.id("StCityName_txtSpeedName")).sendKeys("Mumbai");

A: Ideally, After you type partial text into input you have to find all suggestions from dropdown list and click on it. Perhaps, try to use enter key, but I am not aware that it will help
element.sendKeys("Mumbai" + Keys.ENTER)


text:
Q: how do i get my all TFS shelve-sets in local using git-tf or git tfs? Present i am merging a project TFS to GIT
(using git tfs tool), i am able to merge the project,
all change-sets converted to commits,
and it preserves the history.
refer this.
when i using below command
git tfs shelve-list -u=MyUserName

I am able to view all my shelve-sets from remote TFS.but i am not able to get all shelve-sets.
Similarly is there any way to convert shelve-sets to stashes and store locally.

A: You should create a branch for each shelveset using (See https://github.com/git-tfs/git-tfs/blob/master/doc/commands/unshelve.md):
git tfs unshelve -u UserName MyShelvesetName MyBranch

That's not possible to unshelve them all (no one needed enough to contribute the development).
Note: Even if it's quite easy to add this feature in git-tfs ( here: https://github.com/git-tfs/git-tfs/blob/master/src/GitTfs/Commands/Unshelve.cs#L43 ), and I will be pleased to merge the pull request if you do it...


text:
Q: How can I make my ActiveRecord objects only exist for 5 minutes in Ruby on Rails? I've created a model called Request, which is created when one user makes a request with another user. I'd like each request to only exist for 5 minutes. Is this possible?

A: Couple of ways to do this ... you could add a Sweeper or delayed job to clear the values from the database periodically. Give each record a created_at, clear after 5 minutes.
Alternative would be to do this check when presenting the information to the user ... similar idea, have a created_at, when you check the pending requests for the current user you ignore or delete any that are older than 5 minutes.


text:
Q: QtiPlot and Python: global name 'QLocale' is not defined I'm developing a Python script the will run inside an application named QtiPlot. I searched the Qtiplot's documentation for Python API and it uses PyQt 4. I coded my script as bellow:
#! /usr/bin/env python

# A python script to be used in QtiPlot to convert .dat files into .jpg graphs and these ones into .avi movie

import os
import re
import glob
from PyQt4 import uic
from PyQt4 import *

def chooseInputFolder():
    input_folder = QtGui.QFileDialog.getExistingDirectory(qti.app, "Choose Working Folder")
    ui.inputFolderLine.setText(input_folder)
    return input_folder

def chooseOutputFile():
    output_file = QtGui.QFileDialog.getSaveFileName(qti.app, "Choose Output File")
    ui.outputFileLine.setText(output_file)
    return output_file

def createVideoFromJPG():
    input_folder_name = ui.inputFolderLine.text()
    output_file_name = ui.outputFileLine.text()
    dirList = os.listdir(input_folder_name)
    for fname in dirList:
        t = newTable()
        t.importASCII(input_folder_name+fname,sep="\t",ignoreLines=0,renameCols=False,stripSpaces=True,simplifySpace=False,importComments=False,comment="#",readOnly=False,importAs=Table.Overwrite,locale=QLocale(),endLine=0,maxRows=-1)
#       g = plot(t, 2, 0)
#       cmd = 'mencoder "mf://*.jpg" -mf fps=25 -o %s -ovc lavc -lavcopts vcodec=mpeg4' % output_file
#       os.system(cmd)

ui = uic.loadUi("/home/kurumin/Scripts/python/dat2vid.ui")
ui.connect(ui.inputFolderButton, QtCore.SIGNAL("clicked()"),chooseInputFolder)
ui.connect(ui.outputFileButton, QtCore.SIGNAL("clicked()"),chooseOutputFile)
ui.connect(ui.createVideo, QtCore.SIGNAL("clicked()"),createVideoFromJPG)
ui.show()

And this is the output:
Traceback (most recent call last):

File "<>", line 27, in createVideoFromJPG

NameError
:
global name 'QLocale' is not defined

I tried to define QLocale but I couldn't find anything really useful at the documentation.

A: Replace locale=QLocale() for locale=QtGui.QLocale() in line 27 of your file, because of from PyQt4 import * you must supply the module name..


text:
Q: Monitor local Azure Functions? Is it possible to get Information out of the Azure function SDK?
For example the Function URI. Or the count of Functions running local.
Somthing like Swagger for local Azure Functions would be the goal.
Thanks for your help.

A: I remember trying to use something similar to swashbuckle for Azure Functions, but there was no easy way to integrate it. This may help: AzureFunction Swagger Definition Generator

A: Azure Function's OpenAPI 2.0 support may provide some of the functionality you are desiring. Note that as of April 2018, it is still in preview.


text:
Q: Problem formatting long dates and using GetLocaleInfoEx with LOCALE_SLONGDATE I am getting confused here. According to my Windows 10 Regional Settings the Long Date format is:

I was adjusting some MFC code:
strDate = CFormatUtility::FormatAsLongDate(datToFormat);

So the above calls this method:
CString CFormatUtility::FormatAsLongDate(COleDateTime datDate)
{
    CString strFormattedText;

    TRY
    {
        TCHAR szDateFormatString[_MAX_PATH];
        GetLocaleInfoEx(theApp.GetHtmlLanguageCode(),
            LOCALE_SLONGDATE, szDateFormatString, _MAX_PATH);

        strFormattedText = FormatAsCustomDate(datDate, szDateFormatString);
    }
    CATCH(CException, Except)
    {

    }
    END_CATCH

    return strFormattedText;
}

I don't show you the subsequent method because the issue is here:
    TCHAR szDateFormatString[_MAX_PATH];
    GetLocaleInfoEx(theApp.GetHtmlLanguageCode(),
        LOCALE_SLONGDATE, szDateFormatString, _MAX_PATH);

According to the advanced Windows Settings:

Yet when I use the above code:

As you can see, the format string is dddd, MMMM d, yyyy which is not right.
According to the documentation for LOCALE_SLONGDATE it says:

Long date formatting string for the locale. The maximum number of characters allowed for this string is 80, including a terminating null character. The string can consist of a combination of day, month, year, and era format pictures and any string of characters enclosed in single quotes. Characters in single quotes remain as specified. For example, the Spanish (Spain) long date is "dddd, dd' de 'MMMM' de 'yyyy". Locales can define multiple long date formats.

I should clarify that the value of the first parameter is en.
Update
I see in my Regional settings that there are several types of long date:

But the whole point of this exercise is that I obtain the format string that is in use by the regional settings. And it is not returning that string dd MMMM yyyy.

A: The problem (in my case is that my operating system is English UK. So I had to use a language code of en-gb and then it shows my date format string.


text:
Q: Why d3js exit().remove() don't work? I'm new to d3js, in my understanding.
// links is an array and id is unique key
var pathData = paths.data(links, function(d) {return d.id;});

pathData.enter().append('').attr() ...

// in there will be delete all the duplicate items
pathData.exit().remove();

But in my code, it recreate a node.
Here is my full code http://jsfiddle.net/yunfanyunfan/URpfB/34/
click the line, will appear many lines, because the duplicate node not removes.

A: *

*You need a live copy of the paths selection. Your original code only has the initial snapshot.

*The .attr('d',
needs to be on the UPDATE+ENTER selection because the enter
selection will be zero size since you are re-using the existing path
each time.

// set up SVG for D3
var width  = 960,
    height = 800;

var isWantToAddNode = false;
var svg = d3.select('body').select('svg')
    .attr('width', width)
    .attr('height', height);
var links = [{
    id:1,
    fromPoint: {x:5,y:5},
    toPoint: {x:50,y:50},
    params: 'android',
    color: '#000'
}];
var times = 0;
function initAllDef() {
    svg.select('#defs').append('svg:marker')
        .attr('id', 'arrow').attr("viewBox", "0 -5 10 10")
        .attr("refX", 9)
        .attr("refY", 0)
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
        .append("path")
        .attr("d", "M0,-3L10,0L0,3")
        .attr('fill', '#000');
}

initAllDef();

// handles to link and node element groups
var paths = svg.select('#paths').selectAll('path');
var routeNodes = svg.select('#rects').selectAll('rects');

// update graph (called when needed)
function restart() {
    function rebuildLink() {
        //need a live selection
        var pathData = svg.select('#paths').selectAll('path').data(links, function(d){
            return d.id;
        });
        pathData.enter()
            .append('svg:path')
            .attr('class', 'link')
            .style('marker-end', 'url(#arrow)')
            .on('mousedown', function(d){
                times += 1;
                restart();
            });

        //path needs to be on update+enter
        pathData.attr('d', function(d) {
                var f = d.fromPoint, t = d.toPoint;
                return 'M' + (f.x + times * 10) + ',' + (f.y) + 'L' + t.x + ',' + t.y;
            });

        pathData.exit().remove();
    }

    rebuildLink();
}

function getStartPoint(rect) {
    return {
        x: rect.x + (rect.width>>1),
        y: rect.y + rect.height
    }
}

function getEndPoint(rect) {
    return {
        x: rect.x + (rect.width>>1),
        y: rect.y
    }
}

restart();
svg {
    background-color: #FFF;
    /*cursor: default;*/
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
}

svg:not(.active):not(.ctrl) {
    cursor: crosshair;
}

path.link {
    fill: none;
    stroke: black;
    stroke-width: 2px;
    cursor: default;
}

svg:not(.active):not(.ctrl) path.link {
    cursor: pointer;
}

path.link.selected {
    stroke-dasharray: 10,2;
    color: blue;
    stroke: blue;
}

path.link.dragline {
    pointer-events: none;
}

path.link.hidden {
    stroke-width: 0;
}

circle.node {
    stroke-width: 1.5px;
    cursor: pointer;
}

circle.node.reflexive {
    stroke: #000 !important;
    stroke-width: 2.5px;
}

rect.route-node {
    cursor: pointer;
    stroke-width: 1px;
}

text {
    font: 12px sans-serif;
    pointer-events: none;
}

text.id {
    text-anchor: middle;
    font-weight: bold;
}

input {
    width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body>
    <svg>
        <defs id="defs"></defs>
        <g id="paths"></g>
        <g id="rects"></g>
    </svg>
 </body>

A: In your code you are trying to delete the line that you have created.
//But this is wrong way to delete.
pathData.exit().remove();
//this is the right way
svg.selectAll('path').data(pathData).exit().remove();

Check the updated code:
http://jsfiddle.net/cyril123/ktvkuhta/2/
This should give you a very good insignt on enter and exit: http://bost.ocks.org/mike/circles/


text:
Q: How to add custom view to the layout? I have a GraphicsView class that extends from the View class and I want to add this GraphicsView class to the main layout in my project. How can I do that?
static public class GraphicsView extends View {
        public GraphicsView(Context context) {
        super(context);
        }
        @Override
        protected void onDraw(Canvas canvas) {
        // Drawing commands go here
            Path rect = new  Path();
            rect.addRect(100, 100, 250, 50, Direction.CW);
            Paint cPaint = new Paint();
            cPaint.setColor(Color.LTGRAY);
            canvas.drawPath(rect, cPaint);
        }
    }

and my main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linnnnlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView
        android:id="@+id/Customfont"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

     <View
         android:id="@+id/view"
          android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

A: i finaly got it here is the code
the XML code
<com.customfonts.namespace.BreakDownBar
         android:id="@+id/gview"
          android:layout_width="fill_parent"
        android:layout_height="20dip"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:background="@color/BreakDownBarBack"/>

and the class
package com.customfonts.namespace;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.util.AttributeSet;
import android.view.View;

public class BreakDownBar extends View {

    public BreakDownBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

        @Override
        protected void onDraw(Canvas canvas) {
                //Draw rectangle;
                Path rect = new  Path();
                rect.addRect(0, 0,250, 150,Direction.CW);
                Paint cpaint = new Paint();
                cpaint.setColor(Color.GREEN);
                canvas.drawPath(rect, cpaint);
        }
}

A: you need to do this:
LinearLayout v = (LinearView) findViewById(R.id.linnnnlayout);
GraphicsView myView = new myGraphicsView(this);
v.addView(myView);

A: Because your custom View is an inner class in your Activity the java compiler will output the name ActivityName$GraphicsView for that class. You can't use that name directly as the View name in the xml layout because of the $ character but you can do it like this:
 <view
    class="com.package.here.ActivityName$GraphicsView"
    android:id="@+id/view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

where ActivityName is the name of the activity where your GraphicsView class is declared.

A: You need to give complete path of your class that extends View,
<com.blah.blah.GraphicsView
         android:id="@+id/view"
          android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

A: If I remember correctly, you need to provide more constructors to use view from xml file (add it to xml file like "Me and We" suggested).
public GraphicsView(Context context) {
    super(context);
}

public GraphicsView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public GraphicsView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

Update: fixed code.

A: public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LinearLayout v = (LinearLayout) findViewById(R.id.linearLayout);
    MyGraphics myView = new MyGraphics(this);
    v.addView(myView);
}
}

public class MyGraphics extends View {
public MyGraphics(Context context) {
    super(context);
}

@Override
protected void onDraw(Canvas canvas) {
    // Drawing commands go here
    Path rect = new Path();
    rect.addRect(100, 100, 250, 50, Direction.CW);
    Paint cPaint = new Paint();
    cPaint.setColor(Color.LTGRAY);
    canvas.drawPath(rect, cPaint);
}

}

XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/linearLayout">

<TextView
    android:id="@+id/Customfont"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

</LinearLayout>

A: This is working for me and add the view in XML with full path and try giving wrapcontent for height and width.
public class RectangleView extends View {
    public RectangleView(Context context) {
        super(context);
    }

    public RectangleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RectangleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.GRAY);
        canvas.drawColor(Color.BLUE);
        canvas.drawRect(10,10,50,50, paint);
    }
}


text:
Q: Carrito de compras: no funciona mi función para agregar productos al carrito Estoy haciendo un carrito de compras, sin embargo a la hora de establecer la función para agregar productos al carrito mediante un evento con un botón, me marca el error siguiente:
Uncaught TypeError: productos.find is not a function
at Function.obtenerProducto (scripts.js:126:26)
at HTMLButtonElement.<anonymous> (scripts.js:92:51)

Cada producto tiene un id que se checa a la hora de hacer click sobre el botón.Cabe mencionar que traigo los productos desde un JSON local que llamo mediante una promesa y que son pintados en el HTML :
[
    {
        "id": "1",
        "nombre": "Conchita",
        "precio": "12.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-1.jpg"
    },
    {
        "id": "2",
        "nombre": "Croissant",
        "precio": "13.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-2.jpg"
    },
    {
        "id": "3",
        "nombre": "Pan de Muerto",
        "precio": "13.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-3.jpg"
    },
    {
        "id": "4",
        "nombre": "Baguette",
        "precio": "23.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-4.jpg"
    },
    {
        "id": "5",
        "nombre": "Focaccia",
        "precio": "17.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-5.jpg"
    },
    {
        "id": "6",
        "nombre": "Bolitas de Arándano",
        "precio": "5.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-6.jpg"
    },
    {
        "id": "7",
        "nombre": "Fruit Cake",
        "precio": "14.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-7.jpg"
    },
    {
        "id": "8",
        "nombre": "Chispas de chocolate",
        "precio": "5.99",
        "imgSrc": "../imagenes/imagenes-productos/imagen-productos-8.jpg"
    }
]

Al parecer el error aparece cuando establezco la función obtenerProductos, en la cual uso un método find para recorrer el array. Estoy casi seguro que se trata de un error con el JSON. Aquí está mi código de JS :
// Variables principales
const carritoBtn = document.querySelector (".carrito-btn1")
const carritoContador = document.getElementById ("carrito-contador")
const productosDOM = document.querySelector (".productos-card-container")
const carritoOverlay = document.querySelector (".carrito-overlay")
const carritoDOM = document.querySelector (".carrito-principal")
const carritoCerrar = document.querySelector (".carrito-cerrar")
const carritoContenido = document.querySelector (".carrito-contenido")
const carritoTotal = document.querySelector (".carrito-total")
const carritoVaciar = document.querySelector (".carrito-vaciar")

// Arrays principales
let carrito = []
let botonesDOM = []

// Función para activar contenido del DOM mediante un evento
document.addEventListener ("DOMContentLoaded", () => {
    const productos = new Productos ()
    const desplegar = new Desplegar ()
    // Activar los productos desde el JSON
    productos.activarProductos ().then (resultado => {
    desplegar.desplegarProductos (resultado)
    // Guardar productos en local storage
    Storage.guardarProductos (productos)
    }) .then(() => {
        // Activar botones para agregar productos al carrito
        desplegar.activarBotonesComprar ()
    })
})

// Crear clase "Productos" para cargar productos desde el JSON
class Productos {
    // Utilizo async/await para cumplir la promesa.
    async activarProductos () {
        try {
        let contenido = await fetch ("../farina-rustica-productos.json")
        let resultado = await contenido.json ()
        return resultado;
        } catch (error) {
            console.log (error);
        }
    }
}

// Crear clase "Desplegar" para mostrar los productos cargados por la clase "Productos" o el Local Storage en la página web
class Desplegar {
    desplegarProductos (productos) {
        let productosHtml = ""
        // Utilizo el método forEach para que todas las propiedas de cada producto aparezcan en el HTML
        productos.forEach (producto => {
            productosHtml += `

                        <button class="carrito-btn2" data-id=${producto.id}>

                            Agregar al carrito
                        </button>

${producto.nombre}

$${producto.precio}

            `
        })
        // Utilizo la propiedad innerHTML para mostrar cada producto con sus propiedades en el HTML
        productosDOM.innerHTML = productosHtml
    }
    // Habilitar el uso de los botones para agregar productos al carrito
    activarBotonesComprar () {
        const botonesComprar = [...document.querySelectorAll (".carrito-btn2")]
        botonesDOM = botonesComprar
        botonesComprar.forEach (button => {
            let id = button.dataset.id
            let productoAgregado = carrito.find (item => item.id === id)
            // Si el producto ya está el carrito
            if (productoAgregado) {
                button.innerText = "El producto ya está en el carrito"
                button.disabled = true
            // Si el producto no está en el carrito
            } else {
                button.addEventListener ("click", e => {
                    e.target.innerText = "El producto ya está en el carrito"
                    e.target.disabled = true
                    // Hacer que el boton "agregar al carrito" añada el item con sus características mediante el id
                    let carritoItem = {...Storage.obtenerProducto (id), cantidad: 1}
                    // Agregar el producto al carrito
                    carrito = [...carrito, carritoItem]
                    // Guardar el carrito en local storage
                    Storage.guardarCarrito (carrito)
                    // Número total de items en el carrito y sub-total del carrito
                    this.infoCarrito (carrito)
                    //
                    //
                })
            }
        })
    }
    // Número total de items en el carrito y sub-total del carrito
    infoCarrito (carrito) {
        let totalItems = 0
        let subTotal = 0
        carrito.map (item => {
            totalItems += item.cantidad
            subTotal += item.precio * item.cantidad
        })
        carritoContador.innerText = totalItems
        carritoTotal.innerText = parseFloat (subTotal.toFixed (2))
    }
}

// Crear clase "Storage" encargada del almacenamiento en Local Storage
class Storage {
    static guardarProductos (productos) {
        localStorage.setItem ("productos", JSON.stringify (productos))
    }
    // Hacer que el boton "agregar al carrito" añada el item con sus características mediante el id
    static obtenerProducto (id) {
        let productos = JSON.parse (localStorage.getItem ("productos"))
        return productos.find (producto => producto.id === id)
    }
    // Guardar el carrito en local storage
    static guardarCarrito (carrito) {
        localStorage.setItem ("carrito", JSON.stringify (carrito))
    }
}

A: Diria que el principal problema lo tienes aquí, cuando intentas guardar una instancia de clase en el localStorage:
// Guardar productos en local storage
    Storage.guardarProductos (productos)

pues me temo que deberia ser esto, usando la variable resultado donde realmente se guardan los datos resultantes del método productos.activarProductos() :
// Guardar productos en local storage
    Storage.guardarProductos (resultado)

Ya nos dirás si era eso. En mis pruebas con eso me salto el error.


text:
Q: Can I get an R-square value in a glmmadmb with negative binomial distribution? I used the GLMMadmb function to asses the effect of three fixed factors (and two interactions) and two random factors on the abundance af a specie; my data had a negative binomial distribution. My fixed factors are: size (categorical with 5 levels), size (continous), height (continous) and my random factors: week and patch.
First I ran the model with all interactions and then I removed the non-significant
negbin= glmmadmb(abundance~size + neighbour +height + size*neighbour+ size*height +(1|week) + (1|patch),data=nedyus, family= "nbinom1")

Call: glmmadmb(formula = abundance ~ size + neighbour + height + size *
neighbour + size * height + (1 | week) + (1 | patch), data = nedyus,
family = "nbinom1")
AIC: 2684.1

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)        3.07872    0.65738    4.68  2.8e-06 ***
sizeV             -1.46324    0.88029   -1.66  0.09647 .
sizeIII           -2.86801    0.72962   -3.93  8.5e-05 ***
sizeII            -3.07838    0.79007   -3.90  9.8e-05 ***
sizeI             -3.99529    0.92210   -4.33  1.5e-05 ***
neighbour         -0.03386    0.01267   -2.67  0.00751 **
height            -0.02401    0.00628   -3.83  0.00013 ***
sizeV:neighbour    0.02705    0.02483    1.09  0.27601
sizeIII:neighbour  0.01241    0.01560    0.80  0.42604
sizeII:neighbour   0.03231    0.01416    2.28  0.02248 *
sizeI:neighbour    0.02929    0.01474    1.99  0.04685 *
sizeV:height       0.01405    0.00739    1.90  0.05726 .
sizeIII:height     0.02655    0.00686    3.87  0.00011 ***
sizeII:height      0.01858    0.00788    2.36  0.01838 *
sizeI:height       0.02679    0.00909    2.95  0.00321 **

Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Number of observations: total=976, week=8, patch=122
Random effect variance(s):
Group=week
        Variance StdDev
Intercept)  0.01442 0.1201
Group=patch
        Variance StdDev
(Intercept)   0.4469 0.6685

Negative binomial dispersion parameter: 1.676 (std. err.: 0.10951)

Log-likelihood: -1324.03
Warning message:
In .local(x, sigma, ...) :
  'sigma' and 'rdig' arguments are present for compatibility only: ignored

I want to report this results in my work, but instead of the AIC value iwould also like to have an R-squared value to know how well does the model fit, is there a way to get it?
Any additional observation you can share with me about my model is more than welcome, thank you.

A: First, running the model and removing all that were not significant is not a great method of variable selection. But your table includes ones that are not significant, so it's not clear what you did exactly.
Second, there is no exact equivalent of $R^2$ for models other than linear regression.  In particular, for negative binomial regression. For some ideas on substitutes, see Cameron and Windmeijer. You have the additional complexity of having a multilevel model, I don't know of any work on this particular problem. It's probably possible to generalize what Cameron and Windmeijer did, but I don't know if it's been done.


text:
Q: Accessing Data from a graph on a website using python I have generally wondering if it is possible to access data displayed on graphs such as these: https://coinmarketcap.com/currencies/bitcoin/
I have looked at the .htm file and other links within this, yet none seem to be containing this. Would anyone know how to retrieve and print information from the graph using python?

A: You can retrieve the information from coinmarketcap using their API.
https://coinmarketcap.com/api/
This will allow you to request data from them, sometimes with given parameters (e.g. the currency) and you'll retrieve the data in a JSON format, which  you can then again parse and display with python.
There are plenty of API tutorials out there for python on the web. Good luck!