text:
Q: XPath given by Chrome DevTools could not be found As I was experimenting with some XPath SVG paths while answering another question about Selenium, I found out a strange behaviour with XPath on Chrome (I didn't try on some other browsers).
On http://www.amcharts.com/svg-maps/?map=usa, why doesn't that XPath work?
//*[@id="chartdiv"]/div/div[1]/svg/g[7]/g/g[1]
Whereas this one does?
//*[@id="chartdiv"]/div/div[1]/*[name()="svg"]/*[name()="g"][7]/*[name()="g"]/*[name()="g"][2]

I had to make the following changes:

*

*/g becomes /*[name()="g"]

*/svg becomes /*[name()="svg"]

*/path becomes /*[name()="path"]
The weird thing is that I got the first XPath by right-clicking the element HTML and copied the XPath from there.

I have another example on http://gmsgroup.com/municenter.asp where:

*

*//*[@id='ext-gen203']/*[name()='svg']/*[name()='a']/*[name()='path'][starts-with(@d, 'M136.65')]/.. works,

*//*[@id='ext-gen203']/*[name()='svg']/*[name()='a'][@title='Hawaii'] doesn't.

Here, /*[name()='a'][@title='Hawaii'] couldn't get , why?

A: Namespaces can either be prefixed:
<root xmlns:ns="www.example.com"/>

or default namespaces:
<root xmlns="www.example.com"/>

SVG is in a default namespace. A path expression like /svg tells an XPath processor to look for an element that is called "svg" and that is in no namespace whatsoever. Therefore, this expression only matches:
<svg/>   or <svg xmlns=""/>

Using /*[name()='svg'] does only rule out a prefixed namespace. It still allows for an element that is called "svg" and that is in a default namespace, without a prefix. This second expression matches
<svg xmlns="http://www.w3.org/2000/svg"/>

but not
<ns:svg xmlns:ns="http://www.w3.org/2000/svg"/>

To prove this, consider the following XSLT stylesheet:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="*[name() ='svg']">
        <hit/>
    </xsl:template>

</xsl:transform>

Applied to the following input, a shortened SVG document:
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg"/>

Results in:
<?xml version="1.0" encoding="UTF-8"?>
<hit/>

See for yourself online here.

EDIT (responding to your comment)

More clearly, does it mean that the SVG default namespace overrides the one from the page and therefore doesn't handle expressions such as [@title='Hawaii']?

The HTML elements themselves do not have a namespace - and SVG does not "override" the page's namespace. The default namespace on the svg element only applies to itself and all child elements (including the a[@title='Hawaii'] element inside it.
//*[@id='ext-gen203']/*[name()='svg']/*[name()='a'][@title='Hawaii']should be able to find the a element and I am very surprised it does not.

Where to find the specification for that default namespace?

If you mean default namespaces in general, look here: http://www.w3.org/TR/REC-xml-names/#scoping-defaulting. If you meant the SVG specification, study the following chapter of the SVG specification: http://www.w3.org/TR/SVG/struct.html.

Does it also mean that there isn't a better way of getting  than //[@id='ext-gen203']/[name()='svg']/[name()='a']/[name()='path'][starts-with(@d, 'M136.65')]/..?

The better way to do this is to register or declare those namespaces and thereby make them available for use in Xpath expressions by means of prefixes (as Martin Honnen has pointed out). Chrome Dev Tools is not my field of expertise, I cannot comment on how to do it there.

A: HTML5 and text/html allows you to mix HTML, MathML and SVG elements in one document and does not require you to use the namespaces associated with the different vocabularies. With XPath however you need to make sure you bind a prefix to the SVG namespace and use that prefix in your queries as in the DOM tree the SVG elements are in a different namespace than the HTML elements. Whether that is possible inside the developer tool I don't know but with an API there are usually ways to set up a namespace resolver that maps prefixes you want to use in your XPath expressions to namespace URLs.


text:
Q: Using python requests module to create an authenticated session in Github My goal to create an authenticated session in github so I can use the advanced search (which limits functionality to non-authenticated users).  Currently I am getting a webpage response from the post request of "What? Your browser did something unexpected. Please contact us if the problem persists."
Here is the code I am using to try to accomplish my task.
import requests
from lxml import html

s = requests.Session()
payload = (username, password)
_ = s.get('https://www.github.com/login')
p = s.post('https://www.github.com/login', auth=payload)

url = "https://github.com/search?l=&p=0&q=language%3APython+extension%3A.py+sklearn&ref=advsearch&type=Code"
r = s.get(url, auth=payload)
text = r.text
tree = html.fromstring(text)

Is what I'm trying possible? I would prefer to not use the github v3 api since it is rate limited and I wanted to do more of my own scraping of the advanced search.  Thanks.

A: As mentioned in the comments, github uses post data for authentication so you should have your creds in the data parameter.
The elements you have to submit are 'login', 'password', and 'authenticity_token'. The value of 'authenticity_token' is dynamic, but you can scrape it from '/login'.
Finally submit data to /session and you should have an authenticated session.
s = requests.Session()
r = s.get('https://www.github.com/login')
tree = html.fromstring(r.content)
data = {i.get('name'):i.get('value') for i in tree.cssselect('input')}
data['login'] = username
data['password'] = password
r = s.post('https://github.com/session', data=data)

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP OCI8 Unable to read Unicode chars from NCHAR (Oracle 11g) I'm spending days trying to read Unicode characters (Simplified Chinese names) from an Oracle 11g via PHP7 OCI8 (tried with PDO_OCI and ODBC and in PHP5 as well, same problem) on Linux Ubuntu server 14.04.
This are the Oracle 11g settings:
NLS_LANGUAGE    AMERICAN
NLS_TERRITORY   AMERICA
NLS_CHARACTERSET    WE8MSWIN1252
NLS_SORT    BINARY
NLS_NCHAR_CHARACTERSET  AL16UTF16
NLS_COMP    BINARY
NLS_LENGTH_SEMANTICS    BYTE
NLS_NCHAR_CONV_EXCP FALSE

Important The table column I'm trying to read is defined as NCHAR(40).
I use php-7.0.8 NTS, oci8-2.0.11 (from PECL) and installed Oracle instantclient
This is the php code I'm using:
<?php
$fp = fopen('output.txt','w');
$conn = oci_connect('MYUSER', 'MYPASSWORD', 'xxx.xxx.xxx.xxxx/DBTEST','AL32UTF8');

$query = "SELECT ABALPH FROM CRPDTA.F0101 WHERE ROWNUM <= 1 ORDER BY NULL";
$stid = oci_parse($conn, $query);
oci_execute($stid, OCI_NO_AUTO_COMMIT);

while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
    fwrite($fp, $row['ABALPH']."\n");
}
fclose($fp);
?>

Then I can see English names but I get ¿¿¿¿¿¿¿¿¿¿¿¿¿ into my txt file (UTF8 w/o BOM format) for Chinese names. I think this is related to the NCHAR(40) datatype.
Please, note I've set the Oracle env variables directly (through export and/or putenv()). When I use sqlplus command I can get to export readable Chinese names into a file I set export NLS_LANG ="SIMPLIFIED CHINESE_CHINA.ZHS16GBK"
Any idea about how to solve this? I'd greatly appreciate it!
Regards, Sergio

A: I think I found the solution in this blog post.
Reading the article's comments, basically the NCHAR field needs to be converted to RAW/HEX:
$query = "SELECT UTL_RAW.cast_to_raw(convert(ABALPH,'AL32UTF8')) FROM CRPDTA.F0101 WHERE ROWNUM <= 1 ORDER BY NULL";

If you use oci8 extension in PHP, there is no need to further convert the hex to UTF8 as, according to the post, it's automagically done by PHP. However, if you use PDO_OCI then you need to convert your hex field by using hex2bin() before using it as UTF8 string.
Hope this could help.

A: There is no native support for NCHAR or NCLOB in PHP OCI8 or PDO_OCI.  Many people are using UTF8 nowadays, so they haven't needed N* support.


text:
Q: Remoting plugin for cakephp 2.0 and flex I have a website written in cakephp 1.2 and I'm updating it to cakephp 2.0. This website has a flex front end and I'm using CpAmf plugin for that purpose. It seems like CpAmf plugin has no support with cakephp 2.0 yet. Can anyone recommend me a good remoting plugin for cakephp 2.0 and flex?

A: Although I don't know of anything out there that supports Cake 2.0+, this might be a really good starting point: http://code.google.com/p/flexiblecake/
At first glance, it seems rather simple to build upon.


text:
Q: Is there a way I can make sure that an object created by using my class gets the name that the user assigns to it in java I build a class with the constructor:
public Door(String name){

  this.name = name;
 }

Is there a way where I can create a default constructor where the name becomes whatever the user assigns this object. For example:
{

  Door blackDoor = new Door();
}

Would make the
blackDoor.name = blackDoor?

A: public class Bleh {

    public static void main(String[] args) {
        BlackDoor bd = new BlackDoor();
        System.out.println(bd.name);
    }
}

class Door {
    String name;
    public Door(){
        this.name = this.getClass().getName();
    }
}

class BlackDoor extends Door{
}


text:
Q: VBA Insert Formulas into Table Very Slow I have a workbook that on open, turns the used cells into a table, and then injects different formulas into each column. I'm injecting the formulas to save file size from exploding by pre-dragging formulas down farther than needed. The VBA I have to do this works fine, but is incredibly slow. I've already run performance checks and can confirm that the slowness is caused by the formula injection (only 141 rows can be injected per second). I have already done the basic calculation/screen update related optimizations. What else can be done to speed up the following code? (Note I have reduced to the relevant portion of the code):
Sub OptimizeVBA(isOn As Boolean)
  Application.Calculation = IIf(isOn, xlCalculationManual, xlCalculationAutomatic)
  Application.EnableEvents = Not(isOn)
  Application.ScreenUpdating = Not(isOn)
  ' ActiveSheet.DisplayPageBreaks = Not(isOn)
End Sub

Private Sub Workbook_Open()
    OptimizeVBA True

    Dim ws As Worksheet
    Set ws = Worksheets("Book1")
    Dim tbl As ListObject
    Set tbl = ws.ListObjects("Table1")

    tbl.ListColumns("Dollar Share ").DataBodyRange.Formula = "=IFERROR(([@[Dollar Share  ]] - MEDIAN([[Dollar Share  ]])) / STDEV.P([[Dollar Share  ]]), """")"
    tbl.ListColumns("Unit Share ").DataBodyRange.Formula = "=IFERROR(([@[Unit Share  ]] - MEDIAN([[Unit Share  ]])) / STDEV.P([[Unit Share  ]]), """")"
    tbl.ListColumns("Units PSPW ").DataBodyRange.Formula = "=IFERROR(([@[Units PSPW  ]] - MEDIAN([[Units PSPW  ]])) / STDEV.P([[Units PSPW  ]]), """")"
    tbl.ListColumns("Dollar Growth ").DataBodyRange.Formula = "=IFERROR(IF(OR([@[Dollar Growth  ]] = """", [@[Dollars, Yago]] < New_Item_Floor), """", ([@[Dollar Growth  ]] - MEDIAN([[Dollar Growth  ]])) / STDEV.P([[Dollar Growth  ]])), """")"
    tbl.ListColumns("Unit Growth ").DataBodyRange.Formula = "=IFERROR(IF(OR([@[Unit Growth  ]] = """", [@[Dollars, Yago]] < New_Item_Floor), """", ([@[Unit Growth  ]] - MEDIAN([[Unit Growth  ]])) / STDEV.P([[Unit Growth  ]])), """")"
    tbl.ListColumns("Comp Avg % ACV ").DataBodyRange.Formula = "=IFERROR(([@[Comp Avg % ACV  ]] - MEDIAN([[Comp Avg % ACV  ]])) / STDEV.P([[Comp Avg % ACV  ]]), """")"

    OptimizeVBA False
End Sub

I'm aware that selects/other interactions with Excel objects are expensive, but given that the above formulas are different, I couldn't figure out an easy way to reduce the separate interactions for each column.
Notes:

*

*There are actually more injections than shown above, with different formulas of roughly equal string length.

*On average tbl will have 16k rows.

Thanks in advance for the help!

A: I'll provide you with my tests here, as this is too much code for comments.
I changed your code in order to paste formulas directly. I tested as strings (due to lack of your table setup) and it is basically immediate. So there must be some table-related shenanigans happening. Please try in your table. You will just need to adjust ranges/worksheet to your needs:
Private Sub Workbook_Open()
    OptimizeVBA True

    Dim ws As Worksheet
    Set ws = ActiveSheet

    ws.Range("A2:A200000").Formula = "=IFERROR(([@[Dollar Share  ]] - MEDIAN([[Dollar Share  ]])) / STDEV.P([[Dollar Share  ]]), """")"
    ws.Range("B2:B200000").Formula = "=IFERROR(([@[Unit Share  ]] - MEDIAN([[Unit Share  ]])) / STDEV.P([[Unit Share  ]]), """")"
    ws.Range("C2:C200000").Formula = "=IFERROR(([@[Units PSPW  ]] - MEDIAN([[Units PSPW  ]])) / STDEV.P([[Units PSPW  ]]), """")"
    ws.Range("D2:D200000").Formula = "=IFERROR(IF(OR([@[Dollar Growth  ]] = """", [@[Dollars, Yago]] < New_Item_Floor), """", ([@[Dollar Growth  ]] - MEDIAN([[Dollar Growth  ]])) / STDEV.P([[Dollar Growth  ]])), """")"
    ws.Range("E2:E200000").Formula = "=IFERROR(IF(OR([@[Unit Growth  ]] = """", [@[Dollars, Yago]] < New_Item_Floor), """", ([@[Unit Growth  ]] - MEDIAN([[Unit Growth  ]])) / STDEV.P([[Unit Growth  ]])), """")"
    ws.Range("F2:F200000").Formula = "=IFERROR(([@[Comp Avg % ACV  ]] - MEDIAN([[Comp Avg % ACV  ]])) / STDEV.P([[Comp Avg % ACV  ]]), """")"

    OptimizeVBA False
End Sub

Your question from comments: how you could use autofill for such a task:
Sub autof()
    Cells(1, 1).Value = 1
    Cells(1, 2).Value = 2
    Range(Cells(1, 1), Cells(1, 2)).AutoFill Range(Cells(1, 1), Cells(10, 2)), xlFillCopy
End Sub

A: One source of the slowness could be the use of the MEDIAN function --- it's more expensive/slow to calculate than AVERAGE.
In quick and dirty testing on my hardware using 16K rows of fake date and with Calculations, Events and ScreenUpdating all Enabled (no speedups), your formula
=IFERROR(([@[Dollar Share  ]] - MEDIAN([[Dollar Share  ]])) / STDEV.P([[Dollar Share  ]]), "")

took 5.4 seconds to execute, but when AVERAGE is used instead of MEDIAN
=IFERROR(([@[Dollar Share  ]] - AVERAGE([[Dollar Share  ]])) / STDEV.P([[Dollar Share  ]]), "")

it ran in 0.8 seconds, a speed-up of ~6.6X.
The problem is compounded by the fact that the same MEDIAN and STDEV.P get (wastefully) recalculated 16K times (once for each row of the table). It doesn't appear that the Excel calculation engine optimizes for this. You should be able to speed up your tables by calculating these values ONLY ONCE and then re-using.
One way to do this is to add a Totals row to the table and use MEDIAN as the total function. Then if your code is:
Sheet1.ListObjects("Table1").ListColumns("Dollar Share ").DataBodyRange.Formula = "=IFERROR(([@[Dollar Share  ]] - Table1[[#Totals],[Dollar Share  ]]) / STDEV.P([[Dollar Share  ]]), """")"

the run time gets reduced to 0.52 seconds, a 10X improvement. You could also have helper cells on your worksheet to hold all of the MEDIAN and STDEV.P values; this should give an even greater speed-up.
Hope that helps.

A: You can try to calculate dynamically the last row, if you ignore in advance its value, and so try to apply the formula to active cells and then autofill the formula to this last row of the specified column.
  Sub ExtendFormula()
  .
  .
  Dim Limit As Long 'Instead of Integer : Thanks to BigBen for it's recommendation
  Application.ScreenUpdating = False
  Limit = Range("A" & Rows.Count).End(xlUp).Row
  Range("B5").Formula = "=A5+2*B5"
  Range("B5").AutoFill Destination:=Range("B5:B" & Limit)
  .
  .
  End Sub

Hope that can help you


text:
Q: React Native Fetch Return Network Request Failed I am developing a simple app using React Native. I am testing it on Genymotion Android Emulator. I have created local web server to listen to the requests, it is running at http://localhost:8082/API/.
I have tested the api and is working right. Then I make a fetch request from index.android.js.
here's the API sample request from the React Native code :
var api = { getUser(){
        var url = "http://127.0.0.1:8082/API/";
        return fetch(url)
            .then((res) => res.json())
            .catch(
                (error)=>{
                    console.log('error' + error.message);
                    throw error;
                }
            );
    }
}
module.exports = api;

here's the code from Api Server (built with flightPHP)
Flight::route('GET /',function(){
try{
$db = new PDO('mysql:host=localhost;port=3307;dbname=testapp', 'root','');
    $stmt = $db->prepare("SELECT * FROM user LIMIT 1");
    $stmt->execute();
    header('Content-type: application/json');
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

    $db = null;

}catch(Pdoexception $e){
    echo $e->getMessage();
}
});

after execute this call i receive  Network Request Failed(). it seems android simulator not recognized the api url. any suggestion ? thanks before

A: i already solved. just change the API url var url = "http://127.0.0.1:8082/API/ in the React Code. to var url = "http://local-ip-address:8082/API/
to check your local ip just run ipconfig from command line / cmd

A: You can use ngrok to overwrite network requests.
Android is an emulator, and when you fetch 127.0.0.1, it goes to the local phone.
ngrok will create a link that is accessible from the web and redirect to the local web server.


text:
Q: Separating mySQL server from LAMP and performance degradation I'm currently using LAMP stack (over Centos 6.5) for our sites, and I want to try separating the mySQL from the "web server".
Until now I was using DigitalOcean's VPS with quad core CPU and 8GB of RAM.
Yesterday I've created a new DigitalOcean VPS for a single staging environment (at the moment) with the following specs and utils:

*

*2 CPU cores

*2GB RAM

*Centos 6.7

*Private network with the "web server" (Ping time: min/avg/max/mdev = 0.352/0.481/0.662/0.073 ms

*mySQL 5.6 (same as it was on the current server)

*Same my.cnf configuration with 2 changes:

*

*Added: bind-address=X.X.X.X (the private network's internal IP address)

*Changed innodb_buffer_pool_size from 2GB to 1GB (because we have less RAM now..)

The web server is running a Drupal site, and has APCu, opCACHE and memcached installed.
When checking the load time with Chrome it seems that the site is now being loaded slower in about 0.5 - 1.5 sec.
Unfortunately NewRelic proves me right (see the attached screenshot)

Since this is the first time I'm configuration a remote mySQL server, I'm wondering if this is something I've missed? any configuration or adjustment that may improve the performance?

A: I'm not sure why you'd be surprised since your MySQL server has less RAM assigned to it, and placing it on a different machine adds load on the network interface.
You should monitor your network activity to see if it causes any kind of bottleneck.
Depending on your SQL queries and PHP scripts, there could possibly be ways to better optimize those tasks in terms of query performance as well as improving the results sent back to PHP to reduce the network load.

A: A Few Things I will recommend:
Verify if the website is utilizing Memcached/APC/opcode caching.
I would recommend Memcached for DB query caching.
Do a few tweaks on Mysql configuration using mysqltuner.pl

Optimize memcached apc configuration
Memcached configuration file location in Debian/Ubuntu based OS:

/etc/memcached.conf

Memcached Configuration file in Centos/RHEL based OS:

/etc/sysconfig/memcached

Apc configuration can be inserted in php.ini.
Following these steps should definitely increase performance.
And use NewRelic APM to reveal data about where time is being spent.
If the networking is an issue I guess there's nothing you can do about it.
Let me know.
Thanks,
Shahriar

A: I managed to solve the problem, and I think that the way I've gone through may be helpful to others.

*

*Check the latency between the servers using ping, mtr and traceroute to find out if the problem is latency related

*Check the server's load and free RAM, using top (or htop) and free -m

*Run heavy query on both mysql servers (old local and the new remote) and compare the query time, we may also use mySQL's profiling - see SHOW PROFILE

*Assuming that the mysql query time is similar (or at least almost similar), then we may use PHP snippet to run the same code and see maybe the bottleneck is PHP related - I recommend using NewRelic PHP application profiling - in my case, this was the "enlightenment", since eventually I saw that the problem was not even related to the remote mySQL, but the extra 0.5-1.5 seconds were caused by an additional call to a 3rd party service (only when using the remote DB..)

*Use mysqltuner.pl (as @Shahriar Shojib) suggested, and find if there are some mySQL configuration tweaks that we must have (none on my case..)

*Try disabling iptables or any other firewall

*Check the network traffic (I used iptraf and our 3rd party monitoring services), but there are some other options as @Julie Pelletier suggested

Extra performance boost when using remote mySQL server

*

*Use memcached, APCu and Opcode caching (although all those were already installed on our case - those are game changers..)

*Last but not least - Use SSH tunnel instead of direct connection to the mySQL server (seems like it's saving about 200 ms on the overall page load time)
Hope that reading this answer will save you more than 0.5 to 1.5 seconds :)


text:
Q: Godep with local packages I have a repository that looks like this:
src
|
|--myplace
   |--myprojectRepo
      |--someCmd
      |      main.go
      |--somePackage
      |      package.go

I'm trying to use Godeps to manage dependencies.  However, when I run godep save inside of the someCmd folder, it copies not just the external code into the godep _workspace, but also the somePackage code into the godep _workspace.
Is there anyway to stop godep from copying code that is in the same repository into its _workspace?
The main ugliness that I see with this is that now there are  two versions of somePackage.go. One in the somePackage directory and one in the godeps/_workspace... directory.  And if I make a change to somePackage, I have to rerun godep inside of someCmd in order to have those changes pulled in.

A:
when I run godep save inside of the someCmd folder

Godep will vendor everything that is not a sub-directory, it does not goes up to your repository's root.
You have to run godep save ./... from the root of your project : it will save all external dependencies for your project in one place.
As @JimB said, anyway people are gonna be pulling the whole repository at once, not sub-packages by sub-packages. And they should run godep restore from the repository's root too.


text:
Q: php api rest does not accept cors requests even using header ('Access-Control-Allow-Origin: *'); I'm creating an angular application 6 and api rest in php.
when my angular application tries to perform a request the following url: http://localhost/bdevApi/api/index/categoryexame?page=1
the following error is loaded:

Failed to load Response to preflight request doesn't pass access
  control check: No 'Access-Control-Allow-Origin' header is present on
  the requested resource. Origin 'http://localhost:4200' is therefore
  not allowed access.

The angle is in port 4200 and my api is in 80
I visualized some tutorial and added the following header to my api
api/index.php
  <?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

    include("config/config.php");
    include("import/Interpreter.php");
    include("import/SendJson.php");
    include("database/Connection.php");
    include("import/AuthToken.php");

    $db = Connection::getInstance();

    if( $db->getStateConnection() )
    {
        $arrayHeader = getallheaders();
        $token = isset($arrayHeader["token"]) ? $arrayHeader["token"] : "";

        // Recupera dados via Json
        $strJson = file_get_contents('php://input'); //echo $strJson;
        $jsonObject = json_decode($strJson); //var_dump($strJson);

        $Interpreter = new Interpreter(
            "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
            $_SERVER['REQUEST_METHOD'],
            $jsonObject
        );

        if(AuthToken::validateToken($token))
            $Interpreter->initializes(true);
        else
        {
            if($token == "")
                $Interpreter->initializes(false);
            else
            {
                $S = new SendJson();
                $S->Send("200", "1", "Token não autenticado", null);
            }
        }
        $db->closeConnection();
    }

    ?>

How do I get my application to accept these headers and not show this error?
[EDIT]
[]1
new error

Failed to load
  http://localhost/bdevApi/api/index/categoriaexame?page=1: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:4200' is therefore not allowed
  access.

A: This is happening because of cross origin policy. You can go through this document to get the details knowledge about CORS:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control
You can try this code below:
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}


text:
Q: Default checked radio not changing the checked attribute on change of selection I have a radio group having Male and Female as options. Depending on what is stored in database i am having a default checked radio button.

Now over inspect element i am getting what i needed :

But when i select female lets say, the JQuery is still taking the value of Male radio.
$("input[name=detail-gender]").val();

It is giving me value "M" even if i select Female, in that case it should have resulted in "F".
$("input[name=detail-gender]").change(function() {
    alert($("input[name=detail-gender]").val());
});

A: You should use :checked selector
$("input[name=detail-gender]:checked").val();


text:
Q: jQuery - replace thumbnail image with fullsize and smoothly animate the transition and scale I have a wordpress page where I want to display a thumbnail image which when clicked, is replaced with the fullsize image and scales up smoothly to the new full size. My wordpress function is able to output the src, width and height for both the thumbnail and the fullsize.
I have tried two solutions to this problem:
1) Thumbnail is wrapped in link to full-size - http://jsbin.com/inuxej/8
2) Thumbnail is next to hidden (display: none) full-size - http://jsbin.com/ogasic
They both work but the transition is not smooth. I'm not quite sure how I can achieve a smooth scaling from the thumbnail to the fullsize. Does anyone have an idea how I can make this transition smooth so once the thumbnail is clicked, the fullsize is loaded and then the whole box animates and scales up to the full size?
Many many many thanks in advance!
--
Attempt 1:
JSBIN:
http://jsbin.com/inuxej/8
Javascript:
$(document).ready(function(){

// random resize images
$('.portfolio-image img').each(function() {
  var currWidth = $(this).attr("width");
  var currHeight = $(this).attr("height");

  $(this).removeAttr("width");
  $(this).removeAttr("height");

  var transformScale = (Math.floor(Math.random()*60 + 40))/100;

  $(this).width(Math.floor(currWidth*transformScale));
  $(this).height(Math.floor(currHeight*transformScale));
});

// portfolio images - make bigger on click
$('.portfolio-image a').click(function(e) {
  e.preventDefault();

  var smallImageSrc = $(this).children('img').attr("src");
  var bigImageSrc = $(this).attr("href");

  $(this).children('img').removeAttr("width");
  $(this).children('img').removeAttr("height");
  $(this).children('img').attr("src", bigImageSrc);

  $(this).children('img').load(function(){
    $(this).removeAttr("style");
    $('#ajax-loader').fadeOut();
  });
});

});

HTML:
  <!DOCTYPE html>

<meta charset=utf-8 />
<title>JS Bin</title>

I have also tried an alternate solution where wordpress outputs both images and the fullsize is hidden. However, this seems to also cause a problem as jquery seems to obtain dimension values as undefined as the object is set to display: none.
Attempt 2:
JSBIN: http://jsbin.com/ogasic
Javascript:
$(document).ready(function(){

// random resize images
$('.portfolio-image img').each(function() {
  var currWidth = $(this).attr("width");
  var currHeight = $(this).attr("height");

  $(this).removeAttr("width");
  $(this).removeAttr("height");

  var transformScale = (Math.floor(Math.random()*60 + 40))/100;

  $(this).width(Math.floor(currWidth*transformScale));
  $(this).height(Math.floor(currHeight*transformScale));
});

// portfolio images - make bigger on click
$('.portfolio-image').click(function() {

$(this).attr("width", $(this).children(".portfolio-image-display").attr("width"));
$(this).attr("height", $(this).children(".portfolio-image-display").attr("height"));

var bigImageSrc = $(this).children(".portfolio-image-full").attr("src");
var bigImageWidth = $(this).children(".portfolio-image-full").attr("width");
var bigImageHeight = $(this).children(".portfolio-image-full").attr("height");

$(this).children('.portfolio-image-display').attr("src", bigImageSrc);

$(this).children('.portfolio-image-display').load(function(){
    $(this).animate({
        height: bigImageHeight,
        width: bigImageWidth
    }, 1000, function() {
        //after
    });
});
    });

});

HTML:
<!DOCTYPE html>

<meta charset=utf-8 />
<title>JS Bin</title>

A: Once the users clicks the thumbnail, you could replace the thumbnail with the full image, scaled down to the thumbnail's size (make sure it's loaded before replacing). You then animate the transition to the full size using jQuery's animate().
You can alternatively only replace the paths in the src="" attribute (after preloading the full image) and then animate the size.

A: OK, I was able to figure it out using an element from this previous question:
How to get image size (height & width) using JavaScript?
The big trick was to create a javascript copy of the image and when that loads, to find the height and width of that image and then change the sources and animate.
Thank you for the help hupf.
$('.portfolio-image').click(function() {

        var $clickedBox = $(this);

        var bigImageSrc = $(this).children(".portfolio-image-full").attr("src");

        var img = new Image();
            img.onload = function() {
            newWidth = this.width;
            newHeight = this.height;

            $clickedBox.children('.portfolio-image-display').attr("width", "100%");
            $clickedBox.children('.portfolio-image-display').attr("height", "100%");
            $clickedBox.children('.portfolio-image-display').attr("src", bigImageSrc);

            $clickedBox.children('.portfolio-image-display').animate({
                height: newHeight,
                width: newWidth
            }, 500, function(){
                // callback
            });
        }

        img.src = bigImageSrc;
    });


text:
Q: onclick recyclerview fragment kotlin Following Code works perfectly on Activity but not on fragment
class MyProjects(view: View) : RecyclerView.ViewHolder(view) {
    init {
        view.setOnClickListener { println("Test") }
    }

    var partyname = view.findViewById<TextView>(R.id.txtBorn)
    var service = view.findViewById<TextView>(R.id.txtFirst)
    var status = view.findViewById<TextView>(R.id.txtLast)

    fun bind(b: String, f: String, l: String) {
        partyname.text = b.toString()
        service.text = f.toString()
        if (l == "completed") {
            status.text = "C"
            status.setTextColor(Color.parseColor("#bdbdbd"))
        } else {
            status.text = l.toString()
        }
    }
}

I am new to Kotlin…


text:
Q: Meteor collection undefined despite having the files in a lib directory After looking at the various comments on the net, most of which say, "put them in the lib directory", I'm still at a loss as to where to put my collections js files.  It seems no matter where I put them there is an issue. I've tried them in the client directory, lib directory, lib/collections directory. All to no avail. What else could I be missing.
import { Mongo } from 'meteor/mongo';
export const Subjects = new Mongo.Collection('subjects');

A: The immediate issue was in the way I was importing.  I had:
import Subjects from '../../../../lib/collections/subjects.js';

but the following fixed it:
import {Subjects} from '../../../../lib/collections/subjects.js';


text:
Q: Подключение двух мониторов к ноутбуку Всем привет! Хочу подключить два абсолютно одинаковых монитора к ноутбуку, ноутбук Lenovo Y470, на ноутбуке есть два разъема HDMI и VGA, мониторы вот эти LG 19 Flatron E1942C-BN, у этого моника скорее всего только VGA разъем. Подскажите, пожалуйста, получится ли подключить?
A: Скорее всего никак. Работать будет только один+ монитор самого ноутбука.т.к.  это стандартные настройки.
A: Если интересует возможность работы двух дополнительных мониторов - то вполне возможно, надо смотреть на железке...Если интересует как подключить VGA-моник к HDMI-порту - то можно использовать, например, ЭТО.
A: можно с VGA SPLITTER


text:
Q: Compilation issue ( cc1: error: unrecognized command line option "-ip" ) I'm having trouble while compiling certain python modules. The setup fails with the following error:
cc1: error: unrecognized command line option "-ip"
error: Setup script exited with error: command 'gcc' failed with exit status 1

I am on a shared system and do not have root access. So, I install the modules using:
easy_install --prefix=$HOME/local <module_dir>

I looked this up on google and SO but have found no concrete solution yet. From what I understand, it has to do something with the compiler settings/configuration.
I would really appreciate if you could guide me through the steps required to resolve this. I have encountered the same issue with several python modules(pygame, crypto, etc) while most others installed without any hiccups.
Thank You!


text:
Q: black background in png image in chrome I have a trouble with displaying my .png images in Chrome - background is black instead of transparent. In Firefox everything is ok.
What can i do to fix this bug? I tried to write some CSS rules like "background-color: transparent" but nothing changed.

A: You need to force the background to not be transparent by setting it. This seems to be an issue only with Chrome.
"


text:
Q: How to store large number of images in server for easy retrieval in html page? Please Try to Understand my curiosity
Suppose there is a web application that has mannny users. Each user can upload hundreds
of images and after logged in to his/her account can see those images according to his
will.
E.g - The social networking sites like Facebook.
So what my Question is

*

*How do they store so many images in their servers ?

*

*in database as BLOB data ? OR

*in dedicated folders in server for each user ?

*If I choose to use database then

*

*Should I retrieve the images from database, copy them into a temporary folder in server and
get the images through <img src='/serverpath/image '> tag for each session ?
So How do they store and retrieve ?
Now in my application there are user details(without photos) and whenever I click on "view image"
link the photo should appear without page refresh. How can I achieve this using Java as per my above concerns regarding storage and retrieval ?

A: save in a folder , save the path to database . at the time of retrieval read path from db and place the src accordingly

A: Save image in a folder, rename image to add some user specified id ect. to picture, so you cant have two picture with same id. Then save path in to database.
I would suggest to use something like ImageMagick to do the image saving to folder. It can change the name of image and if you want you can change it format and size.
When you want to show pictures to user just get that path from a database, wich have that specified user id to show pictures wich belongs to user.
Saving images directly to database is not good choice if you really have millions pictures like facebook have.
And I dont think you can do that image appearing with java, I suggest using javascript and ajax for it. Check this page for help, http://www.w3schools.com/ajax/ajax_example.asp


text:
Q: PHP Exceptions - try/catch necessary? I started using "real" Exceptions instead of custom error-functions.
I think I don't need a try/catch-block everytime and its okay just to throw an exception but now I get an fatal error because of these uncaught exceptions.
Everything works fine when I set error_reporting(0) but I want to avoid errors at all. Does anyone know an alternative to try/catch or how to throw an exception without getting an fatal error?
Thanks in advance!

A: You can use set_exception_handler() for that and handle any uncaught exceptions yourself.
The callback that you register will receive the exception as its first and only argument. Registering a dummy function is possible, however:

*

*In a production environment it's recommended to log the exception instead of muffling it; this way you can keep track of exceptions that you didn't expect.

*The script execution halts after your handler is done.


text:
Q: better way to duplicate a layer using ogr in python? I'm splitting a large shapefile into many smaller ones using ogr.  I'd like to just copy all of the field and layer config information from the original.  Here's how I'm doing it now:
src = ogr.Open('original.shp', 0)
layer = src.GetLayerByIndex(0)
driver = ogr.GetDriverByName('ESRI Shapefile')
ds = driver.CreateDataSource('file1.shp')
dest_layer = ds.CreateLayer('layer1',
                            srs = layer.GetSpatialRef(),
                            geom_type=layer.GetLayerDefn().GetGeomType())
feature  = layer.GetFeature(0)
[dest_layer.CreateField(feature.GetFieldDefnRef(i)) for i in range(feature.GetFieldCount())]

Is there a more succinct way to do this?

A: Use Fiona of Sean Gillies , a very simple wrapper of the OGR library (The Fiona User Manual)
All the elements of a shapefile (schema, records) are processed using Python dictionaries:
schema of one of my shapefiles as example:

{'geometry': 'LineString', 'properties': {u'faille': 'str:20', u'type': 'str:20', u'id': 'int'}}

one record in the shapefile:

{'geometry': {'type': 'LineString', 'coordinates': [(269884.20917418826, 151805.1917153612), (270409.89083992655, 153146.21637285672), (272298.05355768028, 154047.38494269375), (272941.74539327814, 155484.96337552898), (272169.31519056071, 156117.92701386689)]}, 'id': '1',  'properties': {'faille': u'de Salinas', 'type': u'normale'}}

so to duplicate a shapefile:
from shapely.geometry import mapping, shape
import fiona
# Read the original Shapefile
with fiona.collection('original.shp', 'r') as input:
    # The output has the same schema
    schema = input.schema.copy()
    # write a new shapefile
    with fiona.collection(''file1.shp', 'w', 'ESRI Shapefile', schema) as output:
        for elem in input:
             output.write({'properties': elem['properties'],'geometry': mapping(shape(elem['geometry']))})

If you want to split a large shapefile into many smaller ones, everything takes place in the for loop but all the schemas of the original shapefile are preserved in the dictionary with schema = input.schema.copy() and {'properties': elem['properties']
see How do I find vector line bearing in QGIS or GRASS? for an example of

*

*spliting a shapefile

*preserve the attributes of the original shapefile in the splitted shapefile

*and add a new field in the splitted shapefile

For Mac OS X or Linux users, it is easy to install. For Windows users, use the version of  Christoph Gohlke Unofficial Windows Binaries for Python Extension Packages

A: For those who struggle to install the libraries above:
import shapefile

r = shapefile.Reader('original') # original shp file
w = shapefile.Writer()

w.fields = list(r.fields)
w._shapes.extend(r.shapes()) # copy over geometry without any changes
w.save('new_shp_file')


text:
Q: How to left align the \dcase to make a straight margin with text I am using dcase to express my equation. However, the equation looks align in center of page. I want to move the equation in the left side of the page. Note that, my text has one space at the beginning of paragraph

\documentclass[preprint,12pt, sort&compress]{elsarticle}

\usepackage{amsmath,math tools}

\newcommand{\diff}{\mathop{}\!d}
\DeclareMathOperator*{\argmin}{arg\,min}

\begin{document}

\begin{equation}
\begin{dcases}
u_j^{k+1}(x)=
  \!\begin{multlined}[t]
  \argmin_{u}
  \biggl\{
  \frac{\mu}{2}\int\limits_{\Omega} (u_j(x)-m(x))^2\diff x \biggr\},
  \end{multlined}
\\[1ex]
f'(x_{0})=0 : z=f(x_{0}) \text{ is de horizontale raaklijn.}
\\[1ex]
\lim_{x\to x_{0}} f'(x)=\pm\infty : x=x_{0} \text{ is de verticale raaklijn.}
\\[1ex]
g(x_{0}){R}_{0} : z-f(x_{0})=f'(x_{0})\cdot(x-x_{0})
  \text{ is de raaklijn.}
\end{dcases}
\end{equation}

This is text.
\end{document}

A: Like this?

\documentclass[12pt]{elsarticle}
\usepackage{mathtools}

\newcommand{\diff}{\mathop{}\!d}
\DeclareMathOperator*{\argmin}{arg\,min}
\usepackage{showframe}

\begin{document}

\begin{flalign}
\begin{dcases}
u_j^{k+1}(x)=
  \argmin_{u}
  \biggl\{
  \frac{\mu}{2}\int_{\Omega} (u_j(x)-m(x))^2\diff x \biggr\},
                                \\[1ex]
f'(x_{0})=0 : z=f(x_{0}) \text{ is de horizontale raaklijn.}
                                \\[1ex]
\lim_{x\to x_{0}} f'(x)=\pm\infty : x=x_{0} \text{ is de verticale raaklijn.}
                                \\[1ex]
g(x_{0}){R}_{0} : z-f(x_{0})=f'(x_{0})\cdot(x-x_{0})
  \text{ is de raaklijn.}
\end{dcases}&&&
\end{flalign}

This is text.
\end{document}

Edit: You can also use equation environment and before dcases add \hspace{-}. However, <dsired shift> can be determined by trial and errors ... This at flalign environment is not needed. There equation start at left text border. Of course, in real aplication you had to omit package showframe.
I also corect the MWE according to comment of Barbara Beeton and Mico.


text:
Q: Field Properties and Text into Existing Table within Header in Word I am able to update the header of a document with text and field properties with the code below
  Dim myRange As Range
        With ActiveDocument
            Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
            .Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="STYLEREF  Title", PreserveFormatting:=True
            myRange.Collapse wdCollapseStart
            myRange.Text = ""
             myRange.ParagraphFormat.Alignment = wdAlignParagraphRight
               Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
        myRange.Collapse wdCollapseEnd
        myRange.InsertParagraphAfter
        myRange.Collapse wdCollapseEnd
    myRange.Text = "Name: "
        myRange.Collapse wdCollapseEnd
        .Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="Name_1", PreserveFormatting:=True
    myRange.Fields.Update
    Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
        myRange.Collapse wdCollapseEnd
        myRange.InsertParagraphAfter
        myRange.Collapse wdCollapseEnd
        .Fields.Add Range:=myRange, Type:=wdFieldDate, PreserveFormatting:=True
        myRange.Collapse wdCollapseStart
            myRange.Text = "Date: "
        myRange.Fields.Update
      myRange.ParagraphFormat.Alignment = wdAlignParagraphRight

               Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
        myRange.Collapse wdCollapseEnd
        myRange.InsertParagraphAfter
        myRange.Collapse wdCollapseEnd
    myRange.Text = "Page: "
        myRange.Collapse wdCollapseEnd
                   .Fields.Add Range:=myRange, Type:=wdFieldPage, PreserveFormatting:=True
    myRange.Fields.Update
        Set myRange = .Sections(1).Headers(wdHeaderFooterPrimary).Range
       myRange.Collapse wdCollapseEnd
    myRange.Text = " of "
    myRange.Collapse wdCollapseEnd
                 .Fields.Add Range:=myRange, Type:=wdFieldNumPages, PreserveFormatting:=True
        myRange.Collapse wdCollapseEnd
                 myRange.ParagraphFormat.Alignment = wdAlignParagraphRight
    myRange.Fields.Update

End With

I've tried to place the Text and Field Codes from the above code into the cell of an existing table(Row 1, Column 2) within the header section of the word doc using variations of the code below.
Dim MyRange As Range
With ActiveDocument
Set MyRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary). _
Range.Tables(1).Cell(1, 2).Range
MyRange.Collapse wdCollapseStart
MyRange.Fields.Add Range:=MyRange, _
               Type:=wdFieldEmpty, _
               Text:="STYLEREF  Title", _
                             PreserveFormatting:=True
MyRange.InsertParagraphAfter

Set MyRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary). _
Range.Tables(1).Cell(1, 2).Range
MyRange.Collapse wdCollapseEnd
MyRange.Text = "Name: "
MyRange.Collapse wdCollapseEnd
MyRange.Fields.Add Range:=MyRange, _
               Type:=wdFieldEmpty, _
               Text:="Name_1", _
                             PreserveFormatting:=True
Set MyRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary). _
Range.Tables(1).Cell(1, 2).Range
MyRange.Collapse wdCollapseEnd
MyRange.Text = "Date: "
MyRange.Collapse wdCollapseEnd
MyRange.Fields.Add Range:=MyRange, _
               Type:=wdFieldDate, _
                             PreserveFormatting:=True
Set MyRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary). _
Range.Tables(1).Cell(1, 2).Range
MyRange.Collapse wdCollapseEnd
MyRange.Text = "Page: "
MyRange.Collapse wdCollapseEnd
MyRange.Fields.Add Range:=MyRange, _
               Type:=wdFieldPage, _
                             PreserveFormatting:=True
MyRange.InsertParagraphAfter
Set MyRange = ActiveDocument.Sections(1). _
Headers(wdHeaderFooterPrimary). _
Range.Tables(1).Cell(1, 2).Range
MyRange.Collapse wdCollapseEnd
MyRange.Text = "Num Page: "
MyRange.Collapse wdCollapseEnd
MyRange.Fields.Add Range:=MyRange, _
               Type:=wdFieldNumPages, _
                             PreserveFormatting:=True
MyRange.InsertParagraphAfter

The error "This is not a Valid Action for End of Row" appears. It seems to be tied to the "wdCollapseEnd" command and I am unable to retain the desired appearance of the text and field properties. I've been tackling this in little bites, but I would like to have the code overwrite the existing values of the cell (Row 1,Column 2) of the table within the header of my document. Any help would be greatly appreciated.


text:
Q: Python Real time Audio Visualizer but without the graphs **Edit I got my solution from
https://www.swharden.com/wp/2016-07-19-realtime-audio-visualization-in-python/
import pyaudio
import numpy as np

CHUNK = 4096 # number of data points to read at a time
RATE = 44100 # time resolution of the recording device (Hz)

p=pyaudio.PyAudio() # start the PyAudio class
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
          frames_per_buffer=CHUNK) #uses default input device

# create a numpy array holding a single read of audio data
for i in range(10): #to it a few times just to see
    data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
    print(data)

# close the stream gracefully
stream.stop_stream()
stream.close()
p.terminate()

I am interested in working on a project but I have no idea how to start. I have quite decent basic knowledge about Python 3. I want to make a script that will convert real time audio output into number values instead of the graph. I have did some research and found out that it can be done with pyAudio and numpy but I can't seem to find any docs or guides on how to convert the audio into numbers instead of graphs. What I want to do is like it will press a key on my keyboard (to toggle rgb) based on the audio "beat" or something like that. Long story short I want it to be able to flicker based on the music / audio.
Basically
I just need the tools and basic concept of how am I going to do it
Any help is appreciated :)


text:
Q: Primefaces - Update modal dialog I have a problem using a primeface modal dialog that is loaded from an external xhtml-file.
My intention is: pressing the button should invoke the method "setType" with the parameter "T" (the reason for invoking this method is to reuse the dialog depending on the type). During this method the DualList inside the dialog.xhtml will be reloaded with the correct and type-depending data. After that the dialog should be shown.
My current code is :
<p:commandButton
value="#{bean.value}"
id="button" type="button" icon="ui-icon-newwin"
onclick="varDialog.show()" style="width: 70px;">

<p:ajax listener="#{bean.setType('T'.charAt(0))}"
    update="dialog" />

<p:dialog id="dialog"
    widgetVar="varDialog"
    header="Dialog Header"
    resizable="false" modal="true" dynamic="true" width="900"
    appendToBody="true">
    <ui:include src="dialog.xhtml" />
</p:dialog>
</p:commandButton>

The problem is that the dialog will disappear right after it is shown (my guess is this is because of the 'update="dialog"'). But leaving out this code will end in a dialog without visible data.

So my question is: how do i achieve to load a generic external dialog with specific type depending data?

A: Why do you use AJAX in this case? I would set up an action:
<p:commandButton
    value="#{bean.value}"
    id="button"
    type="button"
    icon="ui-icon-newwin"
    style="width: 70px;"
    action="#{bean.prepareDialog}">

Inside the bean:
public void prepareDialog() {
    // Do your things.

    RequestContext context = RequestContext.getCurrentInstance();
    context.execute("dialogWidget.show()");
}

And there is a bug in PF which will require you to enclose a dynamic dialogue in a conditional if part of a composition, else it would just load and ignore the dynamic. This may apply to your scenario, but I can't assess it just seeing your example code.
<c:if test="#{bean.condition != null}">
    <ui:include src="dialog.xhtml"/>
</c:if>

A: I found the answer myself reading this thread: http://forum.primefaces.org/viewtopic.php?f=3&t=18503
The first mistake i made was a nested  (one in the main.xhtml and one in the included dialog.xhtml). So - with the help of the thread - i changed the code to the following:
<h:form>
<p:commandButton
    value="#{bean.value}"
    id="supplierButton" icon="ui-icon-newwin"
    actionListener="#{bean.prepareDialog('T'.charAt(0))}"
    oncomplete="varDialog.show()"
    update=":tabView:dialog"
    immediate="true" style="width: 70px;">
</p:commandButton>
</h:form>

<p:dialog id="dialog"
    widgetVar="varDialog"
    header="Dialog title"
    resizable="false" modal="true" dynamic="true" width="900"
    appendToBody="true">
    <ui:include src="dialog.xhtml" />
</p:dialog>

This works like a charm.


text:
Q: AWK sub function syntax I have a files with the contents:
aaa.bbb.ccc ddd.eee.fff.ggg h.i.j.k

If i use the code:
awk '{sub(/\.$/, ""); print $1}' test.txt
returns    aaa.bbb.ccc

awk '{sub(/\.$/, ""); print $3}' test.txt
Returns: h.i.j.k

I understand the sub function is used as:  sub(regexp, replacement, target)
I dont understand this part  .$/, from the sub function.
what is the .$?
thanks
UPDATE
Ok, i like your way of explaining things - thank you!
If i apply this to a real example,
/usr/bin/host 172.0.0.10
01.0.0.172.in-addr.arpa domain name pointer hostname.domain.com.

*

*/usr/bin/host 172.0.0.10 | /bin/awk '{sub(/.$/, ""); print $5}'
gives: hostname.domain.com

*/usr/bin/host 172.0.0.10| /bin/awk '{sub(/.$/, ""); print $1}'
gives: 10.0.0.172.in-addr.arpa
-The sub function will match to the end of the line as there is a "."
-what is the "" doing?
-I dont understand how awk is splitting things into columns?

A: sub(regexp, replacement, target)
So here we used the regex as \.$, which matches the dot at the end. Here sub(/\.$/, "") we didn't mention the target so it takes $0 ie the whole line. If you specify any target , it would remove the last dot only on that particular column.
awk '{sub(/\.$/, ""); print $1}' test.txt

Removes a dot which was present only at the end of the line and prints only the column 1. If there is no dot at the last, then replacement won't occur.
awk '{sub(/\.$/, ""); print $3}' test.txt

Removes the dot at the end of the line and prints only the column 3. Because of there is no dot at the end, it returns the third column aka last column as it is.
Example:
$ cat file
aaa.bbb.ccc. ddd.eee.fff.ggg h.i.j.k.
$ awk '{sub(/\.$/, ""); print $1}' file
aaa.bbb.ccc.
$ awk '{sub(/\.$/, ""); print $3}' file
h.i.j.k

A: sub(/regexp/, replacement, target)
sub(/\.$/, replacement, target)

Your regexp is \.$, not .$/
\ is the escape character. It escapes the character that follows it, thus stripping it from the regex meaning and processing it literally.
. in regex matches any single character. Unless it's escaped by \ like in your example, thus it just matches the dot character .
$ simply means the end of the line.
Putting this together, \.$ is an escaped dot at the end of the line. This would match for example any end of paragraph that ends in a period.
In your example, the sub doesn't substitute anything because there is no . at the end of the line (your input ends with .k. So your first awk just prints the 1st column, and the other one prints the 3rd column.
Update
For your updated question.
Awk splits a string in columns by whitespace by default. Thus in your input, columns are like this:
 01.0.0.172.in-addr.arpa domain name pointer hostname.domain.com.
|----------$1-----------|--$2--|-$3-|--$4---|----------$5--------|

in your sub command, awk finds the dot at the end of the line and replaces with "" which is the empty string (i.e. it just deletes it)
So your 1st command - {sub(/.$/, ""); print $5}, it prints the 5th column which is hostname.domain.com. after it replaces the . at the end with nothing (deletes it). It's worth noting that in this regex you don't escape the . anymore, so the pattern just matches any character at the end and deletes it (it happens to be a . in your input)
Your other command - {sub(/.$/, ""); print $1} deletes the character at the very end of the line and then just prints the first column 10.0.0.172.in-addr.arpa
You can also set custom column separators in awk, I recommend you read some introduction and tutorials on awk to have a better understanding of how it works. E.g. simple awk tutorial

A: I had one table with this format

                Exciter Power Supply

+ 3 V

                OK

 + 5 V

                OK

When i get the value of +3 V
curl -s http://my-site/index.htm | sed -e 's/<[^>]*>//g' | awk '/+ 3 V/{getline;  print}'

I had the output OK'&nbsp'; + 5 V
For remove blank space and text of another field i use sub() for change caracters plus tr to remove the caracters
curl -s http://my-site/index.htm | sed -e 's/<[^>]*>//g' | awk '/+ 3 V/{getline; sub(/+ 5 V/, ""); print}' | tr " " " "

My output is only OK


text:
Q: How to convert the epoch time to time stamp in talend For suppose we have 166667777 of file then we want to convert into time stamp how to convert it in talend

A: in a tjava just paste this code  :
Date myDate= new Date(Long.parseLong("1081157732") * 1000);
System.out.println(myDate) ;
SimpleDateFormat jdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String java_date = jdf.format(myDate);
System.out.println(java_date) ;

Since you didn't tell us your pattern just see what fits your requirement in the console
Don't forget this import in advanced settings :
import java.util.*;
import java.text.SimpleDateFormat ;

Here is the output :
[statistics] connected
Mon Apr 05 11:35:32 CEST 2004
2004-04-05 11:35:32
[statistics] disconnected

If you are wanting to get the the actual timestamp  here how it is done

*

*put in the tJava  :

long epoch = Instant.now().toEpochMilli();
System.out.println(epoch);
LocalDate ld = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(ld);
LocalDateTime ldt = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(ldt);

And as always don't forget the import :
import java.text.SimpleDateFormat ;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

your output would be :
[statistics] connected
1638973017921
2021-12-08
2021-12-08T15:16:57.921
[statistics] disconnected


text:
Q: Remove 'component' word from urls for my custom non mvc component in joomla I wrote a custom non-mvc component (because i don't know how to make mvc component and now it's grown is size so changing it will take more time which is not possible for me) 'com_group' for my client.
Everything is fine but when it comes to sef urls it gives me urls like mysite/component/group/home and in non sef urls like mysite/index.php?option=com_group&view=home but client wants to remove component word from urls.
I also made a router for my component which remove every parameter correctly but it does not remove component. I also made a menu item for it but it didn't helped me.
Here is my router.php
<?php //error_reporting(E_ALL);
defined ( '_JEXEC' ) or die ();
jimport('joomla.error.profiler');

function GroupBuildRoute(&$query){
       $segments = array();
        //$query['Itemid'] = 201;
        if( isset($query['view']) )
       {
                $segments[] = $query['view'];
                unset( $query['view'] );
       };
        if( isset($query['pin']) )
       {
                $segments[] = $query['pin'];
                unset( $query['pin'] );
       };

       return $segments;
}

function GroupParseRoute($segments){
       $vars = array();
       $app =& JFactory::getApplication();
       $menu =& $app->getMenu();
       $item =& $menu->getActive();
       $items = $menu->getItems('component', 'com_group');

       if (!isset($query['Itemid']))
       $query['Itemid'] =  180;//$items->id;
       // Count segments
       $count = count( $segments );
         //Handle View and Identifier
         switch( $segments['0'] ){
               case 'group_page':
                       $vars['view'] = 'group-pages';
                      break;
               case 'group':
                       $vars['view'] = 'home';
                       break;
               case 'folow':
                       $vars['view'] = 'follow';
                       break;
               case 'start':
                       $vars['view'] = 'start-group';
                       break;
               case 'group_eventplan':
                       $vars['view'] = 'group-event-plan';
                       break;
               case 'group_member':
                       $vars['view'] = 'group-members';
                       break;
               case 'manage_subscription':
                       $vars['view'] = 'manage-subscription';
                       break;
               case 'group_msg':
                       $vars['view'] = 'group-message';
                       break;
               case 'group_invite':
                       $vars['view'] = 'invite-friends';
                       break;
               case 'other_group':
                       $vars['view'] = 'other-groups';
                       break;
               case 'groupinfo':
                       $vars['view'] = 'group-info';
                       break;
               case 'home':
                       $vars['view'] = 'group-home';
                       break;
       }

     if (!isset($item)) {
        $vars['view']   = $segments[0];
        $vars['pin']    = $segments[1];
        return $vars;
     }
     if($count==2){
            $vars['view']   = $vars['view'];
            $vars['pin']    = $segments[1];
            return $vars;
     }

       return $vars;
}

I also want to replace group_msg to group-message also so that new urls should be component/group/group-message/ not component/group/group_msg
I tried Remove component part from sef url, menu item not completely but didn't helped me.

A: Finally i managed to solve the question by myself. I am mentioning steps taken to help others. (Please write me if you want source code to use it with your project)
Step 1: add a menu item (Joomla Administrator -> Menus ->Menu Manager->Add new Item)
Step 2: The newly added menu item will be provided an id, add this id to  all urls of your component like this.
index.php?option=com_your_component_name&Itemid=newly_generated_id
that's it.

A: The first option I would try is sh404SEF
Good luck!
EDIT
If SEF extensions are not an option for you, perhaps using .htaccess and redirect, something like the following :
RewriteEngine On

Redirect /component/group/home /something-else


text:
Q: NSSLocale identifier results in runtime crash with a stack I posted a this question earlier to get the most updated locale identifier from the user preference settings.
Here is the answer that I got.
 #include <Foundation/Foundation.h>

    std::string get_user_locale()
    {
        NSLocale* locale = [NSLocale autoupdatingCurrentLocale];
        return std::string([[locale localeIdentifier] UTF8String]);
    }

int main()
{
    std::cout << "Locale is " << get_user_locale() << std::endl;
    return 0;
}

I created a standalone .mm file and tried to print the locale identifier string but the app fails with following stack
2019-11-06 05:40:12.879 App[9062:303135] +[NSLocale autoupdatingCurrentLocale]: unrecognized selector sent to class 0x7fff8f86c458
2019-11-06 05:40:12.894 App[9062:303135] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSLocale autoupdatingCurrentLocale]: unrecognized selector sent to class 0x7fff8f86c458'
*** First throw call stack:
(
        0   CoreFoundation                      0x00007fff36daeecd __exceptionPreprocess + 256
        1   libobjc.A.dylib                     0x00007fff62e66720 objc_exception_throw + 48
        2   CoreFoundation                      0x00007fff36e2c1c5 __CFExceptionProem + 0
        3   CoreFoundation                      0x00007fff36d50b40 ___forwarding___ + 1486
        4   CoreFoundation                      0x00007fff36d504e8 _CF_forwarding_prep_0 + 120
        5   testfun                             0x000000010e72096a main + 58
        6   libdyld.dylib                       0x00007fff63f34ed9 start + 1
        7   ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Locale is

Abort (core dumped)

Am I missing something here ?


text:
Q: normal cone inclusion and non-symmetric matrix and optimization problem I have the following normal cone inclusion
$$-(A x + b) \in \mathcal{N}_\mathcal{C}(x) \qquad (1)$$
where $\mathcal{N}_\mathcal{C}$ denotes the normal cone to the convex set $\mathcal{C}$ at the point $x \in \mathcal{C}$. Matrix $A$ is non-symmetric.
Normally if $A$ would be symmetric, the convex optimization problem is
$$\min \frac{1}{2} x^\top A x + b^\top x + I_{\mathcal{C}}(x) \qquad (2)$$
where $I_{\mathcal{C}}(x)$ is the indicator function of the set $\mathcal{C}$. The inclusion (1) is the necessary and sufficient optimality condition of the convex optimization problem (2).
However, what are the implications of $A$ beeing non-symmetric and how does that relate to an optimization function? I guess there does not exist an optimization function?


text:
Q: Transform text to vector shape in Adobe Flash Professional CS5 How? Question is simple, hope the answer will be as well.

A: *

*Use the text tool T and type

*Select the text with the Selection tool V

*From the menu select Modify then Break Apart or Ctrl+b

*Finally use the Subselection tool A and click the text edge (no the inside fill), you'll see the cursor change to an arrow with a black dot.

A: If it was imported, as @Dementic says, you'll need to trace it using Modify > Bitmap > Trace Bitmap.
If you created it in Flash using the Text Tool, then it is already in a vector format. If you created the file using a newer/older version of Flash that the default/only option is Classic Text whereas for CS5 the default is the TLF format introduced in that version. If you're not sure about the difference between TLF and Classic Text, Andy Anderson can explain.
Reading between the lines of your concise question you're probably trying to break apart Classic Text, so here's how.


text: Q: Get the area for a gaussian line I am wondering if there is a way to get the area for a given gaussian line for python? I have my data for the gaussian but the only method I not in getting the area is to divide the data into bins and sum up the areas of the bins.


text:
Q: How to retrieve an actionlink text in a controller? I have a list of actionlink in my navbar like this

*@Html.ActionLink("Customer Profile", "Index", "Profile")

*@Html.ActionLink("Supplier Profile", "Index", "Profile")

*@Html.ActionLink("Publisher Profile", "Index", "Profile")

now i need to retrieve the link text in my controller to allocate some value in a property by comparing the value of the link text like this
 [HttpGet]
    public ActionResult Index()
    {
        Profile profile = new Profile();
        if(linktext=="Customer Profile")
        {
            profile.cust_supply_cat_id = 1;
        }
        else if (linktext == "Supplier Profile")
        {
            profile.cust_supply_cat_id = 2;
        }
        else if (linktext == "Publisher Profile")
        {
            profile.cust_supply_cat_id = 3;
        }

        return View(profile);

    }

How can i do it?
or if you get the idea what are the possible ways to do that??

A: you can send a value from Html.ActionLink like:-
@Html.ActionLink("Customer Profile", "Index", "Profile", new { linktext: "Customer Profile", null })

then receive the value in controller as a argument to a parameter like:-
[HttpGet]
public ActionResult Index(string linktext)
{
    //your code
}

A: You could add a parameter to the Index function.
E.g:
public ActionResult Index(int id).

Then add a parameter value to your ActionLinks.
E.g:
@Html.ActionLink("Publisher Profile", "Index", "Profile", new {id = 1}, null)

Hope this works for you.


text:
Q: Subversion not authenticating when using Android Studio This is a follow up question to this question:
Android Studio can't authenticate with SVN
I got an Android project which I used in Eclipse and I just converted it to a working AS project. When using Eclipse, the SVN works fine. When using AS for some reason, every time I try to commit or update, I get a prompt asking for my user name and password and it keeps repeating itself without ever succeeding. When I press cancel I get this error:

Error:svn: E170012: When using svn+ssh:// URLs, keep in mind that the --username and --password options are ignored because authentication is performed by SSH, not Subversion
svn: E170012: Unable to connect to a repository at URL 'svn+ssh://...
svn: E170012: Can't create tunnel
svn: E720002: Can't create tunnel: The system cannot find the file specified.

What I tried until now was Uncheck follow two items
Use command line client
Use system default Subversion configuration directory

Also, I tried editing the servers file in the SVN config's folder with:
store-passwords = yes
store-ssl-client-cert-pp = yes
store-plaintext-passwords = yes
store-ssl-client-cert-pp-plaintext =yes

What else can be done?

A: I ended up just checking out the project again to a new folder even without setting all the things I wrote in the question and everything started working


text:
Q: How can I calculate $\sum_{k=0}^{2n}{\binom{6n}{3k}(-1)^{k}}$ how can I calculate this expression:
$\sum_{k=0}^{2n}{\binom{6n}{3k}(-1)^{k}}$ using the identity $ (x + y)^n $ =   $\sum_{k=0}^{n}{\binom{n}{k}x^{n-k} y^k}$ or any other way that doesn't include Euler's number.

A: Denoting $ x=\mathrm{e}^{-\mathrm{i}\frac{\pi}{3}} $, $ y=-1 $, $ z=\mathrm{e}^{\mathrm{i}\frac{\pi}{3}} $, let $ n $ be a positive integer.
$ \left(1+x\right)^{6n}=\sum\limits_{k=0}^{6n}{\binom{6n}{k}\mathrm{e}^{-\mathrm{i}\frac{k\pi}{3}}}=\sum\limits_{k=0}^{2n}{\left(-1\right)^{k}\binom{6n}{3k}}+\mathrm{e}^{-\mathrm{i}\frac{\pi}{3}}\sum\limits_{k=0}^{2n-1}{\left(-1\right)^{k}\binom{6n}{3k+1}}+\mathrm{e}^{-\mathrm{i}\frac{2\pi}{3}}\sum\limits_{k=0}^{2n-1}{\left(-1\right)^{k}\binom{6n}{3k+2}} \cdot $
$ \left(1+y\right)^{6n}=\sum\limits_{k=0}^{6n}{\left(-1\right)^{k}\binom{6n}{k}}=\sum\limits_{k=0}^{2n}{\left(-1\right)^{k}\binom{6n}{3k}}-\sum\limits_{k=0}^{2n-1}{\left(-1\right)^{k}\binom{6n}{3k+1}}+\sum\limits_{k=0}^{2n-1}{\left(-1\right)^{k}\binom{6n}{3k+2}} \cdot $
$ \left(1+z\right)^{n}=\sum\limits_{k=0}^{6n}{\binom{6n}{k}\mathrm{e}^{\mathrm{i}\frac{k\pi}{3}}}=\sum\limits_{k=0}^{2n}{\left(-1\right)^{k}\binom{6n}{3k}}+\mathrm{e}^{\mathrm{i}\frac{\pi}{3}}\sum\limits_{k=0}^{2n-1}{\left(-1\right)^{k}\binom{6n}{3k+1}}+\mathrm{e}^{\mathrm{i}\frac{2\pi}{3}}\sum\limits_{k=0}^{2n-1}{\left(-1\right)^{k}\binom{6n}{3k+2}} $
Using the fact that $ x+y+z=0 $ and that $ x^{2}+y^{2}+z^{2}=0 $, summing the previous relations, we get : $$ \left(1+x\right)^{6x}+\left(1+y\right)^{6n}+\left(1+z\right)^{6n}=3\sum_{k=0}^{2n}{\left(-1\right)^{k}\binom{6n}{3k}} $$
Since \begin{aligned} \left(1+x\right)^{6x}+\left(1+y\right)^{6n}+\left(1+z\right)^{6n}&=\left(\mathrm{e}^{-\mathrm{i}\frac{\pi}{6}}\left(\mathrm{e}^{\mathrm{i}\frac{\pi}{6}}+\mathrm{e}^{-\mathrm{i}\frac{\pi}{6}}\right)\right)^{6n}+\left(\mathrm{e}^{\mathrm{i}\frac{\pi}{6}}\left(\mathrm{e}^{\mathrm{i}\frac{\pi}{6}}+\mathrm{e}^{-\mathrm{i}\frac{\pi}{6}}\right)\right)^{6n}\\ &=2^{6n+1}\left(-1\right)^{n}\cos^{6n}{\left(\frac{\pi}{6}\right)}\\ &=2\left(-1\right)^{n}3^{3n} \end{aligned}
We get $$ \sum_{k=0}^{2n}{\left(-1\right)^{k}\binom{6n}{3k}}=2\left(-1\right)^{n}3^{3n-1}  $$


text:
Q: Insert form data into database Is it possible to just iterate through the post results and insert them into the appropriate fields in a table? Instead of doing Request.Form["something"] for each one?

A: Yes:
Request.Form is a NameValueCollection. This means you can refer to specific keys how you are already doing it: Request.Form["something"],  or you can iterate through the items using a foreach loop
foreach (string value in Request.Form){
    // do stuff with value
    // save-to-database-function(value)
    // ...
}


text:
Q: Can $C^*$ algebra $A$ be decomposed? If $A$ is a $C^*$ algebra ,$B$ is a finite dimensional $C^*$ subalgebra of $A$.Does there exists a $*$ subalgebra of $C$ such that $A=B \oplus C$?

A: No. In such an algebra $A$, both $B$ and $C$ would be nontrivial ideals. So if you take any simple C$^*$-algebra that has finite-dimensional subalgebras, your decomposition does not exist.
Such an example could be $A=$UHF$(2^\infty)$, which has lots of projections. Take a nontrivial projection $p\in A$, and put $B=\mathbb C\, p$. Then $B$ is one-dimensional but not an ideal, and thus the decomposition does not exit.
Any other simple real rank zero example would do.


text:
Q: Music loses quality when playing at the same time well the problem is that when i play a steam game for example, i usually listen to the radio, i use VLC for this, it works perfectly until i open the game. When i open the game apparently looks like the game has higher preference or something and the radio sound sounds really bad, with interferences or something, if i mute the game it sounds perfectly. I use headphones and what i want if possible, is to hear both game and radio without losing quality, any idea? Thanks
P.D. My OS is Windows 10


text:
Q: В Python пройти три цикла с двумя условиями Мне требуется умножить и суммировать значения по формуле. Есть три цикла, бегущих по одному диапазону от 0 до 4. Формула Σ Σ Π (q—l)

*

*основание левой суммы сначала перебираем по j=0 (проходить j будем от [0, 1, 2, 3]);

*тогда основание следующей суммы перебираем по k!= 0 (то бишь k-диапазон [1, 2, 3], когда j=0);

*в заключительном произведении l!= 0 и l!=k (то есть если k=1, то l в диапазоне [2, 3] и тогда первое произведение получаем (q—2)(q—3);

*далее нам требуется перейти к k=2, и тогда следующее слагаемое для второй суммы (q—1)(q—3);

*после финального k=3 переходим на следующую итерацию j=1 (и так, пока не переберем все j в диапазоне [0, 1, 2, 3])).

В итоге должно получиться 12 слагаемых, где слагаемыми выступают произведения двух скобок (q—l_1)(q—l_2).
Я написал код, но он не дает ничего (и ошибки тоже). Понятно, что я там поставил невыполнимое условие, отрицая k и l, хотя все три буквы бегут по одному диапазону.
Но как мне тогда быть? Как наложить ограничение, что если j равна нулю, то k не должна быть ноль, а l не должна нести текущее значение j и k? Ниже привел формулу

Код:
from sympy import symbols
import math
q = symbols('q')
orders = 4
x_js_list = [0.1, 1.3, 5.2, 3.7, 4.9, 7.5]
# q=10
for j in range(0, orders+1):
    if orders < len(x_js_list): # необязательное здесь условие
        for k in range(0, orders+1, -1):
            if k != j:
                for l in range(0, orders+1):
                    if l != k and l != j:
                        print(math.prod(q - l))

A: Не уверен, что понял задание, но что-то похожее получилось - сумма произведений (q-l) в различных сочетаниях
from sympy import symbols

q = symbols('q')
orders = 4
s = 0 # первая сумма
for j in range(0, orders):
    s1 = 0 # вторая сумма
    for k in range(0, orders):
        if k != j:
            m = 1 # произведение
            for l in range(0, orders):
                if l != k and l != j:
                    m *= q - l
            s1 += m
    s += s1
print(s)

2*q*(q - 3) + 2*q*(q - 2) + 2*q*(q - 1) + 2*(q - 3)*(q - 2) + 2*(q - 3)*(q - 1) + 2*(q - 2)*(q - 1)


text:
Q: LINQ merge two grouped query results in my domain I have an object called "Block". A "Block" can have "Pins" and "Attributes" attached to it.
I can create two groups which give me the following results:
Group1 is:
Block:B1
    Pin:P1
    Pin:P2
Block:B2
    Pin:P3
    Pin:P4

Group2 is:
Block:B1
    Attribute:Att1, Value: Value1
    Attribute:Att2, Value: Value2
Block:B2
    Attribute:Att3, Value: Value3
    Attribute:Att4, Value: Value4

now I like to merge this two results to something like this:
Resulting group is:
Block:B1
    Pin:P1
    Pin:P2
    Attribute:Att1, Value: Value1
    Attribute:Att2, Value: Value2
Block:B2
    Pin:P3
    Pin:P4
    Attribute:Att3, Value: Value3
    Attribute:Att4, Value: Value4

Is that possible with LINQ? Or do I need un-grouped results to create a grouped result later?
Thanks
EDIT:
With Road242 solution I get this result:
Pin: P1
Pin: P2
Attribute: Att1
Attribute: Att2
Pin: P3
Pin: P4
Attribute: Att3
Attribute: Att4

The pins and attributes look pretty good, but I lost the blocks as grouping key :-(
EDIT:
My queries look like this:
var blockPinsQuery = from blockPinRelation in blockPinRelations
            join block in blocks
                on blockPinRelation.BlockId equals block.Id
            join pin in pins
                on blockPinRelation.PinId equals pin.Id
            group pin by block
            into g
            select new
                   {
                       Block = g.Key,
                       Pins = g
                   };

and
var blockAttributesQuery = from blockAttributeRelation in blockAttributeRelations
                             join block in blocks
                                 on blockAttributeRelation.BlockId equals block.Id
                             join attribute in stringAttributes
                                 on blockAttributeRelation.AttributeId equals attribute.Id
                                   group attribute by block
                                 into g
                                 select new
                                 {
                                     Block = g.Key,
                                     Attributes = g
                                 };

as you can see there is a relation-table in between the relevant entities. But this is not important, I guess.
My output routines look like this:
foreach (var group in blockPinsQuery)
        {
            Console.WriteLine("Block:" + group.Block.Name);
            group.Pins.ToList().ForEach(x => Console.WriteLine("\t" + "Pin:" + x.Name));
        }

and
foreach (var group in blockAttributesQuery)
        {
            Console.WriteLine("Block:" + group.Block.Name);
            group.Attributes.ToList().ForEach(x => Console.WriteLine("\t" + "Attribute:" + x.Name + ", " + "Value: " + x.Value));
        }

and for Road242 query:
foreach (var group in joinedResults)
        {
            group.Pins.ToList().ForEach(p => Console.WriteLine("Pin: " + p.Name));
            group.Attributes.ToList().ForEach(p => Console.WriteLine("Attribute: " + p.Name));
        }

A: you can use linq join clause:
see http://msdn.microsoft.com/en-us/library/bb311040.aspx
var joinedResults =
    from g1 in Group1
    join g2 in Group2 on g1.Block equals g2.Block
    select new { Pin = g1.Pin, Attribute = g2.Attribute };


text:
Q: Multiple Resultsets to excel file in Java I have a question about Resultsets to Excel file in Java. Let me explain scenario;
I have many sql queries and many resultsets under different classes.
This resultset returns;
Example1 50  20
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package program;
import java.sql.*;

/**
 *
 * @author Lacrymae_Ev
 */
public class SQLQueries1{
    loginscreen logindetails = new loginscreen();
    private static Statement stmt;
    private static final String query = "select 'Example1' as Example1,sum(dur) as dur,sum(tot)as tot from table1 with(nolock)\n" +
"where date between '2013-07-01 00:00:00.000' and '2013-07-01 23:59:59.999'";

    /**
     * @param args the command line arguments
     * @throws java.sql.SQLException
     */
    public static void main(String[] args) throws SQLException {
        // TODO code application logic here
        try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "jdbc:sqlserver://192.168.200.10;" + "databaseName=ExampleDB;" + "user=exampleuser;" +  "password=examplepassword;";
        Connection con = DriverManager.getConnection(connectionUrl);
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
         while (rs.next()) {
         String Example1 = rs.getString("Example1");
         int dur = rs.getInt("dur");
         int tot = rs.getInt("tot");
         System.out.println(Example1 + "\t" + dur + "\t" + tot);
         }

    }
    catch (SQLException e) {
            System.out.println("Wrong id or password!");
     }
    catch (ClassNotFoundException cE) {
            System.out.println("Class Not Found Exception: "+ cE.toString());
     }
     finally {
    if (stmt != null) { stmt.close(); }

    }

}

This resultset returns;
Example2 100 50
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package program;
import java.sql.*;

/**
 *
 * @author Lacrymae_Ev
 */
public class SQLQueries2{
    loginscreen logindetails = new loginscreen();
    private static Statement stmt;
    private static final String query = "select 'Example2' as Example1,sum(dur) as dur,sum(tot)as tot from table1 with(nolock)\n" +
"where date between '2013-07-01 00:00:00.000' and '2013-07-01 23:59:59.999'";

    /**
     * @param args the command line arguments
     * @throws java.sql.SQLException
     */
    public static void main(String[] args) throws SQLException {
        // TODO code application logic here
        try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String connectionUrl = "jdbc:sqlserver://192.168.200.10;" + "databaseName=ExampleDB;" + "user=exampleuser;" +  "password=examplepassword;";
        Connection con = DriverManager.getConnection(connectionUrl);
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
         while (rs.next()) {
         String Example2 = rs.getString("Example2");
         int dur = rs.getInt("dur");
         int tot = rs.getInt("tot");
         System.out.println(Example1 + "\t" + dur + "\t" + tot);
         }

    }
    catch (SQLException e) {
            System.out.println("Wrong id or password!");
     }
    catch (ClassNotFoundException cE) {
            System.out.println("Class Not Found Exception: "+ cE.toString());
     }
     finally {
    if (stmt != null) { stmt.close(); }

    }

}

I want write these resultsets to Excel file as below screenshot;

I try use Apache POI Project for output excel file but i don't understand many things. Do you have any simple solutions i wonder.

A: Look into Comma-separated Values (CSV) as a simple format.  All versions of Excel support CSV files, and you can easily get the output you want using a basic Java FileWriter.


text:
Q: Excel VBA Macro - Copying data from multiple sheets in existing file, and creating new file and pasting selected data into separate sheets any and all help is greatly appreciated.
Description:
I have an excel file with several sheets of data. I need to copy ALL of the data from multiple sheets, create a NEW excel file, and paste that data into multiple sheets. So if I have the following:
excelfile1.xlsx - sheet1 - sheet2
I need to select sheet1, copy all the data in sheet1, create a new excel file and paste the sheet1 data into the new file on sheet1new, and then need to do the same with sheet2.
Here is my code for processing 1 sheet (but am not sure how to ask it to process the actions for the 2nd sheet, which is where I need some guidance):
Dim Directory As String
Dim Filename As String

Directory = Range("directory").Value
Filename = Range("filename").Value

Sheets("RHD").Select

Cells.Select
Range("N15").Activate
Selection.Copy

Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

ActiveWorkbook.SaveAs Filename:=Directory & Filename, _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close

Sheets("I&S").Select

A: Worksheets(Array("Sheet1", "Sheet2")).Copy
With ActiveWorkbook
 .SaveAs Filename:=Environ("TEMP") & "\New3.xlsx", FileFormat:=xlOpenXMLWorkbook
 .Close SaveChanges:=False
End With

from docs.microsoft.com


text:
Q: in vue.js i am trying to get row count but it returning null im trying to get row cout but returning 0 only.
my code
 <template>

{{ resultCount }}

  </template>

A: This is because when you return a property in asyncData, you should not have it in data property of the component instance, instead the later will override the returned with asyncData.

<template>

{{ resultCount }}

  </template>


text:
Q: "ValueError: The truth value of an array with more than one element is ambiguous" I am trying to execute the following code :( this is a simple code for Kmeans algorithm which has been written in Python.The two-step procedure continues until the assignments of clusters and centroids no longer change.  The convergence is guaranteed but the solution might be a local minimum. In practice, the algorithm is run multiple times and averaged.
import numpy as np
import random
from numpy import *

points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]

def cluster(points,center):
  clusters = {}

  for x in points:

    z= min([(i[0], np.linalg.norm(x-center[i[0]]))  for i in enumerate(center)], key=lambda t:t[1])

    try:
      clusters[z].append(x)
    except KeyError:
      clusters[z]=[x]

  return clusters

def update(oldcenter,clusters):

 d=[]
 r=[]
 newcenter=[]

 for k in clusters:
  if k[0]==0:
   d.append(clusters[(k[0],k[1])])

  else:
   r.append(clusters[(k[0],k[1])])

 c=np.mean(d, axis=0)
 u=np.mean(r,axis=0)
 newcenter.append(c)
 newcenter.append(u)

 return newcenter

def shouldStop(oldcenter,center, iterations):
    MAX_ITERATIONS=4
    if iterations > MAX_ITERATIONS: return True
    return (oldcenter == center)

def kmeans():
  points = np.array([[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]])
  clusters={}
  iterations = 0
  oldcenter=([[],[]])
  center= ([[1,1],[5,7]])

  while not shouldStop(oldcenter, center, iterations):
        # Save old centroids for convergence test. Book keeping.
        oldcenter=center
        iterations += 1
        clusters=cluster(points,center)
        center=update(oldcenter,clusters)

  return (center,clusters)

kmeans()

but now i stuck. Can anybody help me with this, please?
Traceback (most recent call last):
  File "has_converged.py", line 64, in <module>
    (center,clusters)=kmeans()
  File "has_converged.py", line 55, in kmeans
    while not shouldStop(oldcenter, center, iterations):
  File "has_converged.py", line 46, in shouldStop
    return (oldcenter == center)
ValueError: The truth value of an array with more than one element is ambiguous.
 Use a.any() or a.all()

A: As the error indicates, you cannot compare two arrays with == in NumPy:
>>> a = np.random.randn(5)
>>> b = np.random.randn(5)
>>> a
array([-0.28636246,  0.75874234,  1.29656196,  1.19471939,  1.25924266])
>>> b
array([-0.13541816,  1.31538069,  1.29514837, -1.2661043 ,  0.07174764])
>>> a == b
array([False, False, False, False, False], dtype=bool)

The result of == is an element-wise boolean array. You can tell whether this array is all true with the all method:
>>> (a == b).all()
False

That said, checking whether the centroids changed in this way is unreliable because of rounding. You might want to use np.allclose instead.


text:
Q: loop error in converting shapefiles to raster for entire folder set My code creates a raster from a shapefile, but now I have tried to get it to loop through all the shapefiles in a particular folder, but I am still getting an error in the loop. Please can someone take a look?
This is the error I get:
RuntimeError: not a string.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 14:17:53 2018

@author: me
"""
from osgeo import ogr, gdal
import subprocess
import os

#change directory
os.chdir('/Users/SpatialDataET')

#Name of folder containing all shapefiles to be transformed
folder = 'region_shapes'
#Accesses all shapefiles in the folder (even if there are 100 or 1000 shapefiles)
shapefiles = [folder + '/' + file for file in os.listdir(folder) if 'shp' in file]

#creates object/folder for storing rasterized version (fills in later)
OutputImages = 'Imagefolder'

#Create an output directory (puts the new geotiffs into a separate folder) if none exists
if not os.path.exists(OutputImages):
    os.mkdir(OutputImages)

#reference with which to grab resolution (x/y spacing, projection and geotransformation)
RefImage = '/Users/ETa_CMRSET_mm-month-1_monthly_2000.01.01.tif'
gdalformat = 'GTiff'
datatype = gdal.GDT_Byte
burnVal = 1 #value for the output image pixels

# Get projection info from reference image
Image = gdal.Open(RefImage, gdal.GA_ReadOnly)

for i in shapefiles:
    shapefiles[i][-9:-3] = ogr.Open(shapefiles)
    Shapefile_layer = Shapefile.GetLayer()

    # Rasterize
    print("Rasterising shapefile...")
    Output = gdal.GetDriverByName(gdalformat).Create(OutputImages, Image.RasterXSize, Image.RasterYSize, 1, datatype, options=['COMPRESS=DEFLATE'])
    Output.SetProjection(Image.GetProjectionRef())
    Output.SetGeoTransform(Image.GetGeoTransform())

    # Write data to band 1
    Band = Output.GetRasterBand(1)
    Band.SetNoDataValue(0)
    gdal.RasterizeLayer(Output, [1], Shapefile_layer, burn_values=[burnVal])

    # Close datasets
    Band = None
    Output = None
    Image = None
    Shapefile = None

    # Build image overviews
    subprocess.call("gdaladdo --config COMPRESS_OVERVIEW DEFLATE "+OutputImages+" 2 4 8 16 32 64", shell=True)

print("Done.")

A: Your loop should start like this
for shapefile in shapefiles:
   ds = ogr.Open(shapefile)
   ds_layer = ds.GetLayer()

I renamed it to ds since it will not be a shapefile anymore but a ogr datasource once loaded with ogr.


text:
Q: .net Printing with staple In my project i have to print a liste of images files (.png) with differents settings, and i ca do it without problem using the native .Net System.Drawing.Printing.PrintDocument classe :

*

*PrintDocument.DefaultPageSettings.Landscape allow me to change the orientation

*PrintDocument.DefaultPageSettings.PaperSize allow me to change the papersize to use

*PrintDocument.DefaultPageSettings.Duplex allow me to change the duplexing mode

The only thing i am not able to do is to define the Stapling property ??
After spending a lot of time of searching, i am very dissapointed on how to do this :

*

*Is it possible to do it using the PrintDocument classe and its sub-classes ??

*Do i have to use a PrintTicket as described in  MSDN article ?

But if the solution is to use the print ticket class, i 've two others questions :

*

*How do i attach the printing of an existing image file (using a printjob, a PrintDocument ???)

*Are thoses classes only available for using XPS document ?

Important constraint : there is no GUI (because the program prints a lot of files in batch mode), so the user cannot change interactivly the staple option.

A: Finally, after spending few more hours of search, i've found the right answer to get and set specific printer settings.
Thanks to this Good Article, i did understand that in order to get/set all the settings of a printer, i have to deal with the DevMode structure of the printer.
Drawbacks :

*

*the DevMode structure is specific to a driver, and also to an operating system

*you have to maintain a list of DevMode address for each parameters you want to change

Benefits :

*

*you can access all the functions offered by a printer (even printing on tee-shirt, or saving mode....)

*the project in the link show a small interface to get/set/examine what parameter have been changed using the Pinter Dialog Settings window. So you yan easily by code change on the fly


text:
Q: How to get Item web client id in Exchange 2007 using EWS Managed API I have an EmailMessage item saved in Draft folder. I need to open an editing form of it in browser, but cannot found id that is used by web client. In documentation there is such property, but it fails with Microsoft Exchange Server 2007. What is alternative?
 Any help is appreciated.

A: I've found.
ExchangeService service = new ExchangeService();
EmailMessage message = EmailMessage.Bind(new ItemId("someId"));
var alternateId = new AlternateId();
alternateId.UniqueId = message.Id.UniqueId;
alternateId.Mailbox = "somemailbox";
alternateId.Format = IdFormat.EwsId;

var convertedId = service.ConverId(alternateId, Format.OwaId) as AlternateId;

And convertedId.UniqueId is what I need;


text:
Q: Two maximum values for $|iz+3-4i|$ what went wrong? I need to find the maximum value of $|iz+3-4i|$ given that $|z|\leq4$
$|iz+3-4i|\leq |iz|+|3-4i|$
$|iz+3-4i|\leq 4+5$
But I could write an inequality for $|3-4i|$ whose maximum value would be 7, not 5 so I get the maximum value to be 11 when doing so rather than the original answer of 9.
What went wrong here? , thanks in advance.

A: For a point in a disk of radius $4$ centered at the origin, what is the maximum distance of that point from $(3,-4)$?  Clearly, the farthest (and closest!) point away is the one that is on the line that joins $(3,-4)$ and the circle center $(0,0)$.  Since the distance between $z$ and the center is at most $4$, and the distance from the center to $(3,-4)$ is $5$, the maximum distance is $4+5 = 9$ and the minimum is $5-4 = 1$.  The fact that $z$ is multiplied by $i$ is of no consequence, because we can set $iz = w$ and then $|z| \le 4$ is equivalent to $|w/i| = |w| \le 4$.

A: Nothing seems to have gone wrong. $9 = 4 + 5 \leq |iz| + |3 - 4i| \leq |iz| + |3| + |4i| \leq 4 + 3 + 4 = 11$. And, well, $9 < 11$.

A: A minor simplification is $|iz+3-4i|=|i(z-4-3i)|=|z-4-3i|$, which dispenses of the distracting factor of $i$. Moreover, it allows us to interpret $|z-4-3i|$ as the distance between $z$ and $4+3i$. That suggests a tidy geometric interpretation and a simple answer.

A: The reason is $|3-4i|$ represents a real number associated to the Eulidean norm of the point which you call the distance from origin. There is no way you can maximize a real number $c$(say) unless it is a real variable.

A: Put $z = a + bi\implies |iz+3-4i|= |i(a+bi)+3-4i|=|3-b+(a-4)i|=\sqrt{(a-4)^2+(b-3)^2}$. The problem translates to: Maximize $f(a,b) = \sqrt{(a-4)^2+(b-3)^2}$ given that $a^2+b^2 \le 16$. First observe that if the max occurs at an interior point inside the disk $D: a^2+b^2 \le 16$ at $M$, then consider the point of intersection $B$ of the line joining $A = (4,3)$ to $M$ and the circle $C: a^2+b^2 = 16$, we have: $AM \le AB$ and $AB$ is the max value. This can be proven rigorously but is quite easy. Thus the constraint is reduced to the circle $a^2+b^2 = 16$, and $f(a,b) = \sqrt{a^2-8a+16+b^2-6b+9}=\sqrt{41-8a-6b}$. Again observe that $f(a,b)$ is maximized iff $g(a,b) = 41 - 8a-6b$ is maximized under the condition $a^2+b^2=16$. This can be done with Lagrange Multiplier from calculus. Indeed, $\nabla g(a,b) = \lambda\nabla h(a,b), h(a,b) = a^2+b^2-16\implies (-8,-6)=(2\lambda a, 2\lambda b)\implies 2\lambda a= -8, 2\lambda b = -6\implies \lambda a = -4, \lambda b = -3\implies \lambda^2(a^2+b^2)= (-4)^2+(-3)^2=25\implies 16\lambda^2=25\implies \lambda = \pm \dfrac{5}{4}$. We can see that only $\lambda = \dfrac{5}{4}$ yields the max value, and it corresponds to $a= -\dfrac{16}{5}, b = -\dfrac{12}{5}\implies g_{\text{max}} = 41-8\cdot \dfrac{-16}{5}-6\cdot \dfrac{-12}{5}=81\implies f_{\text{max}}= \sqrt{g_{\text{max}}}=\sqrt{81} = 9$, and this is the maximum value of $|iz+3-4i|$.


text:
Q: Can I use the Stack Exchange markdown techniques in my own site? When I develop a website, the client almost always requires me to give them edit privileges without referring back to me, i.e. they want to edit the site's content themselves. So, in such scenarios, I always think of implementing a markdown system, just like the one used here in the Stack Exchange network. Can I build a system such that uses the same markdown techniques as used here, for example, **text** for bold, *text* for italic, etc...? If yes, do I have to mention that I copied them from here?

A: Stack Exchange uses MarkdownSharp, available under the MIT license.
However, you may be better served by using CommonMark, an open standard with implementations in many languages. CommonMark is newer than Stack Exchange, which is why Stack Exchange doesn't yet use it. However, they are now making the switch.
Markdown in all its various incarnations dates back to John Gruber in 2004, and many many websites use Markdown or something similar. If you write your own Markdown or Markdown-like parser, there's probably no need to acknowledge anyone. Still, I would recommend CommonMark: they've worked out a number of kinks and edge-cases, and it's good to follow the standards.

A:
Can I build a system such that uses the same markdown techniques as used here ...

Sure you can!
Read on for more details about how I do so already ...
Consider this markdown example:
The [Message Stack][1] appears to be a set of 3 Drupal contributed modules, that can be used in a Drupal 7 site to implement ***messaging*** in a Drupal site.

Here are some details about it (from that same link):

 > **The modules have been written with a pluggable architecture that supports customization and extensibility. Each module includes implementation examples that give a hint of the potential use cases and integration with other popular Drupal modules.**

I wonder what this is all about, ie:

1. What's the purpose of each of these modules?
2. How do its modules work together?
3. Where can I find examples of others who have been using the Message Stack already?

  [1]: https://www.drupal.org/node/2180145

The above example, is the actual "content" (= the source in markdown format) as created/edited to create the question as shown in "What is Drupal's Message Stack and how do its modules work together?". Similarly, the answer to that question (below it, on the same linked page), is yet another chunck of markdown.
Here is what it took to build such site:

*

*Create a site using Drupal, a CMS, in this case version 7.

*Download and enable 2 contributed module (free Drupal plugins), i.e.:

*

*the Answers module (disclosure: I'm a co-maintainer of it).

*the Markdown module (which provides Markdown filter integration for Drupal input formats).

*Create the actual content (only editing/entering text in markdown format).
PS: below (between the 2 lines) is an exact copy of the above markdown sample, though this time not formatted as code (to illustrate how the rendered version of it looks like on a SE site) ...

The Message Stack appears to be a set of 3 Drupal contributed modules, that can be used in a Drupal 7 site to implement messaging in a Drupal site.
Here are some details about it (from that same link):

The modules have been written with a pluggable architecture that supports customization and extensibility. Each module includes implementation examples that give a hint of the potential use cases and integration with other popular Drupal modules.

I wonder what this is all about, ie:

*

*What's the purpose of each of these modules?

*How do its modules work together?

*Where can I find examples of others who have been using the Message Stack already?