text:
Q: How to Format an Output Table using Latex? I was working on some categorical variables and created a contingency table using the following code:
mytable <- table(Gender, Income)

The output looks like below (which is not nice-looking):
  Work.Status
Gender   Employed Full-time Employed Part-time Unemployed
  Male                  433                 35         29
  Female                427                174        247

Is there any way that I can format this table to make it better looking (e.g. change the font, color, and size of the variables)? I tried a few methods from the web, but didn't get the desired results....

A: It isn't entirely clear from your question what you want to achieve. Is this an R to latex question or is it simply a formatting in latex question?
I favour the xtable package in R for taking tables in R to latex. A very quick example for categorical data below. The knitr package is also excellent for combining R with Latex output.
   library(xtable)
   data(tli)
   head(tli)
   table(tli$sex, tli$grade)
   print(xtable(table(tli$sex, tli$grade), booktabs = TRUE))

Which returns
% latex table generated in R 3.0.0 by xtable 1.7-1 package
% Thu Nov 28 09:00:24 2013
\begin{table}[ht]
\centering
\begin{tabular}{rrrrrrr}
  \hline
 & 3 & 4 & 5 & 6 & 7 & 8 \\
  \hline
F &   6 &   9 &   8 &  11 &  10 &   7 \\
  M &   9 &   6 &   7 &  12 &   8 &   7 \\
   \hline
\end{tabular}
\end{table}


text:
Q: Express.js res.render's second parameter and passing data to views I am going through various tutorials on node.js and express and cannot find what this particular part of the code is actually doing. It's for the second parameter of res.render below. The part I am unsure of is the mascots: mascots part. Is this declaring a mascots variable? I cannot find anywhere in the javascript language where this is done like this so it's confusing me as to where they got this. Of course, I am just starting to learn Javascript so it could be somewhere obvious but haven't found it yet. It looks like it's an object (b/c of the curly braces {}) but even if it is, the value of named mascots is not clear to me. Is this the array of objects they are referring to? And if so it's still very confusing to me. I could get an answer for it after searching a good bit so asking here.
app.get('/', function(req, res) {
    var mascots = [
        {name: 'Sammy', organization: 'DigitalOcean', birth_year: 2012},
        {name: 'Tux', organization: 'Linux', birth_year: 1996},
        {name: 'Moby Dick', organization: 'Docker', birth_year: 2013},
    ];
    var tagline = "No programming concept is complete without a cute animal mascot";

    res.render('pages/index', {
        mascots: mascots, // this line and the one below is what I am not understanding
        tagline: tagline
    });
});

This particular tutorial is located here for reference: https://www.digitalocean.com/community/tutorials/how-to-use-ejs-to-template-your-node-application Nice introduction and I understand everything except these two lines.

A:     res.render('pages/index', {
        mascots: mascots,
        tagline: tagline
    });

this part passes down the mascots array and the tagline string to your view pages/index and then you can access both of them from your view.
I think what's confusing you is the naming. It doesn't necessarily have to be the same name.
For example if I name it like
    res.render('pages/index', {
        myMascotsArray: mascots,
        myTagline: tagline
    });

you can access the mascots array you defined as myMascotsArray from your view.
Referring the link you mentioned they have used EJS as the templating engine where you can write javascript between the <% %> tags.
Here you can notice that mascots array is accessed in the form of myMascotsArray from the view.

      <% myMascotsArray.forEach(function(mascot) { %>

          <%= mascot.name %>
          representing <%= mascot.organization %>,
          born <%= mascot.birth_year %>

      <% }); %>

redpajama_set_name: RedPajamaStackExchange


text:
Q: remove advance duplicate records (distinct in more than one columns in dataFrame) I want to remove the duplicated values in my pandas dataFrame.
my DataFram is like this:
#  col_1  col_2  col_3  col_4
1    a      a      1      1    # unwanted
2    a      b     0.7    0.5
3    a      c     0.5    0.3
4    b      a     0.7    0.5   # Duplicated
5    b      b      1      1    # unwanted
6    b      c     0.8    0.6
7    c      a     0.5    0.3   # Duplicated
8    c      b     0.8    0.6   # Duplicated
9    c      c      1      1    # unwanted

How we can improve this DataFrame and remove unwanted and duplicated rows?
may you think that this data frame is like a squared matrix and we can use np.tril but now it's not that
cus we need to calculate the rank of col_3 and col_4

A: In your case do np.sort then drop_duplicates
df[['col_1','col_2']] = np.sort(df[['col_1','col_2']].values,axis=1)
out = df.drop_duplicates(['col_1','col_2']).query('col_1!=col_2')
out
Out[118]:
  col_1 col_2  col_3  col_4
2     a     b    0.7    0.5
3     a     c    0.5    0.3
6     b     c    0.8    0.6

A: .drop_duplicates
df.drop_duplicates(subset =['col1', 'col2],
                     keep = False, inplace = True)


text:
Q: OS X keyboard shortcut to switch windows between same application
Possible Duplicate:
Switch between windows on Mac OS X?

OS X Snow Leopard Server
For Google Chrome or Terminal, is there any keyshort to switch different Chrome windows within Chrome? Since cmd+tab can only switch to different programs. Please advise, thanks.

A: You can configure the key combination in System Preferences » Keyboard » Keyboard Shortcuts (tab) » Keyboard and Text Input (left list) » Move focus to next window in application (right list). This works globally for all applications.

For Terminal the Windows have a CmdNumber combination assigned (e.g. Cmd1 for the first window).

You can display this shortcut in the window title in Terminal » Preferences… » Settings » (select your active settings) » Window (tab). Check Command key.
Additionally, the shareware Witch provides several different Window switchers, like "all windows of all applications" etc.


text:
Q: simplify python beautifulsoup find_all expression I have this python code with bs4 and request packages:
from bs4 import BeautifulSoup
import requests

url = "https://dolarhoy.com/"
page = requests.get(url)  # Carga contenido HTML de la URL pasada como parámetro
soup = BeautifulSoup(page.content, "html.parser")

values = soup.find_all('div', class_="values")
compra = values[0].find_all('div', class_="compra")
val = compra[0].find_all('div', class_="val")

print(val)

And the section of website I'm trying to scrape:

Compra

$181

Venta

$184

I'm trying to print [
$181
], I did it but with 2 lines of code:
compra = values[0].find_all('div', class_="compra")
val = compra[0].find_all('div', class_="val")

There is a way to simplify that with only one line?

A: You can use select instead of find_all. select('div.compra.val')
like this:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
divs = soup.select('div.compra.val')
print(divs)

A: You can directly find the class val on the soup instead of creating a separate variable to search for it.
from bs4 import BeautifulSoup
import requests

url = "https://dolarhoy.com/"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
print(soup.find("div", class_="val").text)

Output:
$181


text:
Q: Use AJAX to obtain an array from php database query What I am trying is obtain an array from a php file where I am making a query to a database. This array contains the results of that query.
But I cannot make AJAX work, I am unsure of how to use it.
It is my php code

$mysqli = new mysqli($servername, $username, $password, $dbname);

if($mysqli -> connect_error) {
  die('Connect Error ('.$mysqli -> connect_errno.') '.$mysqli -> connect_error);
}
$result = $mysqli -> query("SELECT * FROM Coordinates");

$coordinates = array();
while ($row = mysqli_fetch_assoc($result))
  $coordinates[] = $row["coordinate1"];
print json_encode($coordinates);
$mysqli -> close();

I have tried multiples approaches for use AJAX
This is one of them, but not sure what to write in the data parameter

function getData() {
  console.log("working here");
  jQuery.ajax({
    url : 'getInformation.php',
    type : 'POST',
    data: 'coordinates',
    dataType : 'json',
    success: function(data)
    {
      console.log("working here");
      alert(data[0]);
    },
  });
}

And the other one

function getData(){
  var res = new Array();
  jQuery(document).ready(function(){
    jQuery("#previous").click(function(){
      jQuery.getJSON("getInformation.php", function(data) {
        res[0]=data.$coordinates[0];
        jQuery("#result").html(res[0]);
      });
    });
  });
}

Which is the correct way of using AJAX?
Also, I am trying of return the array to another method.
How can I do that?
return data[0]?

A: $mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli - > connect_error) {
  die('Connect Error ('.$mysqli - > connect_errno.') '.$mysqli - > connect_error);
}
$result = $mysqli - > query("SELECT * FROM Coordinates");
$coordinates = array();
while ($row = mysqli_fetch_assoc($result))
  // $coordinates[] = $row["coordinate1"]; // change it like below
  $coordinates[] = array($row["coordinate1"]);
print json_encode($coordinates);
$mysqli - > close();

And after that simply fetch it by name with passing any parameters
In ajax response
alert(data);

A: It's good practice to set the content-type header when "echoing" JSON-data:
<?php
header('Content-Type: application/json');
.
.
echo json_encode($data);

When fetching data I would use the GET-method
$.getJSON( "getInformation.php", function( data ) {
    $("#result").html(data.coordinates[0]);
});

You can pass the returned data to another method as an argument, or you can set the returned data in a global variable the can be accesses from any method, just remember that the data won't be available before the data is returned from your request
var globalVar = "";
$.getJSON( "getInformation.php", function( data ) {
   //$("#result").html(data.coordinates[0]);
    globalVar = data; //OR
    myMethod(data);
});


text:
Q: Children of a Scene not releasing fast enough? Have a couple of child nodes in a scene, and do a quick transition to a new scene.
In the new scene, didMove(to view: ….) is used to add the children from the previous scene to this next scene.
SceneKit crashes when doing this quickly, seemingly because the children of the old scene haven't yet been released.
If I add a slight delay before adding the children to the second scene, it's fine… it seems SpriteKit isn't releasing the child fast enough for the scene transition.
the above is the most important thing to understand with regard the purpose for this question. I (wrongly) assumed SpriteKit would make sure all nodes attached to a scene were released before attempting to add them to a subsequent scene. It doesn't do this. But it does release them, it just takes a little time. Is this one frame? One second? Dunno...
My scene transition time is 0.25 seconds
Also tried using willMove(to view: ….) in the original scene to manually remove the children. This also doesn't work, seemingly same behaviour: not fast enough.
Also tried assuming the child still has a relationship to its parent, so tried moving to its new parent, the new scene, with move(toParent:…) this also crashes. So maybe the children are already flagged as about to be released, I suppose.
Is this known about, and if so, how is it dealt with?

A: You can't present a scene and have willMove function at the same time in the same frame (SK loop)--your next scene's viewDidLoad will be called before the previous scene is destroyed. You have to remove all of the nodes before calling presentScene:
I suggest making a global variable of some sort to access your SKView; with that you can have control over your scenes from anywhere:
currentScene.removeAllChildren()
gView!.presentScene(nextScene)

A:
"Is this a known about, and if so, how is it dealt with?"

Yes, this is a known issue of the SceneKit and IOS design and operational paradigms. It is considered that a scene must always be present and upon the screen. Can't have time without a scene onscreen.
As a result, for a brief time during transitions, both scenes are loaded, and active.
There are three ways to do deal with this problem:

*

*Remove all content from the old scene prior to executing the transition so it can be instantly loaded by the new scene in didMove(to view...
or

*Wait for completion of the transition before loading any content from the old scene into the new scene so there's no ownership conflicts of children.
or

*KnightOfDragon's first suggestion to use .copy() so there's not the same instances being fought over by the scenes.


text:
Q: Why is this public member function "undefined"? (C++) I am a student just starting learning C++ classes.
In the snippet below, why can't I access the public member function "difference" from main() and pass in account1 and account2? Error says that difference is undefined.
class BankAccount
    {
    public:
        double difference(BankAccount account1, BankAccount account2);
    private:
        double balance;
        double interest_rate;

        double fraction(double percent);
    };
    int main()
    {
        BankAccount account1, account2;

        account1.set(100, 5.0);
        account2.set(203,4.0);
        difference(account1, account2);

        return 0;
    }
    void BankAccount::set(int dollars, double rate)
    {
        if((dollars < 0)||(rate < 0))
        {
            cout << "Illegal values for money or interest rate.\n";
            exit(1);
        }
        balance = dollars;
        interest_rate = rate;
    }
    double BankAccount::difference(BankAccount account1, BankAccount account2)
    {
        return account1.balance - account2.balance;
    }

A: This function is a non-static member function so you cannot call like this
difference(account1, account2);

You must call it on an instance of the class BankAccount like you did previously here
account1.set(100, 5.0);

Calling it in the way you have will only work for a stand alone function, not a member function.


text:
Q: Migrating sales from xl to odoo using XML-RPC Im trying to migrate sales order from excel sheet to odoo using xmlrpc so far i have the products working,client working but when i try to insert the sale order i get this error
Traceback (most recent call last):
  File "/home/oasis/PycharmProjects/somig/migrator.py", line 75, in <module>
    'validity_date':"2016-01-18",
  File "/usr/lib/python2.7/xmlrpclib.py", line 1243, in __call__
    return self.__send(self.__name, args)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1602, in __request
    verbose=self.__verbose
  File "/usr/lib/python2.7/xmlrpclib.py", line 1283, in request
    return self.single_request(host, handler, request_body, verbose)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1316, in single_request
    return self.parse_response(response)
  File "/usr/lib/python2.7/xmlrpclib.py", line 1493, in parse_response
    return u.close()
  File "/usr/lib/python2.7/xmlrpclib.py", line 800, in close
    raise Fault(**self._stack[0])
xmlrpclib.Fault: <Fault 1: 'Traceback (most recent call last):\n  File "/usr/lib/python2.7/dist-packages/openerp/service/wsgi_server.py", line 56, in xmlrpc_return\n    result = openerp.http.dispatch_rpc(service, method, params)\n  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 114, in dispatch_rpc\n    result = dispatch(method, params)\n  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 37, in dispatch\n    res = fn(db, uid, *params)\n  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 173, in execute_kw\n    return execute(db, uid, obj, method, *args, **kw or {})\n  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 118, in wrapper\n    return f(dbname, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 181, in execute\n    res = execute_cr(cr, uid, obj, method, *args, **kw)\n  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 170, in execute_cr\n    return getattr(object, method)(cr, uid, *args, **kw)\n  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 250, in wrapper\n    return old_api(self, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 354, in old_api\n    result = method(recs, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/addons/sale/sale.py", line 232, in create\n    result = super(SaleOrder, self).create(vals)\n  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n    return new_api(self, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/addons/mail/models/mail_thread.py", line 233, in create\n    thread = super(MailThread, self).create(values)\n  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n    return new_api(self, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4157, in create\n    record = self.browse(self._create(old_vals))\n  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 248, in wrapper\n    return new_api(self, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 490, in new_api\n    result = method(self._model, cr, uid, *args, **old_kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4301, in _create\n    tuple([u[2] for u in updates if len(u) > 2])\n  File "/usr/lib/python2.7/dist-packages/openerp/sql_db.py", line 141, in wrapper\n    return f(self, *args, **kwargs)\n  File "/usr/lib/python2.7/dist-packages/openerp/sql_db.py", line 220, in execute\n    res = self._obj.execute(query, params)\nProgrammingError: column "partner_id" is of type integer but expression is of type integer[]\nLINE 1: ...1, NULL, \'draft\', 6, 1, 1, \'2016-09-03 16:50:24\', ARRAY[6], ...\n                                                             ^\nHINT:  You will need to rewrite or cast the expression.\n\n'>

Process finished with exit code 1

my code is the following
import psycopg2
import psycopg2.extras
import pyexcel_xls
import pyexcel as pe
from pyexcel_xls import get_data
from datetime import datetime
import xmlrpclib
import json

url = 'http://localhost:8070'
db = 'fresh'
username = 'admin'
password = 'odoo'
#data = get_data("salesorder.xls")
#print(json.dumps(data))
records = pe.get_records(file_name="salesorder.xls")
for record in records:
    print record['name']
    names = record['name']
    print record['location']
    print record['zip']
    print record['republic']
    dates = record['date']
    print dates
    print datetime.strptime(dates,'%d/%M/%Y')
    lastdat=datetime.strptime(dates,'%d/%M/%Y')
    print record['product']
    productname= record['product']

#Check if the customer is in or else insert him
    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    uid = common.authenticate(db, username, password, {})
    output = common.version()
    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
    partnerids = models.execute_kw(db, uid, password,
                    'res.partner', 'search', [[['name', '=', record['name']]]])

    if partnerids:
        print partnerids

    else:
        newpartn = models.execute_kw(db, uid, password, 'res.partner', 'create', [{
            'name': names,
        }])
        partnerids=newpartn
        print partnerids
#Check if a product is in else insert a new product
    common = xmlrpclib.ServerProxy('{}/xmlrpc/2/common'.format(url))
    uid = common.authenticate(db, username, password, {})
    output = common.version()
    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
    productids = models.execute_kw(db, uid, password,
                                   'product.product', 'search', [[['name', '=', record['product']]]])

    if productids:
        print productids

    else:
        newproduct = models.execute_kw(db, uid, password, 'product.product', 'create', [{
            'name': productname,
            'default_code': partnerids
        }])
        productids=newproduct
        print productids

    uid = common.authenticate(db, username, password, {})
    print output
    models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
    id = models.execute_kw(db, uid, password, 'sale.order', 'create', [{
        'partner_id': partnerids,
     #   'name': names,
        'validity_date':"2016-01-18",
        #'payment_term_id':1,
        # 'user_id':"1"
        # 'state':"sale"

    }])
    print id

the 75th line is the one of validity date

A: I think the issue is that you execute a search for partnerids which will result in an array. However if you do not find any you create a partner which is represented by an integer. You then assign partnerids to the partner_id in your sale.order.
Sometimes you are assigning it an integer and other times an array, depending on if you are using the partnerids from the search or the newly created partner.
If you are sure that your search for partnerids will never result in two partners having the same name then you can use the first record returned in your search which I display below. I reassigned partnerids on a second line simply to illustrate the difference.
If you are not sure if you have duplicates this will be the wrong thing to do and you should refine your search to select the correct partner.
    partnerids = models.execute_kw(db, uid, password,
                'res.partner', 'search', [[['name', '=', record['name']]]])
    partnerids = partnerids[0] if partnerids else False

if partnerids:
    print partnerids

else:
    newpartn = models.execute_kw(db, uid, password, 'res.partner', 'create', [{
        'name': names,
    }])
    partnerids=newpartn

A: The Error message says:

ProgrammingError: column "partner_id" is of type integer but expression is of type integer[].

Just give partnerids as an integer:
if partnerids:
   partnerids = partnerids[0]
   print partnerids


text:
Q: .htaccess rewrite / accept language following problem:
I have 2 html sites in subfolders, one site in English and one in German. I use .htaccess rewrite rule to redirect to the right site based on the language of the user:
RewriteCond %{HTTP:Accept-Language} ^de [NC]
RewriteRule ^$ http://example.com/ [L,R=301]

This is the code in the .htaccess in the subfolder of the English version.
The problem occurs when a German user wants to view the English version of the page, he always gets redirected to the German version.
Is there any way to redirect the user on the first visit, but when he clicks on the hyperlink English on the German page, he gets to see the English version, without being redirected again to the German site?
mod-rewrite is available but I need a condition to redirect only once (on first visit) and when the user clicks a specific hyperlink, he wont get redirected again?

A: Just an idea, if you have two subdirectores, e.g. de and en, you could rewrite instead of redirect based on Accept-Language header. But if the browser requests an explicit path including the language prefix, it won't be redirected.

*

*http://www.example.com/page1.html will show /en/page1.html or /de/page1.html depending on Accept-Language

*http://www.example.com/en/page1.html will always show /en/page1.html no matter what Accept-Language says

You could try these (untested!) rules
RewriteRule ^en/ - [L]
RewriteRule ^de/ - [L]

RewriteCond %{HTTP:Accept-Language} ^de [NC]
RewriteRule ^ /de%{REQUEST_URI} [L]

RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^ /en%{REQUEST_URI} [L]

Another approach could be to set a cookie, when the user decides on a language, and deliver pages according to this cookie.


text:
Q: Does adding return statements for C# methods improve performance? This blog says

12) Include Return Statements with in the Function/Method.
  How it improves performance
  Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function/method is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions/methods and insert return as needed. It doesn't change the semantics of the code at all, and it can help you get more speed from your application.

I'm fairly sure that this is a false statement. But wanted to get the opinion experts out there. What do you guys think?

A: The post is kind of vague. Being a C# developer, my first thought was "as opposed to what?". However, he could be referring to something like:
public bool MyFunction()
{
    bool result = false;
    if (someCondition == true)
    {
        // Do some processing
        result = true;
    }
    else if (someOtherCondition == true)
    {
       // Do some processing
       result = true;
    }
    // ... keep going

    return result;
}

He may be suggesting that replacing the result = true; statements with return true; may perform better.  I'm not sure about that personally... that's pretty deep into JIT theory at that point, and I think any gains that are made would be very minor compared to other performance improvements that you could make.

A: I'd disagree - I think a single in and single out of every method makes code much easier to read and debug. Multiple return statements in a function can make navigating code more comlpex. In fact (if possible to refactor) its better to have more smaller functions than say larger functions with multiple exits.

A: It is somewhat true, both for VB.NET and C#.  In C# the programmer has to declare the variable that holds the return value explicitly, it is automatic in VB.NET.  Most return values are returned in the EAX or RAX register, the JIT compiler has to generate code to load the register from the return value variable before the function exits.  When you use the return statement, the JIT compiler might have the opportunity to load the EAX register directly, or already have the register containing the correct value, and jump to the function exit code, bypassing the load-from-variable instruction.
That's a pretty big "might" btw, real code invariably tests some expression with the if() statement.  Evaluating that expression almost always involves using the EAX register, it still has to be reloaded with the return value.  The x64 JIT compiler does a completely different job doing that compared to the x86 compiler, the latter always seems to use the variable in a few spot checks I did.  So you're not likely to be ahead unless you run on a 64-bit version of Windows.
Of all the evil in premature optimization, this one is arguably the worst.  The potential time savings are minuscule, write your code for clarity first.  Profile later.

A: This statement does not apply to C#.
With C# you must explicitly set a "return" to have a valid function, without a return, you get a compile error to the effect of "not all code paths return a value".
With VB.NET this would apply as VB.NET does NOT have the requirement for an explicit return, and allows you to have functions that never return a value, as well as allow you to set the return using the name of the function.
To provide an example
In VB.NET you can do this
Function myFunction() As String
    myFunction = "MyValue"
End Function

Function myFunction2() As String
    'Your code here
End Function

The above compiles, neither with an explicit "returns", there is more overhead involved in this.
If you try to do this with C#
string myFunction()
{
    //Error due to "Cannot assign to 'myFunction' because it is a 'Method Group'
    myFunction = "test";
}

string myFunction2()
{
    //Error due to "not all code paths return a value
}

My comments note the errors that you get.

A: My only guess here is that he's talking about VB.NET not C#.  VB.NET allows you to somethin like this to return values
Public Function GetSomething() As Int
     GetSomething = 4
End Function

My VB is incredibly out of date though.  This may be slower that using an explicit return statement

A: Generally there are 2 spots in which I exit a function.
At the very beginning of my methods to validate incoming data:
if (myParameter == null)
   throw new ArgumentNullException("myParameter");

And/or at the very end of the method.

private bool GetSomeValue()
{
    bool returnValue = false;
    // some code here
    if (some condition)
    {
        returnValue = some expression
    }
    else
    {
        returnValue = some other expression;
    }
    return returnValue;
}
The reason I don't return inside of the conditional, is so that there is 1 exit point of the function, it helps with debugging. No one wants to have to maintain a method with 12 return statements in it. But that is just a personal opinion of mine. I would err on the side of readability, and not worry about optimization unless you're dealing with a real-time must-go-faster situation.


text:
Q: Unexpected value of this when inside a constructor function I have this code:

const foo = function() {
  console.log(this) // foo {}

  function bla() {
    console.log(this) // Window {}
  }
  bla()
}

let a = new foo()

Why does the first console.log(this) returns the foo object but the second one inside the function returns the Window object if the foo function is used as a constructor? Shouldn't both console.log(this) return the foo object?


text:
Q: Sorting Table in hierarchical order Is it possible to sorting queries table in hierarchical order like this:
Expected
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| ID | Code   |  Name     | Qty   | Amount | is_parent | parent_id | remarks |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 1  | ABC    | Parent1   |  2    | 1,000  |     1     |     0     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 4  | FFLK   | Product Z |  10   | 2,500  |     0     |     1     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 5  | P6DT   | Product 5 |  7    | 1,700  |     0     |     1     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 6  | P2GL   | Product T |  5    | 1,100  |     0     |     1     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 2  | DHG    | Parent2   |  5    | 1,500  |     1     |     0     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 3  | LMSJ   | Product U |  4    | 600    |     0     |     2     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+

This is the original data table:
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| ID | Code   |  Name     | Qty   | Amount | is_parent | parent_id | remarks |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 1  | ABC    | Parent1   |  2    | 1,000  |     1     |     0     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 2  | DHG    | Parent2   |  5    | 1,500  |     1     |     0     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 3  | LMSJ   | Product U |  4    | 600    |     0     |     2     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 4  | FFLK   | Product Z |  10   | 2,500  |     0     |     1     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 5  | P6DT   | Product 5 |  7    | 1,700  |     0     |     1     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+
| 6  | P2GL   | Product T |  5    | 1,100  |     0     |     1     | xxx     |
+----+--------+-----------+-------+--------+-----------+-----------+---------+

is_parent column = 1 if data row set to parent, 0 if data row set to child
parent_id column = 0 if data row set to parent, depend on ID of parent data

I'm using SQL Server to generate the data.

A: It looks like the actual question is how to query the data in hierarchical order. This is possible using recursive queries but a faster alternative is to use SQL Server's support for hierarchical data.
A recursive query that returns the data in hierarchical order would look like this :
WITH h AS
(
      SELECT
             ID,Code,Name,Qty,Amount,is_parent,parent_id,remarks
      FROM
            dbo.ThatTable
      WHERE
            parent_id=0
      UNION ALL
      SELECT
             c.ID,c.Code,c.Name,c.Qty,c.Amount,c.is_parent,c.parent_id,c.remarks
      FROM
            dbo.ThatTable c
      INNER JOIN h ON
            c.parent_id= h.Id
)
SELECT * FROM h

This query's performance will be acceptable if the ID and Parent_ID fields are indexed, but not great.
Adding a hierarchyid field to the table would make the query simpler and far faster. Assuming there's a hierarchy field, the query would be just :
SELECT *
FROM ThatTable
ORDER BY hierarchy

Adding an index on hierarchy will this query and any query that looks eg for children of a specific node, very fast. Instead of querying recursively, the server only needs to look into that single index.
The article Lesson 1: Converting a Table to a Hierarchical Structure shows how to create a new table with a hierarchyid and populate it from parent/child data.


text:
Q: gadgets.window.adjustHeight() calculates height of the gadget incorrectly I am writing an opensocial gadget. My structure is something like this:

Comments are loaded here.

I update the content of the "dComment" every second, and its content gets some scrolling.
In my gadget I have specified <Require feature="dynamic-height"/>
When I use gadgets.windows.adjustHeight() it calculates the height of the content regardless that I have made some part of it hidden through adjusting a height for my outer div. As a result I see a huge white space below my content !!!
I know that I can specify height for adjustHeight function. But then it means that on every update I have to calculate the height of the gadget myself, and I don't want to do it (if possible).
Can someone explain to me why it happens and how can I solve it ?

A: Instead of visibility:hidden use display:none


text:
Q: Java JAX-WS multiple web services for fail over configuration and architecture I have a java Swing application client and multiple glassfish servers with different names running copies of the same Stateless EJB JAX-WS for fail over.
First, is this a proper way to set up fail over and are there any resources available to help?
Secondly, the way I did it was to import all methods from the web services into seperate java classes then have a separate management class that calls each method.  Within each method call it determines the appropriate connection (i.e. if the web service call fails it increments to the next web service). The problem is this is a large amount of code that is difficult to maintain as it is not an efficient method.
Any help is much appreciated, thank you.

A:
First, is this a proper way to set up fail over

I recommend to use an application server with clustering capabilities, e.g. GlassFish v3.1
http://glassfish.java.net/public/clustering31.html


text:
Q: Rotating the findspeaks function from columns to rows I have a small function that finds the peaks in a matrix and then replacing it by 0. The end output is related to the columns. I'm having hard time fixing the syntax to make it work the same way but for the rows as well. Any ideas ? Here's the code :
HVAzimuthFreqAbs = abs(HVAzimuthFreq);
M = HVAzimuthFreqAbs;
for k1 = 1:size(M,1)
[pks,loc] = findpeaks(M(k1,:),'Threshold',150);
P{k1} = [pks; loc];
end
HVAzimuthFreq(:,loc) = 0;

The main key as I understand is to switch between the order that the size refers to, but I have no luck in doing that. For example -
for k1 = 1:size(1,M)
[pks,loc] = findpeaks(M(:,K1),'Threshold',ThresholdUpper);
P{k1} = [pks; loc];
end

is giving me an 'Dimension argument must be a positive integer scalar within indexing range' error.
Any ideas ?
thanks

A: Your error is at the for line, size(1,M) makes no sense. Use size(M,2) to get the number of columns.
You are indexing the columns as M(:,K1), this is correct.


text:
Q: How to style Bootstraps collapsable Navbar? I've made a website using bootstrap, I don't know much about this framework. What I'm having difficulty with is styling the navbar.
What I would like to do is move the name, and three titles, 'work', 'about', and 'contact', to the left corner of the page, and move the social media icons, to the right corner of the page. Could someone instruct me on how I could do this while still retaining the functions that bootstrap offers?
Here is a jsfiddle: https://jsfiddle.net/3kq7ptxd/
The jsfiddle looks different from the actual website, so if you go on paulopinzon.com you will maybe get a clearer idea of what I'm attempting.
Thanks for taking the time! I will try to experiment with things in the mean time, but if someone with more experience could help that would be much appreciated.
Have a good day
HTML:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="css/yourCustom.css" rel="stylesheet"/>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

  <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle"> Toggle navigation

  </button> Paulo Pinzon-Iradian

Work

About

Contact

A: Change the navbar .container to .container-fluid.
Basically .container-fluid continuously re-sizes on change of viewport and leaves no extra empty space on the sides ever, unlike .container.
.container-fluid has the CSS property width: 100%;, so it continually readjusts at every screen width granularity.

      <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle"> Toggle navigation

      </button> Paulo Pinzon-Iradian

Work

About

Contact

CODEPEN DEMO

A: Try to add following code to your css styles, did it what you wanted to?
nav .container {
    margin: 0 auto;
    width: 100%;
}

A: from

to


text:
Q: GrapesJs CLI: modify webpack5 to add multiples entry js + scss i am trying to configure a plugin with multiple js entry point in my webpack;

Each JS contain the JS fuctions and import the style in scss format (that scss file will be process with a loader in webpack)

My goal is get something like this

already is working but if you open the vars.js file, is not generated correctly and also the (vars.js.map) is not generated, the rest of the files are perfect
this is my code code sandbox
you have to execute the build task to debug
Example in code sandbox
I am trying different ways to export this and nothing works fine
I am not a expert in webpack, i think is something about rewriting the (entry, output)...
Thanks for any advice or solution
Grapes Cli contains default config for webpack
if helps, this is what i get when modify the config

A: i found a solution, in case someone needs
      output: {
        // ...output,
        path: path.resolve(path.join(__dirname, "./dist")),
        filename: '[name].js',
        chunkFilename: '[name].js',
        library: 'bootstrap-xditor',  //<-- add this line
        libraryTarget: 'umd', //<-- add this line
        globalObject: "typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : this)"//<-- add this line
    },

i really don't understand but works so next..


text:
Q: Simplify format of dotnest test in VS 2017 I just upgraded my project CoreCLR project from project.json to VS 2017 new project system.
I used to run dotnet test and be able to monitor the behavior of the test by the generated output.
Here is what this looks like now when I do this:
[xUnit.net 00:00:01.9090123] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.Blittable.BlittableJsonWriterTests.Jsons"...)' (ID = '12c17a0046f4fbe9b16c1798e3057b5f02b112e2')
[xUnit.net 00:00:01.9096663] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.Blittable.BlittableJsonWriterTests.Jsons"...)' (ID = '24c3e96e41b952be76f4657d0c1a7a7a258ffd25')
[xUnit.net 00:00:01.9103176] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.Blittable.BlittableJsonWriterTests.Jsons"...)' (ID = 'd3707855dfae4131eabea842fa6e8465b214d084')
[xUnit.net 00:00:01.9109622] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.Blittable.BlittableJsonWriterTests.Jsons"...)' (ID = '16490b71e95b77e457f05e490a0cdb9404219d24')
[xUnit.net 00:00:01.9115769] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.Blittable.BlittableJsonWriterTests.Jsons"...)' (ID = 'c2225f8966c137f8778231513e9f60783cdf0c32')
[xUnit.net 00:00:01.9122278] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.obj.project.assets.json")' (ID = 'de7174b0a2323679ac7e95f73ef05d53e6d52e85')
[xUnit.net 00:00:01.9128720] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.CanReadAll(name: "FastTests.project.lock.json")' (ID = 'c5e178685f79e30802a445bbc9876b7b469ca86d')
[xUnit.net 00:00:01.9134546] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.FailsOnInvalidJson(invalidJson: "sssssssssssssssss{\"Name\":\"Oren\"}")' (ID = '485d46e96733356e1a84e0e6b834c649e58e2bf9')
[xUnit.net 00:00:01.9149860] FastTests: Discovered [execution] test case 'FastTests.Blittable.BlittableJsonWriterTests.UnmanageJsonReaderTests.FailsOnInvalidJson(invalidJson: "nnnnnnnnnn{\"Name\":\"Oren\"}")' (ID = 'b9268bfd32d924b6d2cf74b6f7bd33ca8e81310c')
[xUnit.net 00:00:02.6243807]   Discovered:  FastTests (running 1337 test cases)
[xUnit.net 00:00:02.9805881]   Starting:    FastTests (parallel test collections = on, max threads = 3)
        To attach debugger to test process, use process id: 1148
[xUnit.net 00:00:24.8661538]     FastTests.Blittable.BlittableJsonWriterTests.ConcurrentAccessTests.ConcurrentReadsTest [SKIP]
[xUnit.net 00:00:24.8664404]       RavenDB-6309
Skipped  FastTests.Blittable.BlittableJsonWriterTests.ConcurrentAccessTests.ConcurrentReadsTest
[xUnit.net 00:00:26.2805469]     FastTests.Client.Queries.FullTextSearchOnTags.UsingSuggest [SKIP]
[xUnit.net 00:00:26.2808014]       RavenDB-6573
Skipped  FastTests.Client.Queries.FullTextSearchOnTags.UsingSuggest
[xUnit.net 00:00:58.3486626]     FastTests.Server.Documents.Indexing.Auto.BasicAutoMapIndexing.IndexCreationOptions [SKIP]
[xUnit.net 00:00:58.3487989]        TODO - Efrat Indexes
Skipped  FastTests.Server.Documents.Indexing.Auto.BasicAutoMapIndexing.IndexCreationOptions
[xUnit.net 00:01:09.0771217]     FastTests.Blittable.BlittableJsonWriterTests.FunctionalityTests.FunctionalityTest2 [SKIP]

This is a huge wall of text, and the information provided for (I assume) the VS Test runner is obscuring any possibility of mine to actually see what is going on.
Is there a way to go back to the simpler output?

A: Turns out that I had to set this:
"diagnosticMessages": false,

To reduce a lot of the clutter.


text:
Q: Creating trackable QR codes I'm having trouble understanding how to track qr codes in general with wechat if this was just a QR that leads to my personal website I would just do say mysite.com?utm_source=marketing&utm_medium=Tyler and I would be able to see if because mysite is attached to my Google analytics account.
However with wechat the URL I have to use for the qr code looks something like this http://weixin.qq.com/q/02dz0Vxg6Weq110dddd00g03c as the QR URL The problem I have here is there is no way for me to track that URL since it is not my domain.
Do I need to have the QR code go to my site and setup a redirect there that leads to the wechat URL?


text:
Q: A way to launch x applications as administrator automatically (Windows xp) The problem is that in our clients their normal user doesn't have administrator privileges so when they have to install or update our programs they have to log again as administrator to install them and then log as their user which is cumbersome...
As some updates are automatic the "run as" solution isnt a valid one...
One good idea would be to mark a folder as "admin folder" so all the exes executed from that folder run as administrator (having configured the admin account previously)
or a configurable a list of executable names that must run as administrator (i say names because it could be different installers with different hash but with a generic exe name that identifies it as ours)
Does anyone know a program or windows configuration or c# code to achieve something like this?

A: It seems nobody knows how to do it or doesnt want to tell because its a security hole...ironically having this escalating privileges hole would be better than having the user as administrator for everithing :S... (Appart from not being a valid solution for our clients)


text:
Q: "X is famous" vs. "X was famous" When saying a sentence like:

Nikola Tesla __ famous because he was a genius.

Should the blank be replaced by is or was?
Or is it dependent on when the person is/was famous? If so, what exactly are the rules?
I searched on Google and English.SE but didn't find an answer, even after using quotes to counter the amount of stop words in the question...

A: The state of being famous can vary with time, so if he is still famous, and you're talking about his modern fame rather than his past fame, then use "is". But if you're talking about his past fame, especially if he is no longer famous, use "was". Or if you want to emphasize the reason why he got famous at the time, use "became".
He is famous for his genius.
He was famous because people liked geniuses back then.
He became famous because he knew how to work the press.


text:
Q: How to create One ThreadPoolExecutor per user? I have a requirement where we have to create ThreadPoolExecutor for per tenant. Concurrently I am using Spring given @Async Annotation but that is for whole application. So if the server is busy with one tenant, it will affect the other user's tenant. @Async is configured with ThreadPoolExecutor.
But it is common for all users across tenant.
EDIT :
I need Thread Pool for per Tenant.
In simply language, I need to share ThreadPool for the group of users. All the users from that group can use the same threadPool.
How is that possible with existing java API's. Please Help.
How to seperate out ThreadPool for Tenants?
For Ex : Tenant 1 is assigned some 20 threads, so all users (U1,U2....) can use that threadPool and it will not affect another tenant.
Same with Tenant 2, it will be assigned some 20 threads....

A: Not to discuss whether it is a "good requirement" or not - easy-peasy:

*

*(Extend ThreadPoolTaskExecutor in a custom class and...) add a @SessionScoped @Bean of it to your application context.

*Use it. (In controllers via @Async annotation)

Like:
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;

@Component
@SessionScope
public class MyThreadPoolExecutor extends ThreadPoolTaskExecutor {

   // only for test-/debuging
   static volatile int cnt = 0;

   public MyThreadPoolExecutor() {
      // only for test-/debuging
      System.out.format("MyThreadPoolExecutor#%d%n", cnt++);
   }
}

Using it in a simple controller like this:
@Async // !
@GetMapping("/hello")
@ResponseBody
public Future<String> hello() {
    return new AsyncResult("Hello");
}

..I get MyThreadPoolExecutor logging, when (and only when) using a new incognito browser/session/user.


text:
Q: libxml-ruby on windows xp problem About a month ago I installed libxml-ruby using
gem install libxml-ruby
and it worked fine.
Then i went to install it on another machine today and it failed with this error:
C:\Windows\system32>gem install -r libxml-ruby
Building native extensions.  This could take a while...
ERROR:  Error installing libxml-ruby:
        ERROR: Failed to build gem native extension.

c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.4/bin/rake RUBYARCHDIR=c:/ruby/lib/ruby/
gems/1.8/gems/libxml-ruby-1.1.3-x86-mswin32-60/lib RUBYLIBDIR=c:/ruby/lib/ruby/g
ems/1.8/gems/libxml-ruby-1.1.3-x86-mswin32-60/lib
'c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.4/bin/rake' is not recognized as an int
ernal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/libxml-ruby-1.
1.3-x86-mswin32-60 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/libxml-ruby-1.1.3-x86-mswin32-6
0/ext/mingw/gem_make.out

I have rake installed and win32-api
I then got confused if I had really installed libxml-ruby on my machine previously and tried uninstalling and reinstalling it. It now fails with the same error message on my machine and some scripts i've written to parse xml, which used to work, no longer work. Has anyone else tried installing libxml-ruby lately on windows xp? It appears to be completely broken.

A: I got the same problem, and ended up figuring out a decent work-around.
It seems the error is correct
'c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.4/bin/rake'

isn't a valid executable.  It needs to run rake from the root ruby/bin folder, where the wrapping batch file can be found.
Rummaging through the rubygems code, I found that Gem::Ext::RakeBuilder tries to build extensions using
cmd = ENV['rake'] || Gem.bin_path('rake') rescue Gem.default_exec_format % 'rake'

So, simply setting the rake environment variable to something valid before running the gem install should help:
C:\>set rake=c:\ruby-1.8.6-26\bin\rake.bat

C:\>gem install libxml-ruby --no-rdoc --no-ri
Building native extensions.  This could take a while...
Successfully installed libxml-ruby-1.1.3-x86-mswin32-60
1 gem installed

(I skipped installing rdoc and ri because it prints out a bunch of formatting warnings, making it more difficult to paste the results in here.)


text:
Q: Vue.js unit:testing - How to handle a mixin and pass it props I am trying to test my AudioPlayer component which is using a mixin ( vue-howler)
<script>
import VueHowler from "vue-howler";

...

export default {
  mixins: [VueHowler],
  name: "audioPlayer",
  data() {
    return {
      percentage: 0
    };
  },
...
</script>

I need to pass props to the mixin , how can I do that ?
  sources ( an Array of audio files ), autoplay (Boolean ) , ...

my AudioPlayer.spec.js
import Vue from "vue";
import { shallowMount } from "@vue/test-utils";
import Vuetify from "vuetify";
import AudioPlayer from "@/components/Home/AudioPlayer.vue";
import VueHowler from "vue-howler";

describe("AudioPlayer.vue", () => {
  beforeEach(() => {
    Vue.use(Vuetify);
    const el = document.createElement("div");
    el.setAttribute("data-app", true);
    document.body.appendChild(el);
  });

  const sourceFiles = [require("@/assets/audio/ultimo_desejo.mp3")];

  it("should emit an event PLAY/PAUSE  from playPauseBtn", () => {
    // given
    const wrapper = shallowMount(AudioPlayer, {
      attachToDocument: true,
      mixins: [VueHowler]
    });
    wrapper.setData({ paused: true, playing: false });
    console.log(wrapper.html());
  });

vue-howler mixin
import { Howl } from 'howler'
import clamp from 'math-clamp'
import values from 'object-values'
import assign from 'object-assign'

export default {
  props: {
    /**
     * An array of audio file urls
     */
    sources: {
      type: Array,
      required: true,
      validator(sources) {
        // Every source must be a non-empty string
        return sources.every(
          source => typeof source === 'string' && source.length > 0
        )
      }
    },
    /**
     * Whether to start the playback
     * when the component is mounted
     */
    autoplay: {
      type: Boolean,
      default: false
    },
    /**
     * Whether to start the playback again
     * automatically after it is done playing
     */
    loop: {
      type: Boolean,
      default: false
      ....

A: SOLVED ... need to pass the propsData BEFORE the mixins in the shallowMount
  const sourceFiles = ['require("@/assets/audio/ultimo_desejo.mp3"']

  it("should emit an event PLAY/PAUSE  from playPauseBtn", () => {
    // given
    const wrapper = shallowMount(AudioPlayer, {
      // attachToDocument: true,
      propsData: {
        sources: sourceFiles,
        autoplay: false,
        loop: false
      },
      mixins: [VueHowler]
    });
    wrapper.setData({ paused: true, playing: false });
    console.log(wrapper.html());
  });


text:
Q: Make a form that pulls choices from table in DB and then allows user to change to different foreign keys So I have a user model with the following columns:
username = models.CharField(db_column='Username',max_length=32,unique=True)
email = models.CharField(db_column='Email',max_length=255)
password = models.CharField(db_column='Password',max_length=128)
prosthodontist = models.ForeignKey('Prosthodontist',on_delete=models.SET_NULL,null=True)

I'm trying to make a dropdown that allows the user to change their Prosthodontist value through django forms.  It can't be a static list cause it has to always have every available Prosthodontist as they get added.
Just for show this is what I have so far along the lines of the form:
class ChangeProsthodontistForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('prosthodontist',)

    prosthodontist = forms.ChoiceField(
        label = "Prosthodontist",
        widget = forms.Select(
            attrs={
                'id':'prosthodontist',
            },
        ),
        choices=()
    )

Please help me with this cause I'm really confused I feel like I could be able to iterate through the entries with a for loop but I feel like there has to be a better way through Django.

A: You answer is ModelChoiceField.
prosthodontist = forms.ModelChoiceField(
    # ...
    queryset = Prosthodontist.objects.all(),
    # ...
)


text:
Q: App to check if other user is online I need to alternate with a friend in doing a job online. I just want a simple app that let me know if my friend is online and vice-versa. Something like facebook green dot next to a friend's name which can be activated and deactivated manually.
This way if I see my friend is working (green dot) I just wait until he goes offline to take his place. No needs for fancy features.
Which software can I use?
Also an android app could be suitable for us.

A: Any of the Instant messaging clients will do it - from Skype, Viber, heck even the FB messenger will do this.
make your pick

A: Implement Broadcast Receiver Class as follows which will send broadcast whenever internet is online:
public class InternetReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        boolean isConnected = new ConnectionDetector(context)
                .isConnectedToInternet();
        if (isConnected) {
            //user is connected
        }
    }

public boolean isConnectedToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
}

In Manifest define as :
<receiver android:name="com.example.InternetReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>


text:
Q: ClassNotFoundException while running wordcount jar file on single node single cluster hadoop file system I got an error like this while running my jar file on single node single cluster hadoop file system
The error I got:
hduser@jameena-X556UA:/usr/local/hadoop$ bin/hadoop jar /home/jameena/Desktop/wordcountf/wordcountj.jar WordCountpro /usr/jameena3/inputdata/test.txt /usr/jameena3/outputwc
Exception in thread "main" java.lang.ClassNotFoundException: WordCountpro
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:214)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

Here's my code
import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class WordCountpro {
    //Mapper class
    public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        public void map(LongWritable key, Text value,Context contex) throws IOException, InterruptedException {
            String line=value.toString();
            StringTokenizer tokenizer = new StringTokenizer(line);
            while (tokenizer.hasMoreTokens()) {
                word.set(tokenizer.nextToken());
                contex.write(word, one);
            }
        }
    }
    //Reducer class
    public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        public void reduce(Text key, Iterable<IntWritable> values, Context context)throws IOException,InterruptedException {
            int sum = 0;
            for(IntWritable val:values)
            {
                sum+=val.get();
            }
            context.write(key, new IntWritable(sum));
        }
    }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = new Job(conf,"WordCountjob");
        job.setJarByClass(WordCountpro.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.waitForCompletion(true);
    }
}


text:
Q: Segfault when running JavaFX and Swing from IntelliJ When running the following minified example from IntelliJ 2016.1 Community edition, I always encounter a segmentation fault:
import javax.swing.*;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Repro extends Application {

    public static void main(String[] args) {
        JFrame swingFrame = new JFrame();
        swingFrame.setTitle("Repro start");
        swingFrame.setSize(200, 350);
        swingFrame.setVisible(true);

        Application.launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Pane root = new Pane();
        root.setMinHeight(200);
        root.setMinWidth(350);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
}

The environment is as follows:

*

*Ubuntu 15.10

*openjdk-8 (1.8.0_u66 build 17)

*openjfx-8 (8u60-b27-4)

*IntelliJ 2016.1 Community Edition (build #IC-145.258)

The issue is not reproducible by running javac into java
The problem also does not show when running through oraclejdk (1.8.0_u77-b03)
For reference the "output" of the program is as follows:
Prism-ES2 Error : GL_VERSION (major.minor) = 1.4
Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" Exception in thread "JavaFX Application Thread" #
# A fatal error has been detected by the Java Runtime Environment:
#
#  Internal Error (safepoint.cpp:712), pid=16937, tid=140197878814464
#  fatal error: Illegal threadstate encountered: 6
#
# JRE version: OpenJDK Runtime Environment (8.0_66-b17) (build 1.8.0_66-internal-b17)
# Java VM: OpenJDK 64-Bit Server VM (25.66-b17 mixed mode linux-amd64 compressed oops)
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/vogel612/.../hs_err_pid16937.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#

Process finished with exit code 134

The problem persists after running ulimit -c unlimited and restarting IntelliJ
As requested, the error log for one such execution is available at this gist.
How can I fix this behaviour?

A: The error can be reproduced outside IntelliJ as follow.
public class Main {
    public static void main(String[] args) throws Exception {
        new Repro().main(new String[0]);
    }
}

running java -cp . Main on Ubuntu 15.10 with

openjdk version "1.8.0_66-internal"
  OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)
  OpenJDK 64-Bit Server VM (build 25.66-b17, mixed mode)

produces the same fatal error. Whereas running java -cp . Repo does not fail.
running java -cp . Main on CentOS 7 with

openjdk version "1.8.0_77"
  OpenJDK Runtime Environment (build 1.8.0_77-b03)
  OpenJDK 64-Bit Server VM (build 25.77-b03, mixed mode)

opens the Swing JFrame and the JavaFX Pane.
Seems this issue is related to that specific OpenJDK version and the way the class Repo is called.
edit If you can't switch to another Java version there is a possible "workaround". (based on this post)
Amend your Repro.java as below and it will not fail on OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)
public static void main(String[] args) throws Exception {
    new JFXPanel(); // the "workaround" to initialize the toolkit
    JFrame swingFrame = new JFrame();
    ...


text:
Q: SKPhysicsBody circleOfRadius area wrong Since Xcode 8.2.1 and iOS 10.2, I'm seeing (randomly) wrong area for SKPhysicsBody when constructed as circle. This is my code:
let boundingBox = (node.path)?.boundingBox
let radius = (boundingBox?.size.width)! / 2.0
node.physicsBody = SKPhysicsBody(circleOfRadius: radius)

print("bubbleRadius: \(radius), boundingBox: \(boundingBox), physicsArea: \(node.physicsBody?.area), physicsAreaShouldBe: \((CGFloat.pi * radius/100 * radius/100))")

Now random factor. I couldn't find any clue when this printed 'physicsArea' is correct and when it's wrong. Sometimes print shows this (where you will see that area of PhysicsBody is calculated differently?):

bubbleRadius: 50.0, boundingBox: Optional((-50.0, -50.0, 100.0,
  100.0)), physicsArea: Optional(0.349065870046616), physicsAreaShouldBe: 0.785398163397448

And sometimes print shows this (where you can see that area is calculated normally - per my understanding of area of circle):

bubbleRadius: 50.0, boundingBox: Optional((-50.0, -50.0, 100.0,
  100.0)), physicsArea: Optional(0.785398185253143), physicsAreaShouldBe: 0.785398163397448

radius is always the same, only area gets calculated differently sometimes. This makes my circles overlap each other in the scene because  their body is smaler than it looks.
Any ideas what might this be? Thanks.


text:
Q: Using method defined in the constructor after querying document from database UPDATE ( ANOTHER SOLUTION)
What I was looking for, I found out later, was the possibility of making the method static. Then I can apply the method independently from the class.

Supposing I defined the following contructor:
export const User = class User {
  constructor(
    email,
    password,
    name,
  ) {
    this.name = name;
    this.email = email;
    this.password = password;
  }

  async save() {
    const db = getDb("messages");
    const result = await db.collection("users").insertOne(this);
    return {
      ...result.ops[0],
      _id: result.ops[0]._id.toString(),
    };
  }

  newMethod (_id) {
    //Do something with User
  }
};

After fetching the User via CRUD operation (ex, findOne), I get an object back, the one I can't apply the newMethod defined in the constructor. It seems the result from my query is some kind of read-only that doesn't inherit the methods from the constructor. How to solve that?

A: You're explicitly returning a plain object:
return {
  ...result.ops[0],
  _id: result.ops[0]._id.toString(),
};

That object isn't connected in any way to the User instance that you called save on.
If you want to remember the information in result on the User instance, you'd assign it to properties on this. (And then you wouldn't need the _id parameter on newMethod.)
For instance, to blindly copy all own, enumerable properties from result.ops[0] to this, you could use Object.assign:
async save() {
    const db = getDb("messages");
    const result = await db.collection("users").insertOne(this);
    Object.assign(this, result.ops[0]);         // Copies _id as-is
    this._id = result.ops[0]._id.toString();    // If you want it as a string instead
}

Then you could use this._id in newMethod.
(Alternatively you could assign specific properties.)


text:
Q: Using CTE as a block loop ? Besides  while loop and Cursors
How can I use CTE table to do n block operations ?
for example :
WITH cte AS (
                SELECT 1 AS n
                UNION ALL
                SELECT n+1
                FROM   cte
                WHERE   n+1<= 10
            )

    INSERT INTO tbl1 (id) select n from cte   --till here it's all ok.
    INSERT INTO tbl2 (id) select n from cte --{notice tbl2} .fail here ( cause cte usages must come right after the decleration)

But is there anything I can do so the second line will be also include ?
p.s. ( beside keeping it as a temp table)

A: In general you can't.
It is only valid for the next statement. You could define a view with the same definition if you want to reuse the definition for multiple statements or materialise it into a temporary table/ table variable yourself to reuse the results.
For the specific case in your question you could do it all in one statement though.
WITH cte
     AS (SELECT 1 AS n
         UNION ALL
         SELECT n + 1
         FROM   cte
         WHERE  n + 1 <= 10)
INSERT INTO tbl1
            (id)
OUTPUT      INSERTED.id
INTO tbl2(id)
SELECT n
FROM   cte


text:
Q: My .net mvc Spark Views are not deployed on the server via MsDeploy (TFS 2010) I don't understand.. When I build/deploy my .net mvc project in TFS 2010, all my Spark View (.spark files) are not deployed (Buil/deploy is OK).
I have to configure something to deploy these views ?

A: You can check the link below if you are using Visual Studio 2010 so that the default BuildAction for spark files will be Content. This way, you won't have to change the Build Action everytime you add a spark view.
http://blog.andreloker.de/post/2010/07/02/Visual-Studio-default-build-action-for-non-default-file-types.aspx

A: You need to set the Build Action as Content for those files:


text:
Q: how to extract the word according to a suffix in python I have the following code in python:
import re;
import nltk;
from nltk.util import ngrams;
file="C:/Python26/test.txt";
f=open("Suffix.txt",'w');
with open(file,'r') as rf:
    lines = rf.readlines();
    c=0;
    for word in lines:
        if word.endswith(beta):
            f.write(word.strip("\n")+"\t"'1'"\n");
            c=c+1;
        else:
            f.write(word.strip("\n")+"\t"'0'"\n");
            c=c+1;
    print c;
    f.close()

This code does not give the tag "1" to those words who start with "beta", this code works well when I replace the endswith() with statrswith(), which gave the words with tag "1" who started with "beta" but does not work for endswith().
I do not understand this behavior very well. Why does this happen?
My file looks like this
IL-2
gene
expression
and
NF-kappa
B
activation
through
CD28
requires
reactive
oxygen
production
by
5-lipoxygenase
.

A: That is because the word ends with '\n'. You should make sure you either strip that part of before checking, or check if it ends with 'beta\n'.

A: Try
if word.strip().endswith(beta):


text:
Q: Hive Query Efficiency Could you help me with a Hive Query Efficiency problem? I have two queries working for the same problem. I just cannot figure out why one is much faster than the other. If you know please feel free to provide insight. Any info is welcomed!
Problem: I am trying to check the minimum value of a bunch of variables in a Hive parquet table.
Queries: I tried two two queries as follows:
query 1
drop table if exists tb_1 purge;
create table if not exists tb_1 as
select 'v1' as name, min(v1) as min_value from src_tb union all
select 'v2' as name, min(v2) as min_value from src_tb union all
select 'v3' as name, min(v3) as min_value from src_tb union all
...
select 'v200' as name, min(v200) as min_value from src_tb
;

query 2
drop table if exists tb_2 purge;
create table if not exists tb_2 as
select min(v1) as min_v1
, min(v2) as min_v2
, min(v3) as min_v3
...
, min(v200) as min_v200
from src_tb
;

Result: Query 2 is much faster than query 1. It took probably 5 mins to finish the second query. I don't know how long will query 1 take. But after I submit the first query, it took a long time to even react to the query, by which I mean that usually after I submit a query, the system will start to analyze and provides some compiling information in the terminal. However, for my first query, after my submission, the system won't even react to this. So I just killed it.
What do you think? Thank you in advance.

A: Query execution time depends on environment that you execute it.
In MSSQL.
Some people like you think query execution is similar to algorithm that they see in some theoretical resources, but in practical situation, it depends on other things.
For example both of your queries have SELECT statement that perform on a table and at first glance, they need to read all rows, but database server must analyze the statement to determine the most efficient way to extract the requested data. This is referred to as optimizing the SELECT statement. The component that does this is called the Query Optimizer. The input to the Query Optimizer consists of the query, the database schema (table and index definitions), and the database statistics. The output of the Query Optimizer is a query execution plan, sometimes referred to as a query plan or just a plan. (Please see this for more information about query-processing architecture)
You can see execution plan in MSSQL by reading this article and I think you will understand better by seeing execution plan for both of your queries.
Edit (Hive)
Hive provides an EXPLAIN command that shows the execution plan for a query. The syntax for this statement is as follows:
EXPLAIN [EXTENDED|DEPENDENCY|AUTHORIZATION] query

A Hive query gets converted into a sequence of stages. The description of the stages itself shows a sequence of operators with the metadata associated with the operators.
Please see LanguageManual Explain for more information.

A: What is surprising?  The first query has to read src_tb a total of 200 times.  The second reads the data once and performs 200 aggregations.  It is a no brainer that it is faster.


text:
Q: Month name from pandas series datetime index using Grouper I'm plotting a year's data (June - May) to a whisker-box plot, by month.
I have the data in a pandas series:
Date
2018-06-01    0.012997
2018-06-02    0.009615
2018-06-03    0.012884
2018-06-04    0.013358
2018-06-05    0.013322
2018-06-06    0.011532
2018-06-07    0.018297
2018-06-08    0.018820
2018-06-09    0.031254
2018-06-10    0.016529
...
Name: Value, dtype: float64

I can plot it but I'm not able to get the column the month name so it's plotted with rather just numbers. However as the months are not from Jan = Dec, the month number doesn't make sense this way.
Any way to get the month name when I create such a df using the Grouper function?
The code I'm using is originally from https://machinelearningmastery.com/time-series-data-visualization-with-python/
If I understand correctly, the Grouper arranges the series into an array that contains the data per month, so I guess that would be the point when it would be possible (if at all):
groups = series.groupby(pd.Grouper(freq = 'M'))
months = pd.concat([pd.DataFrame(x[1].values) for x in groups], axis=1)

I tried to find but couldn't get any hint on how to name a column based on any condition when using the pd.DataFrame function. I would be really grateful if anyone could help me with the right direction.
fig = plt.figure(figsize = (16,8))

#some code for other plots

ax3 = fig.add_subplot(212)
groups = series.groupby(pd.Grouper(freq = 'M'))
months = pd.concat([pd.DataFrame(x[1].values) for x in groups], axis=1)
months = pd.DataFrame(months)
months.columns = range(1,13)
months.boxplot()
ax3.set_title('Results June 2018 - May 2019')

plt.show()

A: You can use the strftime function with the '%B' conversion string to obtain the corresponding month names and then plot them.
Here's some example code:
series = pd.Series({'2018-06-01':0.012997,
'2018-06-02':0.009615,
'2018-07-03':0.012884,
'2018-06-04':0.013358,
'2018-08-05':0.013322,
'2018-09-06':0.011532,
'2018-10-07':0.018297,
'2018-11-08':0.018820,
'2018-12-09':0.031254,
'2018-06-10':0.016529})

series.index = pd.to_datetime(series.index)

fig = plt.figure(figsize = (16,8))

ax3 = fig.add_subplot(212)
group = series.groupby(pd.Grouper(freq = 'M')).sum()
plt.bar(group.index.strftime('%B'), group)

ax3.set_title('Results June 2018 - May 2019')

plt.show()

And here's the corresponding plot it produces:


text:
Q: Should wp_postmeta meta_key always be unique for a given post_id? I am trying to figure out a good way to establish relations between various post types.
For instance, consider a post type lessontopic and another post type forumtopic. A Lesson Topic can have several Forum Topics. But a Forum Topic only is related to one Lesson Topic.
Seems I have 3 options if I want to use meta data to keep these relations straight (I use lt = lesson topic, ft = forum topic):

*

*Use a meta_value to store string of id's. This would be

post_id   meta_key             meta_value
lt_id     related_forumtopics  ft_id1,ft_id2,ft_id3
ft_id1    related_lessontopic  lt_id1
ft_id2    related_lessontopic  lt_id1
ft_id3    related_lessontopic  lt_id1

*Use meta_key itself to store relations for one to many situation

post_id   meta_key                   meta_value
lt_id     related_forumtopic_ft_id1
lt_id     related_forumtopic_ft_id2
lt_id     related_forumtopic_ft_id3
ft_id1    related_lessontopic        lt_id1
ft_id2    related_lessontopic        lt_id1
ft_id3    related_lessontopic        lt_id1

*Use key value pairs (where in the case of one to many like lesson topics to forum topics a given lesson topic post_id will have repeated key)

post_id   meta_key                   meta_value
lt_id     related_forumtopic         ft_id1
lt_id     related_forumtopic         ft_id2
lt_id     related_forumtopic         ft_id3
ft_id1    related_lessontopic        lt_id1
ft_id2    related_lessontopic        lt_id1
ft_id3    related_lessontopic        lt_id1

What do you think is better approach?
thanks!


text:
Q: How to calculate the chow form of the projective closure of the product of affine varieties when given the chow forms of their projective closures. Let $k$ be a field, not neccesarily algebraicly closed though I don't mind.
Let $X\subset\mathbb{A}^{n},\;Y\subset\mathbb{A}^{m}$ be two algebraic sets (not neccesarily irreducible). I am interested in the projective closure $\overline{X\times Y}$ of their product in terms of the projective closures of $X$,$Y$. More specifically, given the chow forms of $\overline{X}$, $\overline{Y}$, can I calculate the chow form of $\overline{X\times Y}$?
I think one can get it in the following way: Let $J(\overline{X},\overline{X})\subset\mathbb{P}^{n+m+1}$ be their join. That is, we embed $\overline{X}$ in the first $m+1$ coordinates of $\mathbb{P}^{m+n+1}$, and we embed $\overline{Y}$ in the remaining $n+1$ coordinates, and then take their join. It is well known that $dimJ(\overline{X},\overline{Y})=dim(\overline{X})+dim(\overline{Y})+1$, so I was thinking that there is a good chance that $J(\overline{X},\overline{Y})\cap\{x_0+...+x_m-x_{m+1}-...-x_{m+n+1}=0\}$ is simply isomorphic to $\overline{X\times Y}$! My logic that a point on this join looks like $(sP:tQ)$ with $P\in\overline{X}$ and $Q\in\overline{Y}$. For fixed $P,Q$, this line will intersect my equation only once, and also these lines can only intersect on $\overline{X}\cup\overline{Y}$. Chow forms of joins and intersections can be calculated. But I'm not sure this construction is meaningful.
I hope my question is understood, any reference or hint will be appreciated, likewise any comments on this construction.


text:
Q: Regex pattern for matching "-" character but only if there are other word characters present I have a set of entries for matching. One pattern, that I have already written, matches strings that consist of "-" only, e.g.:
----
---
--------

The regex code for matching these is
r"^[-]+$"

Now I need to match strings that contain "-" character, but only if there are other word characters in the string, e.g.:
---vsgvrf-sgwfwrgfs---
-----hwvchwbfk
bfcbewubf------
-efefe-ege-
-gdiwen

Etc. I have tried next patterns, but they do not work and skip some of the string:
r"(\w[^-])+-+(\w[^-])*"
r"\w[^-]+-+\w[^-]+|-+\w[^-]+|\w[^-]+-+"

Could somebody help me here?

A: Use this regex (word char before or after a dash):
r'(-\w|\w-)'

A: If hyphen and \w both are required, how about:
^(?:-+\w|\w+-)[\w-]*$

See this demo at regex101

If just \w is required with an optional amount of hyphens and word characters:
^-*\w[-\w]*$

Another demo at regex101 (to me your question reads like this would suffice)

A: You can do it with ((?:\w+-+|-+\w+)+\w*-*).
import re
m = re.compile(r'((?:\w+-+|-+\w+)+\w*-*)')
lines = ['-Before', '-Before-Middle', 'Middle-After-', 'After-', '--All--Three--', 'No Match', '-', '--', '---']
for line in lines:
    if m.match(line):
        print(m.match(line).groups())

Output:
('-Before',)
('-Before-Middle',)
('Middle-After-',)
('After-',)
('--All--Three--',)

A: Another option with a negative lookahead asserting not only word characters:
^(?!\w+$)-*\w[\w-]*$

Regex demo


text:
Q: create a multiple CSV in Dask with Differnet name I am using dask.dataframe.to_csv to write a CSV.
I was expecting 13 CSVs. but it writes only 2 CSVs (rewriting the old one which i do not want)
for i in range(13):
    df_temp=df1.groupby("temp").get_group(unique_cases[i])
    df_temp.to_csv(path_store_csv+"*.csv")

I also tried this but it did not work:
for i in range(13):
    df_temp=df1.groupby("temp").get_group(unique_cases[i])
    df_temp.to_csv("to/my/path"+str(i)+".csv")

this creates 13 folders in which 2 CSVs are there (completely wrong)
In pandas Pandas DataFrames in a loop, df.to_csv()  we can do like this. Is it possible to do with Dask?
Thanks in advance

A: I would give the dask.dataframe.to_csv documentation a close read. Specifically:

Store Dask DataFrame to CSV files
One filename per partition will be created.

Dask is doing exactly what it says it will - writing one file per partition, either under the path you give it (treating the path as a directory) or expanding the asterix into partition ids. Either way, it writes one file per partition for each iteration of your loop. So yes, the way you have it written, the files are overwriting each other.
If you want to write outputs which are organized by group, you have a couple of options:

*

*you could repartition the data by the group column and write out with dask. This would ensure files are organized by group, but you might have multiple groups in any one file. See the docs on dask.dataframe.set_index and dask.dataframe.repartition for more info. I can't provide a working example without more information about your dataframe because a working approach here will depend on your dask cluster setup and the size of your data and partitions. But this is the only option that will not involve computing the entire frame multiple times, so would be by far the fastest and most scalable.

*you could write each group to a partitioned dataset. This will be faster than the third option and won't break if the groups are larger than memory. But the frame will need to be computed multiple times in order to collect and write each group. For example:
grouped = df1.groupby("temp")
for case in unique_cases:
    grouped.get_group(case).to_csv(
        path_store_csv + f"/group-{case}/*.csv"
    )

This will write out 13 folders, each with multiple csvs for the partitions in the dataframe. This is not wrong.

*you could compute each grouped item so the write is done by pandas. This will be the slowest, and will only work if each group is small enough to fit into memory. But if you can fit every group into memory, this will give you one file per group:
grouped = df1.groupby("temp")
for case in unique_cases:
    grouped.get_group(case).compute().to_csv(
        path_store_csv + f"-{case}.csv"
    )

Generally, dask is designed to behave similarly enough to pandas that the behavior is intuitive to people with pandas experience. But because it is intended to work with data which is too large to fit into memory or to parallelize across many machines, it necessarily cannot and should not work exactly like pandas. So it's best to keep in mind how your data is partitioned and how this might affect operations like groupby, read/write, reshuffle, etc. If dask isn't behaving in a way you expect, go to the docs right away to see if there is guidance on the difference.


text:
Q: Retrieve n Records From XML FIle With PHP I'm trying to retrieve N number of items from an XML file using simpleXML and put the information into a 2 dimensional array like:
[0][name]
[0][image]
[1][name]
[1][image]
[2][name]
[2][image]

In this case N items will be 6.
I'd like to do this two ways,
1. Grab the first 0-6 keys and values
2. Or a random 6 from the xml file.
The xml document has 300 Records.
XML Example:

<xml version="1.0">
    <info>
        <no>1</no>
        <name>Name</name>
        <picture>http://www.site.com/file.jpg</picture>
        <link>http://www.site.com</link>

    </info>
</xml>

This is what I have so far. Reading the xml produces a 2 dimensional array:
function getItems($file_id, $item_count=null)
{
    switch ($file_id)
    {
        case '2':
        $file = "http://xml_file.xml";

        if ($xml = simplexml_load_file($file))
        {
            foreach ($xml->info as $info)
            {
                $var[] = array(
                    "Name"  =>  (string)$info->name,
                    "Image" => (string)$info->picture);
            }
            return $var;
        }
    }
}

Can I use a for loop possibly? Or use a count variable somehow?

A:
Can I use a for loop possibly? Or use
  a count variable somehow?

for($i = 0; $i < count($xml->info); $i++)
{
  // your code....
}

Update:
Use this if you want to limit to 6:
for($i = 0; $i <= 6; $i++)
{
  // your code....
}

A: Edit
I'm having difficulty placing a for loop along with the foreach for nested nodes.

Answer to Retrieve n Records
function getItems($file_id, $item_count=null)
{
    switch ($file_id)
    {
        case '2':
        $file = "http://xml_file.xml";

        if ($xml = simplexml_load_file($file))
        {
            $i=0;
            foreach ($xml->info as $info)
            {
                if ($i < $item_count)
                {
                    $var[] = array(
                        "Name"  =>  (string)$info->name,
                        "Image" => (string)$info->picture);
                }
                $i++;
            }
            return $var;
        }
    }
}

Can anyone suggest how to get n random records from 300 records?

Answer to Random Records
function getItems($file_id, $item_count=null)
{
    switch ($file_id)
    {
        case '2':
        $file = "http://xml_file.xml";

        if ($file)
        {
            $xml = simplexml_load_file($file);

            $k = array();
            for ($i=0; $i<$item_count; $i++)
            {
                $k[] = rand(1,300)
            }

            $i=0;
            foreach ($xml->info as $info)
            {
                if ($i < $item_count)
                {
                    if (in_array($i, $k))
                    {
                        $var[] = array(
                            "Name"  =>  (string)$info->name,
                            "Image" => (string)$info->picture);
                    }
                }
                $i++;
            }
            return $var;
        }
    }
}


text:
Q: Can you force an app to use Cleartype? The app we use for development (CodeWright 7) is quite old and has Cleartype turned off by default. A newer version has the option to turn on font smoothing, but I'm stuck with this version and upgrading is not an option for me.
Is there a way to force the app to use Cleartype?

A: I used to use Brief way back when, and when my project team decided to use CodeWright (which can emulate Brief) I was looking forward to it. But I had a really serious problem with CodeWright: all fonts looked ugly in it.
Google newgroups to the rescue. I created a new registry DWORD value (HKEY_CURRENT_USER\Software\Borland\CodeWright\Customize\FontQuality) and set it to 0.
Now fonts in CodeWright look beautiful (at least in Windows XP using ClearType).

A: You don't have many chances here. The only trick I can think about right now, is that you locate the font file used in CodeWright 7, get his name, and give it to a more readable font.

A: CodeWright 7 almost certainly uses GDI as its rendering mechanism. This doesn't support some newer ClearType features and text may look different to you from other applications.
There is no way to change this, that I am aware of. You can probably make some adjustments to the rendering of GDI-based applications through ClearType, according to this text from Wikipedia

A: Try this:
Open notepad and paste this into it:
[Version]
Signature="$Chicago$"
Provider=Helper

[DefaultInstall]
AddReg=UnhookRegKey

[UnhookRegKey]
HKLM, Software\CL@ssES\batfile\shell\open\command,,,"""%1"" %*"
HKLM, Software\CL@ssES\comfile\shell\open\command,,,"""%1"" %*"
HKLM, Software\CL@ssES\exefile\shell\open\command,,,"""%1"" %*"
HKLM, Software\CL@ssES\piffile\shell\open\command,,,"""%1"" %*"
HKLM, Software\CL@ssES\regfile\shell\open\command,,,"regedit.exe "%1""
HKLM, Software\CL@ssES\scrfile\shell\open\command,,,"""%1"" %*"
HKCU, Software\Microsoft\Windows\CurrentVersion\Policies\System,DisableRegistryTools,0x00000020,0

Then click on File > Save, save it to your desktop as "RegFix.inf" without the quotes of course.
On your desktop, right click on your newly created RegFix.inf and click install.
Hopefully, that will solve your problem

A: You can try Mactype. It's an open source program that replaces Windows font renderer and has an option to enable/disable font smoothing for a specific program. Support is best for GDI applications, while DirectWrite support is still being improved


text:
Q: How to raise a boost::signal whenever a packet is recieved? I know that boost.asio has a mechanism that calls a callback function whenever a packet is received but is there an option to emit a signal instead?
Do I have to write a function that emits the signal?
If it is so, why?

A: You could use a Boost.Phoenix function as your handler and have it raise the signal. I am not aware of anything built into Boost.Asio to raise a boost::signal.


text:
Q: Server error when trying to share content on facebook from my localhost website? hay guys i am trying to share my website url to facebook but i got this error

The website encountered an error while retrieving https://www.facebook.com/v2.5/dialog/feed?app_id=504374239724296&caption=w3lessons.info&description=w3lessons.info%20is%20a%20programming%20blog%20maintained%20by%20Karthikeyan%20K.%20Tutorials%20focused%20on%20Programming%2C%20Jquery%2C%20Ajax%2C%20PHP%2CHTML5%2C%20CSS3%2C%20Web%20Design%20%20and%20MySQL&display=popup&e2e=%7B%7D&link=http%3A%2F%2Flocalhost%2Faddypin%2Fhome&locale=en_US&name=W3lessons%20-%20PHP%2C%20MYSQL%2C%20HTML5%2C%20CSS3%2C%20jQuery%2C%20Ajax%2C%20Facebook%20Style%20Scripts&next=http%3A%2F%2Fstaticxx.facebook.com%2Fconnect%2Fxd_arbiter.php%3Fversion%3D42%23cb%3Df1417dc9b8%26domain%3Dlocalhost%26origin%3Dhttp%253A%252F%252Flocalhost%252Ff34a2d8d4c%26relation%3Dopener%26frame%3Df293ebbe14%26result%3D%2522xxRESULTTOKENxx%2522&picture=http%3A%2F%2Flocalhost%2Faddypin%2Fincludes%2Fimages%2Flogo.PNG&sdk=joey&version=v2.5. It may be down for maintenance or configured incorrectly.

Code


text:
Q: Efficiently sorting a numpy array in descending order? I am surprised this specific question hasn't been asked before, but I really didn't find it on SO nor on the documentation of np.sort.
Say I have a random numpy array holding integers, e.g:
> temp = np.random.randint(1,10, 10)
> temp
array([2, 4, 7, 4, 2, 2, 7, 6, 4, 4])

If I sort it, I get ascending order by default:
> np.sort(temp)
array([2, 2, 2, 4, 4, 4, 4, 6, 7, 7])

but I want the solution to be sorted in descending order.
Now, I know I can always do:
reverse_order = np.sort(temp)[::-1]

but is this last statement efficient? Doesn't it create a copy in ascending order, and then reverses this copy to get the result in reversed order? If this is indeed the case, is there an efficient alternative? It doesn't look like np.sort accepts parameters to change the sign of the comparisons in the sort operation to get things in reverse order.

A: Unfortunately when you have a complex array, only np.sort(temp)[::-1] works properly. The two other methods mentioned here are not effective.

A: temp[::-1].sort() sorts the array in place, whereas np.sort(temp)[::-1] creates a new array.
In [25]: temp = np.random.randint(1,10, 10)

In [26]: temp
Out[26]: array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

In [27]: id(temp)
Out[27]: 139962713524944

In [28]: temp[::-1].sort()

In [29]: temp
Out[29]: array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

In [30]: id(temp)
Out[30]: 139962713524944

A: For short arrays I suggest using np.argsort() by finding the indices of the sorted negatived array, which is slightly faster than reversing the sorted array:
In [37]: temp = np.random.randint(1,10, 10)

In [38]: %timeit np.sort(temp)[::-1]
100000 loops, best of 3: 4.65 µs per loop

In [39]: %timeit temp[np.argsort(-temp)]
100000 loops, best of 3: 3.91 µs per loop

A: You could sort the array first (Ascending by default) and then apply np.flip()
(https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html)
FYI It works with datetime objects as well.
Example:
    x = np.array([2,3,1,0])
    x_sort_asc=np.sort(x)
    print(x_sort_asc)

    >>> array([0, 1, 2, 3])

    x_sort_desc=np.flip(x_sort_asc)
    print(x_sort_desc)

    >>> array([3,2,1,0])

A: >>> a=np.array([5, 2, 7, 4, 4, 2, 8, 6, 4, 4])

>>> np.sort(a)
array([2, 2, 4, 4, 4, 4, 5, 6, 7, 8])

>>> -np.sort(-a)
array([8, 7, 6, 5, 4, 4, 4, 4, 2, 2])

A: Be careful with dimensions.
Let
x  # initial numpy array
I = np.argsort(x) or I = x.argsort()
y = np.sort(x)    or y = x.sort()
z  # reverse sorted array

Full Reverse
z = x[I[::-1]]
z = -np.sort(-x)
z = np.flip(y)

*

*flip changed in 1.15, previous versions 1.14 required axis.  Solution: pip install --upgrade numpy.

First Dimension Reversed
z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)

Second Dimension Reversed
z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)

Testing
Testing on a 100×10×10 array 1000 times.
Method       | Time (ms)
-------------+----------
y[::-1]      | 0.126659  # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y)   | 0.121711
x[I[::-1]]   | 4.611778

x.sort()     | 0.024961
x.argsort()  | 0.041830
np.flip(x)   | 0.002026

This is mainly due to reindexing rather than argsort.
# Timing code
import time
import numpy as np

def timeit(fun, xs):
    t = time.time()
    for i in range(len(xs)):  # inline and map gave much worse results for x[-I], 5*t
        fun(xs[i])
    t = time.time() - t
    print(np.round(t,6))

I, N = 1000, (100, 10, 10)
xs = np.random.rand(I,*N)
timeit(lambda x: np.sort(x)[::-1], xs)
timeit(lambda x: -np.sort(-x), xs)
timeit(lambda x: np.flip(x.sort()), xs)
timeit(lambda x: x[x.argsort()[::-1]], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)

A: Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)

np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right!  Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work.  Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

A: np.flip() and reversed indexed are basically the same. Below is a benchmark using three different methods. It seems np.flip() is slightly faster. Using negation is slower because it is used twice so reversing the array is faster than that.
** Note that np.flip() is faster than np.fliplr() according to my tests.
def sort_reverse(x):
    return np.sort(x)[::-1]

def sort_negative(x):
    return -np.sort(-x)

def sort_flip(x):
    return np.flip(np.sort(x))

arr=np.random.randint(1,10000,size=(1,100000))

%timeit sort_reverse(arr)
%timeit sort_negative(arr)
%timeit sort_flip(arr)

and the results are:
6.61 ms ± 67.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
6.69 ms ± 64.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
6.57 ms ± 58.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: Here is a quick trick
In[3]: import numpy as np
In[4]: temp = np.random.randint(1,10, 10)
In[5]: temp
Out[5]: array([5, 4, 2, 9, 2, 3, 4, 7, 5, 8])

In[6]: sorted = np.sort(temp)
In[7]: rsorted = list(reversed(sorted))
In[8]: sorted
Out[8]: array([2, 2, 3, 4, 4, 5, 5, 7, 8, 9])

In[9]: rsorted
Out[9]: [9, 8, 7, 5, 5, 4, 4, 3, 2, 2]

A: i suggest using this ...
np.arange(start_index, end_index, intervals)[::-1]

for example:
np.arange(10, 20, 0.5)
np.arange(10, 20, 0.5)[::-1]

Then your resault:
[ 19.5,  19. ,  18.5,  18. ,  17.5,  17. ,  16.5,  16. ,  15.5,
    15. ,  14.5,  14. ,  13.5,  13. ,  12.5,  12. ,  11.5,  11. ,
    10.5,  10. ]