text:
Q: Pegar atributo com JS estou tentando fazer um carrinho de produtos, e até ai tudo bem, já ta funcionando, coisa linda, porém, como sempre, tem os problemas, eu sou meio novo no JS, então to apanhando muito, eu estou tentando pegar o atributo dentro da data-price (data-price="25.99") porém eu não estou conseguindo fazer isso para poder adicionar junto ao carrinho, e o mesmo iria pra pegar o nome do produto, cor, quantidade, etc.
HTML
<button class="add-to-cart" data-price="25.99">
    Adicionar ao Carrinho
    <svg x="0px" y="0px" width="32px" height="32px" viewBox="0 0 32 32">
        <path stroke-dasharray="19.79 19.79" stroke-dashoffset="19.79" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" d="M9,17l3.9,3.9c0.1,0.1,0.2,0.1,0.3,0L23,11"/>
    </svg>
</button>

JS
addToCartBtn.on('click', function() {   updateCart(); });
function updateCart() {var cartWrapper = $('.cd-cart-container'),
    cartWrapperPrice = cartWrapper.find('.add-to-cart'),
    cartPrice = cartWrapperPrice.attr('data-price'),
    cartBody = cartWrapper.find('.body'),
    cartList = cartBody.find('.cd-cart-items');
    productAdded = $('
1xProduto
'+cartPrice+'
Remove
');
    cartList.prepend(productAdded);};

Esse de cima me retorna "undefined".
Esse de baixo, me retorna o preço, mas quando eu testo em outro com valor diferente, ele me retorna somente um valor, como se fosse o um valor para todos produtos.
var cartWrapper = $('.cd-cart-container'),
    cartWrapperPrice = $('.add-to-cart'),
    cartPrice = cartWrapperPrice.attr('data-price'),
    cartBody = cartWrapper.find('.body'),
    cartList = cartBody.find('.cd-cart-items');
    productAdded = $('
1xProduto
'+cartPrice+'
Remove
');
    cartList.prepend(productAdded);

A: No primeiro caso, você pode fazer da seguinte forma, enviando o elemento como parâmetro para a função:
addToCartBtn.on('click', function() {   updateCart($(this)); });

E na função, você pode usar a sintaxe i.data("price") para pegar o valor do atributo:
function updateCart(i) {
   var cartWrapper = $('.cd-cart-container'),
   cartPrice = i.data("price"),
   cartBody = cartWrapper.find('.body'),
   cartList = cartBody.find('.cd-cart-items');
   productAdded = $('
1xProduto
'+cartPrice+'
Remove
');
   cartList.prepend(productAdded);
};

No segundo caso, seria quase a mesma coisa:
var cartWrapper = $('.cd-cart-container'),
    cartWrapperPrice = $('.add-to-cart'),
    cartPrice = cartWrapperPrice.data('price'),
    cartBody = cartWrapper.find('.body'),
    cartList = cartBody.find('.cd-cart-items');
    productAdded = $('
1xProduto
'+cartPrice+'
Remove
');
    cartList.prepend(productAdded);

Veja:

addToCartBtn= $(".add-to-cart");

addToCartBtn.on('click', function() {   updateCart($(this)); });

var cartWrapper = $('.cd-cart-container'),
    cartWrapperPrice = $('.add-to-cart'),
    cartPrice = cartWrapperPrice.data('price'),
    cartBody = cartWrapper.find('.body'),
    cartList = cartBody.find('.cd-cart-items');
    productAdded = $('
1xProduto
'+cartPrice+'
Remove
');
    cartList.prepend(productAdded);
   console.log("Valor fora da função: "+cartPrice);

function updateCart(i) {
   var cartWrapper = $('.cd-cart-container'),
   cartPrice = i.data("price"),
   cartBody = cartWrapper.find('.body'),
   cartList = cartBody.find('.cd-cart-items');
   productAdded = $('
1xProduto
'+cartPrice+'
Remove
');
   cartList.prepend(productAdded);
   console.log("Valor dentro da função: "+cartPrice);
};

<button class="add-to-cart" data-price="25.99">
    Adicionar ao Carrinho
    <svg x="0px" y="0px" width="32px" height="32px" viewBox="0 0 32 32">
        <path stroke-dasharray="19.79 19.79" stroke-dashoffset="19.79" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" d="M9,17l3.9,3.9c0.1,0.1,0.2,0.1,0.3,0L23,11"/>
    </svg>
</button>


text:
Q: Is it possible to use both GET and POST in a same method? I would like to know, in a wcf rest service is it possible to use both HTTP POST and HTTP Get in same method? I mean to say that a client page can either use post or get to invoke my method.
My client wants me to implement a method in this way.

As our API is a "RESTful" service we should be able to use both GET
  and POST with this method. The parameter can be placed in the URL
  of a GET request and also in the Header section of the GET request. When
  using a HTTP POST with this method the parameter can be
  stored in the header section or the body.

Is it possible?

A: Lets do it by writing code! Suppose you have a method!
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "Leads",
ResponseFormat = WebMessageFormat.Xml,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
[WebGet(UriTemplate="/Leads")]
Result AddLeads(ReqLead[] rl); // This is our method.

When you will run your service, it will compiled and run successfully and browser will display you a page.

Now green arrow pointing is my Service name. By cliking on it will redirect you an error page and it will make an idea clear to you! See the image below.

I hope it will give you an idea. Moreover! In you [OperationContract] you will define only one method type, whether GET or POST. You can't have both.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nuget versioning issue with package restore I am unable to install a package (using package restore) due to some kind of versioning issue with Nuget. Here are the steps I took:
build project:
error : The schema version of 'MagicalUnicorn.MvcErrorToolkit' is incompatible with version 1.6.21205.9031 of NuGet. Please upgrade NuGet to the latest version from http://go.microsoft.com/fwlink/?LinkId=213942.
Extension manager says version is: 2.0.30619.9119.
Ok, restart VS as administrator, extension manager uninstall nuget.
restart VS as administrator again, search for nuget and install.
Extension manager again says version is: 2.0.30619.9119.
rebuild project:
error : The schema version of 'MagicalUnicorn.MvcErrorToolkit' is incompatible with version 1.6.21205.9031 of NuGet. Please upgrade NuGet to the latest version from http://go.microsoft.com/fwlink/?LinkId=213942.
Ok, so restart VS as administrator, extension manager uninstall nuget again.
This time download from http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
Run the installer, all seems ok.
Extension manager again says version is: 2.0.30619.9119.
rebuild project:
error : The schema version of 'MagicalUnicorn.MvcErrorToolkit' is incompatible with version 1.6.21205.9031 of NuGet. Please upgrade NuGet to the latest version from http://go.microsoft.com/fwlink/?LinkId=213942.
Grr! Any ideas?

A: None of the offered solutions worked for me (Visual Studio 2013, Nuget Package Manager Version 2.8.5).
I had same error but it was saying I had version 2.5.4.
I fixed it by going to Tools > Nuget Manager Console > Nuget Package Console. This open's up a command line window. At the top of the window was a prompt to download missing packages for my project.
Pressed the download button and errors went away upon build.

A: The following worked for me in Visual Studio 2012:

*

*Run VS 2012 as Administrator

*Click Tools -- Extensions and Updates

*In the left nav, Updates -- Visual Studio Gallery

*Click Update on NuGet Package Manager

*Install the update

*Restart Visual Studio

A: It looks like problem in nuget command line tool. When you enable 'Nuget package restore' feature it adds .nuget folder to you solution with nuget.exe. And when you compile project this tool is using to download missing packages, not VS extension is used here. So try update this tool from command line:
cd .nuget
nuget.exe update -Self

Procedure screenshot:

A: I was facing the same issue. I resolved it by selecting Tools on VS 2010 Menu --> Library Package Manager --> Package Manager Settings --> Check "Automatically check for updates". After that I restarted VS and was prompted for Nuget Update Installation. Once the update was installed, the Nuget package, HTTP Client in my case, got installed smoothly.

A: I faced to this problem and I checked all answers that were this page and at the end my problem did not solved. After lot of search on web I could update my nuget from original site
http://docs.nuget.org/docs/start-here/installing-nuget
and for example for vs2010 :
http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c
At this site select your version of VS and then update it .
Note : before installing nuget,close all Visual Studios and after install,Open your project.
Thanks

A: This above did not work for me, completely. There is one last step that is IMPORTANT to note. After downloading the latest nuget version, you may notice that the same error prints in the output window. The reason is due to the .nuget folder containing a NuGet.exe which specifies a version number.
The solution (for me and perhaps to those of your that did not resolve your issue with the above directions), is to

*

*Delete the .nuget folder from you solution.

*Right click your web project and click Enable Nuget Restore.

*The directions above should cause a NEW .nuget folder to be added, this time the NuGet.exe should be the newest version of nuget that you downloaded.


text:
Q: How to position a table in iText Thanks for taking the time to answer my question. I'm dynamically filling data in a PDF template. Everything is working as expected except for one part. The table I am generating in Java code is not displayed in the PDF. My question would be how do I position a table in the top left corner using iText's API?
This is my code so far:
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("VAT Rate"));
table.setWidthPercentage(500);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Net Value"));
table.addCell(cell);
table.addCell("VAT Amount");
table.addCell(Double.toString(currentVatRate));
table.addCell(Double.toString(currentVatRateNetValue));
table.addCell(Double.toString(currentVatVatAmount));
table.addCell("Totals");
table.addCell(Double.toString(subTotalExcludingVat));
table.addCell(Double.toString(totalVatAmount));

Basically I need a 3 column table, each column 33%. How do I set the tables position?

A: Try this:
// table.setWidthPercentage( 500 );
table.setWidths( new int[]{ 1, 1, 1 } );

You should be using something like the following code:
com.itextpdf.text.Document document =
    new com.itextpdf.text.Document( com.itextpdf.text.PageSize.A4 );
FileOutputStream fos = new FileOutputStream( outputFileFolder + "PdfTableExample.pdf" );
com.itextpdf.text.pdf.PdfWriter pdfWriter =
    com.itextpdf.text.pdf.PdfWriter.getInstance( document, fos );

document.open();
document.add( table );
document.close();


text:
Q: How to iterate though a FirebaseObjectObservable property as an array in Angular? I want to be able to do run an *ngFor on the users property of the groups object in my Firebase database.
So far, I'm trying this:

{{ (group$ | async)?.name }}

  {{ user.email }}

Where group$ = getGroup(): FirebaseObjectObservable<any>;
And the data's structure looks like this:
"groups": {
  "marketing": {
    "apps": {
      "someid": {
        "id": "someid",
        "name": "Payroll"
      }
    },
   "id": "marketing",
   "name": "Marketing",
   "users": {
     "23948n": {
       "id": "23948n",
       "email": "someemail@domain.com"
      },
     "asdfasdfasdf": {
       "id": "asdfasdfasdf",
       "email": "someemail@domain.com"
      }
    }
  }
}

When I try the markup above, I get the name of the group back, but I get an error when it comes to the *ngFor:
ERROR Error: Cannot find a differ supporting object '[object Object]'
of type 'object'. NgFor only supports binding to Iterables such as Arrays.

It makes sense to me why I am receiving that error, because the property users on the group object is not an array, but rather an object. My question is how to get it so that the users property can be treated as an array.

A: You don't need the async pipe in this context. As the error states, *ngFor can only bind to iterables, but what the async pipe does is:

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted

So you don't get an iterable. Instead, use:
*ngFor="let email of emails"

EDIT: No, it won't convert it an array. As above, it takes an iterable, so you need to do that yourself, with, say:
let emails: [];
Object.keys(group$?.users).map(key => emails.push(group$?.users[key].email)))

Add additional properties, or the whole user object, to the array, as you wish. For exaxmple, in ES7's Object.values():
let users = Object.values(group$.users)

And the original
{{user?.email}}

A: Response from Joshua:
So, what I ended up doing was subscribing to the group object and created a separate users$ model that was assigned to group.users:
this.group$ = this.route.paramMap
  .switchMap((params: ParamMap) =>
    this.gs.getObjectObservable(params.get('id')));

this.group$.subscribe(snapshot => {
  this.users$ = Object.values(snapshot.users);
});

Then I just displayed the data as:

  {{ user.email }}

Not sure if this is the best way to do it, but it seems the easiest. Also, from what I understand of subscriptions and "snapshots", this should work out fine.


text:
Q: How to make [Flags] enum and switch case work together? How to make [Flags] enum and switch case work together? Very desirable to make it looks simple. Similar Questions asked many times, but never directly to [Flags] enum.
If M1 set execute operation 1,
if M2 set execute operation2 ,
if BOTH M1 and M2 then set execute operation 1 and 2.
 [Flags]
    public enum TST
    {
        M1 =1,
        M2 =2,
        M3 =4
    }

 public void PseudoCode()
    {

        TST t1 = TST.M1 | TST.M3; //1+2= 3

        switch( t1)
        {
            case TST.M1:
                {
                    //Do work if Bit 1 set
                }
            case TST.M2:
                {
                    //Do work if Bit 2 set
                }
            case TST.M3:
                {
                    //Do work if Bit 3 set
                }
            default:
                {
                    //nothing set;
                    break;
                }
        }

    }

I also quite sure a lot of people want to know how to make it work. Request fix of C#?

A: This will execute for any bit set
for example
ExecuteOnFlagValue(TST.M1 | TST.M3); //1+2= 3

Will execute code for bits 1 and 3
public void ExecuteOnFlagValue(TST value) {
    if (value & TST.M1 == TST.M1) {
        //Do work if bit 1
    }
    if (value & TST.M2 == TST.M2) {
        //Do work if bit 2
    }
    if (value & TST.M3 == TST.M3) {
        //Do work if bit 3
    }
}

A: You can't do that with switch in c#, since once a case is executed, no other case will be executed.
You can think of a switch statement as a shorter way to write if... else if... else... constructs - where each case is an if, and the default is the final else:
This means that the following switch statement:
switch( t1)
{
    case TST.M1:
        //Do work if Bit 1 set
        break;
    case TST.M2:
        //Do work if Bit 2 set
        break;
    case TST.M3:
        //Do work if Bit 3 set
        break;
    default:
        //nothing set;
        break;
}

Is equivalent to the following if...else if... else construct:
if(t1 == TST.M1)
{
    //Do work if only Bit 1 set
}
else if (t1 == TST.M2)
{
    //Do work if only Bit 2 set
}
else if (t1 == TST.M3)
{
    //Do work if only Bit 3 set
}
else
{
    //nothing set or multiple bits set
}


text:
Q: Flask get viewport size a short question: Is there a way to get my browsers viewport size by Flask?
I'm designing a page for many devices, for example: normal PC, iphone etc...
Thank you, FFodWindow

A: An ugly workaround with JavaScript, it works nonetheless:
Assuming your original route looks like the following:
@app.route('/user/<user>')
def user(user):
    return 'Hello ' + user

The route after the workaround:
@app.route('/user/<user>', defaults={'width': None, 'height': None})
@app.route('/user/<user>/<width>/<height>')
def user(user, width=None, height=None):
    if not width or not height:
        return """
        <script>
        (() => window.location.href = window.location.href +
        ['', window.innerWidth, window.innerHeight].join('/'))()
        </script>
        """
    return 'Hello %s (%s, %s)' %(user, width, height)

A: That's not really possible until you have a request from the user and explicitly provide that data in the request (or use the UserAgent to map certain devices to viewport sizes, but the user can change the UserAgent so this isn't necessarily reliable).
Flask solely runs on the server, and thus has no idea what the client is. For example, I can send a request from my terminal or from another server or from another Python app and your Flask server would still respond without knowledge of where I sent it from. If I really wanted to, I could set all to the same UserAgent so that there was no way of distinguishing the three different clients.
The simplest way is to make your content responsive on the client side using CSS media queries.

A: Rushy already provided a correct answer, but when you want to use flask and bokeh (I am in the same position right now) responsive design does not help in all cases (I am using a bokeh-gridplot and don't want that if accessed from a mobile device).
I will append "/mobile" to the links from my home page to the plot page on mobile devices (by checking the screen width with css) and then make the plot layout depend on whether "/mobile" was appended to the link.
Obviously this has some drawbacks (if someone on desktop sends a link to someone on mobile or the other way around), but as my page is login-protected, they will be redirected to the login page in most of the cases anyways (if they are not already logged-in) and need to go to the plot-page manually.
Just in cases this helps someone.


text:
Q: Can I specify that exactly one child element has a certain unique attribute in XMLSchema? Is it possible to specify an equivalent of HTML's <option selected> in XSD -- exactly and only one element has a particular attribute?
For example, given the following example XML fragment:
<foo-list>
  <foo/>
  <foo bar="bar"/>
  <foo/>
</foo-list>

I can write the following XSD to ensure that only one foo has @bar:
<xs:element name="foo-list">
  <!-- FOO-LIST contains [1..n] FOO elements -->
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="foo" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>
  <!-- any FOO with @BAR must have unique @BAR -->
  <xs:unique name="oneFooBar">
    <xs:selector xpath="foo"/>
    <xs:field xpath="@bar"/>
  </xs:unique>
</xs:element>
<xs:element name="foo">
  <xs:complexType>
    <!-- FOO has optional @BAR -->
    <xs:attribute name="bar">
      <xs:simpleType>
        <!-- @BAR must = "bar", if specified -->
        <xs:restriction base="xs:string">
          <xs:enumeration value="bar"/>
        </xs:restriction>
      </xs:simpleType>
    </xs:attribute>
  </xs:complexType>
</xs:element>

Assuming everything's properly qualified, and that my decision to use a solitaire enumeration instead of a pattern is sound:
1) does this schema sensibly mean what I intended? (i.e. there are zero or one <foo bar="bar"/> and zero or more <foo/> in the <foo-list>)
2) is there a way to require that there be exactly one <foo bar="bar"/> ?

A: 1) Yes, it does, in a "weird" workaround-ish way.
2) Not with stock XSD 1.0. Throw in Schematron, and you're all set. Or move to XSD 1.1 with assertions (which allows you exactly what Schematron does for what you want). The thing is, since you're not specifying a target platform, XSD 1.1 implementations are hard to come by (Java has a free option in Xerces and paid in Saxon EE) but others, such as .NET have nothing free. A Schematron "compiler" is really just a tranformation of the schema into XSLT; it can be 1.0 or 2.0,  which means it can be used to augment a normal XSD 1.0 on virtually any (reasonable) platform.


text:
Q: CSS Background to fit multiline text My problem :
I have text without  and a max-width.
I want the background to fit exactly the width and height of the text not without empty space cause the text is breaking.
I try to remove that kind of padding-right...
HTML:

bigword another big word

hello there what's up

CSS:
div{
    background: #C00;
    max-width:157px;
}

Here is a jsFiddle : http://jsfiddle.net/T8g89/1
Any suggestions?

A: If you only want the color around the text you should set the background color on the header the best thing I could tell you is remove the bg color from the div and put it on the h1.  Then set the h1 to inline, * Because headers tend to be block/inline-block elements which will cause that extra body.  Think of a block as a box *
div{
    max-width:157px;
}

h1{
    background: #C00;
    display: inline;
}

http://jsfiddle.net/Hu8v6/


text:
Q: Bootstrap input field width too small I'm trying change the width of the input field for the username and password. But nothing seems to happen

                     Login
                    <form class="dropdown-menu p-4 dropdown-menu-right" method="post" action="#">
                        {% csrf_token %}

                                Username:
                                <input type="text" class="form-control" id="username">

                                Password:
                                <input type="password" class="form-control" id="password">

                            <button type="submit" class="btn btn-primary">Login</button>

                    </form>


text:
Q: unique word abbreviation alternate solutions? Help! Numerous solutions solved it in HashMap, it is more efficient than ArrayList, however for simplicity of code and as a beginner coder:

*

*I was wondering if it can be solved in ArrayList: abbreviate all elements first and the given word, then compare if abbreviated given word matches any of the elements in the array. Please check the code that begins with "why not..." and the function"isUnique2". It keeps giving error, someone please tell me how it can be fixed.

*My second idea was: to compare first && last element && length. Wouldn't this be much simpler? If not, please tell me why it is wrong.
//<first letter><number><last letter> check if a word is unique
//Given dictionary = [ "deer", "door", "cake", "card" ] ,isUnique("dear") -> false, isUnique("cart") -> true, isUnique("cane") -> false, isUnique("make") -> true

public class UniqueWordAbbr {

Map<String, String> map= new HashMap<String, String>();

public static void main(String[] args){
    String[] dictionary  = { "deer", "door", "cake", "card" };
    UniqueWordAbbr uwa = new UniqueWordAbbr(dictionary);
    System.out.println(uwa.isUnique2 (dictionary,"cane"));
    System.out.println(uwa.isUnique("word"));
}
//why not create array to check if elements match???
public boolean isUnique2(String[] dictionary, String word) {
    String abbr_w = abbreviate(word);
    List abbr_dictionary = new ArrayList();

    for(int i = 0; i<dictionary.length; i++){
        String n_w = abbreviate(dictionary[i]);
        abbr_dictionary.add(n_w);
    }
    for (Object copy : abbr_dictionary) {
        if (abbr_w.equals(copy))
             return false;
         else return true;
    }
    return false;
}
//1. abbreviate
private String abbreviate(String str){
    return str.charAt(0)+ Integer.toString(str.length()-2) + str.charAt(str.length()-1);
}
//2. establish the map, convert array into map
public UniqueWordAbbr(String[] dictionary){
      for(int i = 0; i < dictionary.length; i++){
        String abbr = abbreviate(dictionary[i]);
        //always check if map does NOT contain first!
        if (!map.containsKey(abbr)){
            map.put(abbr, dictionary[i]);
        }else{
            map.put(abbr, "");
        }
    }
}
// check if word is unique
public boolean isUnique(String word) {
    String abbr_w = abbreviate(word);
    //为啥不直接 查询 map.containsKey(abbr_w)?
        if (map.containsKey(abbr_w)) {
            //why also need to compare the value?
            if (map.get(abbr_w).equals(word)){
                return true;
            }else {
                return false;
            }
        }
    return true;
}

}

A: Regarding your first question: The idea might be considered ok (but see my performance comments below), but you seem to be inconsistent with when you want to abbreviate the dictionary items: you try to do it in the constructor, and then again in isUnique2() you do: String n_w = abbreviate(dictionary[i]);

Regarding your second question: I know that you already know the answer. :-)
Why do I know this? In the constructor UniqueWordAbbr() you already check for collisions of your abreviations: if (!map.containsKey(abbr)). So you know already, that collisions happen and have to be accounted for. The first line of defense against collisions is good hashing (=a good abbreviation method) – i.e. a method that makes collisions extremely unlikely. Your idea expressed in abbreviate() is not good at generating unique hashes. So your program will have to revert often to next lines of defenses that you will have to code (and so your program will slow down executing this additional code...)

From the performance point of view I would advise you to consider that:
1. it is a waste of time to abbreviate a significant part of the dictionary again and again at every call to isUnique2().
It is more reasonable to abbreviate the whole dictionary less often, but doing so in constructor disables future updates to the existing dictionary. Performance-wise it is usually best to abbreviate at every update.
2. You also have to store unabbreviated and abbreviated forms together, which you now only do locally in List abbr_dictionary which exists temporarily in isUnique2(). So you loose it quickly...

3. You are searching your dictionary using linear search. This is inefficient as the complexity of this search is O(n). But using e.g. binary search would require to keep the dictionary hashes (your 'abbreviations') ordered after every update.


text:
Q: Evince does not see my search string. But why not? I have got a number of pdf documents (bank account statements), where I regularly need to search for certain kinds of transaction by keyword. Recently I observed that with Acrobat 9 (a very old version) I can do so, however, with current Evince 3.10.3 searching does not work.
I looked up the document properties and found that those pdf documents have two fonts ArialMT and Arial BoldMT. After I installed ttf-mscorefonts-installer I noticed that Acrobat leaves the fonts, whereas Evince replaces them by DejaVu Sans (/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf)  and
Arial Negrata (/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf), respectively.
So, even if the pdf documents, when opened in Evince, have got two well-defined fonts, my search by keyword results in "not found".
I would like to understand:

*

*why Evince cannot find what Acrobat can find, and

*if that is a matter of configuration or an an Evince bug.


text:
Q: ifdef not working in resource file I'm trying to use:
#include "Resource.h"

#ifdef __x86_64
IDR_D3D9X43     BINARY              "D3DX9_43_64.dll"
#else
IDR_D3D9X43     BINARY              "D3DX9_43_32.dll"
#endif

in my resource file (.rc). When I compile for x64, it should include the x64 resource. When I compile for x32, it should include the x32 resource. However, it does not..
It is being compiled using:
x86_64-w64-mingw32-g++.exe -Wall -fexceptions -O2 -m64 -std=c++11  -c C:\Users\School\Desktop\TestLoader\main.cpp -o obj\Release\main.o
windres.exe --target=pe-x86-64  -J rc -O coff -i C:\Users\School\Desktop\TESTLO~1\RESOUR~1\Resource.rc -o obj\Release\Resources\Resource.res
x86_64-w64-mingw32-g++.exe  -o bin\Release\TestLoader.exe obj\Release\main.o  obj\Release\Resources\Resource.res -s -m64 -static -static-libgcc -static-libstdc++

Output file is bin\Release\TestLoader.exe with size 3.02 MB
for x64 compilation and it uses:
x86_64-w64-mingw32-g++.exe -Wall -fexceptions -O2 -m32 -std=c++11  -c C:\Users\School\Desktop\TestLoader\main.cpp -o obj\Release\main.o
windres.exe --target=pe-i386  -J rc -O coff -i C:\Users\School\Desktop\TESTLO~1\RESOUR~1\Resource.rc -o obj\Release\Resources\Resource.res
x86_64-w64-mingw32-g++.exe  -o bin\Release\TestLoader.exe obj\Release\main.o  obj\Release\Resources\Resource.res -s -m32 -static -static-libgcc -static-libstdc++

for x32 compilation.
Any ideas why it does not conditionally include the specific resource? It always includes the first resource at the top of the file.. aka the x64 one.


text:
Q: Why is `infix` the default I'm reading about advanced operators in swift.
A basic function:
func add(a: Unicorn, b: Unicorn) -> Unicorn { return a + b }
add(u1, u2) // two unicorns are added

An infix operator:
func + (a: Unicorn, b: Unicorn) -> Unicorn { return a + b }
c = u1 + u2

postfix:
postfix func + (a: Unicorn) -> Unicorn { return a + 2 } // nonsense example
u1+

I don't understand how infix can be presumed to be the default. It doesn't look any different to me from a normal function declaration.
What is the rule here--is any single character a legal name for an infix operation? Does this mean single char functions are not otherwise allowed? Can any two-argument function in swift be called infix style?

A:
I don't understand how infix can be presumed to be the default.

If you implement an operator with two arguments the compiler can be sure you want an infix operator, because only infix operators operate on two values.
If you implement an operator with one value the compiler isn't sure whether it is either an prefix or postfix operator and will complain.
Infix operators take two values, postfix and prefix only one.

Does this mean single char functions are not otherwise allowed? Can any two-argument function in swift be called infix style?

No. A function that begins with any of these characters is an operator: /, =, -, +, !, *, %, <, >, &, |, ^, ?, or ~1. An operator can also consist of multiple characters, but it must begin with one of these characters.
Remember that a new operator must be declared first, for instance like this:
prefix operator / {}
prefix func / (a: Int) -> Int {
    return a / 42
}

/56

However this declaration won't work, because a is not one of the characters with which an operator must start:
prefix operator a {}

1 There are actually more characters. Read here.

A: No, not all single characters can be infix operators. In general, the rule is that the characters allowed in identifiers (variables, method names etc) and characters allowed in operators are not the same.
For example, the characters allowed in operators are specified here
More specifically, the first character in a token is the decisive one.

A: If I get your question right I think the answer is: That you are overloading existing operator.
Let's say we would use a custom operator, I would need to declare prefix/infix/postfix
EDIT:
Found a better example on the internet:
Like:
infix operator **= { associativity right precedence 90 }
func **= (inout left: Double, right: Double) {
    left = left ** right
}


text:
Q: Libhand library compilation error I'm trying to build a hand model library from libhand.org on Ubuntu 14.04. The library uses ogre and opencv libraries. I followed the instructions provided by the author that allowed me to successfully install ogre and opencv. There is no problem with cmake .. . but during execute command
make -j4

I get the following error:
[ 87%] Building CXX object source/CMakeFiles/hand_renderer.dir/hand_pose.cc.o
[ 91%] Building CXX object source/CMakeFiles/hand_renderer.dir/scene_spec.cc.o
Linking CXX static library libhand_renderer.a
[ 91%] Built target hand_renderer
Scanning dependencies of target pose_designer
[ 95%] Building CXX object source/CMakeFiles/pose_designer.dir/pose_designer_main.cc.o
[100%] Building CXX object source/CMakeFiles/pose_designer.dir/pose_designer.cc.o
Linking CXX executable pose_designer
/usr/bin/ld: cannot find -lNOTFOUND
/usr/bin/ld: cannot find -lNOTFOUND
libhand_utils.a(file_dialog.cc.o): In function `libhand::FileDialog::TkExec(std::string const&)':
file_dialog.cc:(.text+0xead): warning: the use of `mktemp' is dangerous, better use `mkstemp' or `mkdtemp'
collect2: error: ld returned 1 exit status
make[2]: *** [source/pose_designer] Error 1
make[1]: *** [source/CMakeFiles/pose_designer.dir/all] Error 2
make: *** [all] Error 2

Does anyone know why this error occurs and what can be done?

A: if you're still interested in an answer, in the months since you posted this question in November 2015, I have started being the maintainer of the most popular version of LibHand that was uploaded to GitHub.
We have moved the repository to https://github.com/libhand/libhand/
As of writing LibHand should compilation and run fine on modern Debian (and derivatives such as Ubuntu) if you follow those instructions.

Satisfying software dependencies under Debian/Ubuntu
The following instructions allow compilation of LibHand without too much trouble on all versions of Debian/Ubuntu currently supported by the Debian Project and Canonical.
See the 'Supported platform' section of README.md for exact OS versions LibHand currently supports.
sudo apt-get install build-essential cmake git libogre-1.9-dev libglu1-mesa-dev libxt-dev libopencv-dev tcl tk libboost-system-dev libboost-filesystem-dev

On Ubuntu 12.04 and Debian Wheezy, there is no libogre-1.9-dev package available, so substitute with libogre-dev (which is v1.7.4 on those systems).
On a fresh Ubuntu 12.04/14.04/16.04 install, if apt-get is unable to locate the OpenCV (libopencv-dev) and OGRE packages, append 'universe' to your sources.list, run sudo apt-get update and try again.
Compiling libhand and pose_designer
git clone https://github.com/libhand/libhand
mkdir build
cd build
cmake ..
make
# Collate libhand build artifacts into local "dist" directory (for external applications to link against)
make install
# Ensure path exists first: on 32-bit, x86_64 is replaced with i386. Replace OGRE version with whatever was installed (likely OGRE-1.9.0, OGRE-1.8.0, or OGRE-1.7.4).
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/x86_64-linux-gnu/OGRE-1.9.0
./hand_cpp/source/pose_designer

(Source)


text:
Q: iOS - SiriKit Intent Extension - Cannot see prints nor hit breakpoints I'm trying to incorporate SiriKit intents into my application. I followed all the instructions including

*

*Enable SiriKit

*Add the usage string in Info.plist

*Add the intent extension target to the project

*Add the intent I want to support in the Info.plist of that new target

*Add my handler method for the intent

*Add the SiriKit authentication request in the AppDelegate

When I open Siri now and I ask the required question for the intent it does ask me if I want to open my app, so I go ahead and click yes and my app is opened. However, no print-statement in my intent handling method nor a breakpoint in there is hit.
I also tried starting the intent extension scheme via the run button in Xcode, I select my app on the popped up drop down, but then nothing on the phone appears and it just says Finished running my app on the device, no print statement or breakpoints hit either.
Does anybody know what I'm doing wrong here?


text:
Q: How do I get reasonable server-side NFS log output? I was experiencing some problems with nfs-kernel-server on Debian stretch which I could solve by luck. Still, I learned that the log output was not of much help of me. I would like to change that to extend my NFS-problem-solving capabilities.
This is my /etc/exportfs file:
/srv/nfs/magicbox_rootfs 127.0.0.0/8(rw,no_root_squash,async,no_subtree_check,insecure)

When that line is commented, i.e. when I don't have access rights on my local machine, following connection attempt does not have any effect on

*

*/log/syslog

*/log/messages

*/log/dmesg

*/log/kern.log

*/log/debug

*/log/daemon.log
:
sudo mount -v -t nfs 127.0.0.1:/srv/nfs/magicbox_rootfs /tmp/mountdir/

My own solving attempts
When I run
sudo rpcdebug -m nfsd -s

as this page recommends, connection attempts do generate a entry in /log/kern.log, but it is rather meaningless:
Aug 31 11:49:43 manuelthinkpad kernel: [125549.999823] nfsd_dispatch: vers 4 proc 0

Can someone suggest how I achieve meaningful NFS log entries? I'm under the impression NFS does not do any logging by itself, but rather relies on third-party deamons and tools to do the logging for it. However, this doesn't make it easier for new users like me.


text:
Q: Pyspark: How to exclude not null records of a column while calculation pyspark sql function? I am trying to calculate the statistics for each numerical field. But i got stuck here on how to exclude null while performing this pyspark sql function
new_df=data.select([min(line).alias("Min"),max(line).alias("Max"),mean(line).alias("Mean"),stddev(line)])

Tried like this, but it gives error
new_df=data.select([min(line).alias("Min"),max(line).alias("Max"),mean(line).alias("Mean"),stddev(line.na.fill(0))])

A: You can filtered the null values using where condition before the select statement by isNotNull() function which exclude the null values.
new_df=data.where(data.line.isNotNull()).select([min(line).alias("Min"),max(line).alias("Max"),mean(line).alias("Mean"),stddev(line)])


text:
Q: How do I use a recursion for sum of squares from user input? Let's say for the user input 1, I can easily find the square of it. (A single digit input)
How do I use a recursive method to find the sum of squares (input with more than one number) e.g. 12345 should give 1*1 + 2*2 + 3*3 + 4*4 + 5*5 = 55? For the base case, it is correct to as num == 1 right? And from there, how do I compute the subsequent number behind 1?
public static int squareSum(int num) {
    if (num == 1) {
        return num*num;
    } else {
        return 0;
    }
}

A: You have to think about the small steps first. It is all about extracting the digits and the calculating the squares.
public static int squareSum(int num) {
    if (num == 0) return 0;
    return (num%10)*(num%10) + squareSum(num/10);
}

For 12345 :-
f(12345)

f(1234)+5*5

f(123)+4*4+5*5

f(12)+3*3+4*4+5*5

f(1)+2*2+3*3+4*4+5*5

f(0)+1*1+2*2+3*3+4*4+5*5

A: The problem is, that you can't get the number at position x easily. The fact that 12345 consists of the numbers 1, 2, ... is only obvious in the decimal system. We will therefore store our number as a String, take each character and parse it to an integer. Then we square the number and add them
int i sum = 0;
String iAsString = i;
for (int i = 0; i < iAsString.length; i++) {
    int currentNumber = Character.getNumericValue(iAsString.charAt(i));
    sum += currentNumber * currentNumber;
}


text:
Q: Proving the non-existence of rational zeros in a polynomial with irrational coefficients I have a conjecture, but have no idea how to prove it or where to begin. The conjecture is as follows:

A polynomial with all real irrational coefficients and no greatest common factor has no rational zeros.

This conjecture excludes the cases where the polynomial does have a greatest common factor despite having an irrational coefficient, such as $x^3+\pi x^2=0$, as that has rational zero $0$.
I know that not all polynomials with rational coefficients have rational zeros, but I am not sure how to begin. How would I go about beginning to prove this? Has it already been proved - or is there a counterexample that I am missing?

A: If one were able to prove that, that would imply that $\pi x-e=0$ has no rational roots. However, it is not known whether $e/\pi$ is rational. So, I think your conjecture as stated would be difficult to prove.

A: For the case of just one irrational coefficient $a_i$, supose by absurd that there is a rational solution $q$. Then: $$(a_i=a_0+...+a_n q^n)\frac{1}{q^i}$$ hence $a_i$ is rational. Therefore for this case there is no rational solutions.


text:
Q: iOS app status bar colors I'm working with an common code to change all screens status bar but for some reason just one screen (like the example) is with the default color. Why this happen?

My Code:
UINavigationBar.appearance().tintColor = colorWithHexString("FFFFFF")
UINavigationBar.appearance().barTintColor = UIColor(red: 0.05, green: 0.27, blue: 0.11, alpha: 0.5)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent

A: I'm working with an common code to change all screens status
There is a one stop solution for this. Set View controller-based status bar appearance in info.plist to No and in app target settings under General tab select a default Status Bar Style

No coding is required:)

A: Swift
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent

Objective-C
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

If it's not working set value to View controller-based status bar appearance in ProjectName -> (Targets) Info section -> Custom iOS Target Properties to NO.


text:
Q: Add star ratings to my model rails3 I have a model called teacher that I'd like to add ratings to (5 star). Currently, I implement this by adding a ratings nested route (resource rating) inside of my teacher resource. Then I created a model: rating with (id, user_id, teacher_id, ratings, ...). Then I created a form with hidden fields, one of which is called stars. When a user clicks on a star, I use jQuery to send an AJAX request to create/update the rating for that user and teacher.
My confusion is this: I'm having two separate forms on the page. I have a form for writing the reviewers comments. This form has two fields: title, comments (and submit). Then I have the ratings form with hidden fields. Is this the right way to go about something like this? It seems to me that I should really have the ratings model fields somehow embedded in the main review form.
Any help highly appreciated. Thank you.
[EDIT]
I've updated my application so that instead of rating a teacher object, users now rate a comment on a teacher
my setup is something like this:
routes
resources :comments as :teacher_comments do
 resource :rating
end

models
comment
has_one :rating
attr_accessible :body, :rating_attributes
accepts_nested_attributes_for :rating

rating
belongs_to :comment
attr_accessible :stars, :user_id, :teacher_id, :comment_id

view
<%= form_for( @comment, :remote => true, :url => teacher_comments_path ) do |tc| %>
  <%= tc.text_area :body, :maxlength => 450  %>
  <%= tc.fields_for :rating do |builder| %>
    <%= builder.text_field :stars  %>
  <% end %>
<% end %>

I don't see the text_field for the stars. It's just not showing up. Is there something I missed?

A: Indeed, it's generally better to have all these fields in a single form (good for user experience).
Edit:
You might use the method accepts_nested_attributes_for (as you suggested in the comments below). Put the following in your parent Model (teacher); then you should be able to create a single form to handle inputs for both Models:
in the model:
class Comment < ActiveRecord::Base
  has_one :rating
  accepts_nested_attributes_for :rating
end

in the controller:
def new
  @comment = Comment.new
  @comment.rating = Rating.new
end

Ryan Bates gives a detailed screencast on the use of these concepts here: Nested Model Form. I recommend it for users who want to know more ins and outs.
Original:
This means that you'll need to point the form to an action that can handle both types of input. You can still use form_for if you like, but specify an action other than your default (or change the code within the default action in your teacher_controller.rb file):
<%= form_for @teacher, :url => {:action => 'create_and_rate'} do |f| %>

Since rating is a Model distinct from teacher (whose form we just created), you'll want to use the generic _tag form helpers for the rating fields.
<%= text_field_tag :rating, :name %> # rating's fields should use the generic form helper
<%= f.text_field :name %> # teacher's fields can use the specific form helper

Since you are pointing to a non-RESTful action, add it to your routes file.
resources :teacher do
  :collection do
    post 'create_and_rate' # this will match /teachers/create_and_rate to TeachersController#create_and_rate
  end
end


text:
Q: How to parse a comma delimited string into seperate rows but ignore the comma for certain values We have a comma delimited string
"col1=xyz,col2=mno,col3=ABC,ZZZ,col4=complete"

So, the desired result needs to be:
col1 xyz
col2 mno
col3 ABC,ZZZ
col4 complete

When I try to parse this is what happens (col4 get split as it had a comma)
col1 xyz
col2 mno
**col3 ABC
col4 ZZZ**
col4 complete

What's the best way to get this into the desired result using SQL?

A: Declare @YourTable table (ID int,SomeList varchar(max))
Insert Into @YourTable values
(1,'col1=xyz,col2=mno,col3=ABC,ZZZ,col4=complete'),
(2,'emp_id="123",emp_status="New Hire",emp_name="Smith, John A"')

;with cte as (
      Select A.ID,B.*
      From  @YourTable A
      Cross Apply [dbo].[udf-Str-Parse](Replace(A.SomeList,' ','|'),',') B
)
Select A.ID
      ,Col_Name = left(A.RetVal,charindex('=',A.RetVal)-1)
      ,Value    = replace(substring(replace(A.RetVal + case when charIndex('=',B.RetVal)>0 then '' else ','+B.RetVal end,'|',' '),charindex('=',A.RetVal)+1,len(B.RetVal)+len(A.RetVal)),'"','')
 From  cte A
 Left  Join cte B on A.ID=B.ID and A.RetSeq=B.RetSeq-1
 Where B.RetVal is not null and charIndex('=',A.RetVal)>0
 Order By ID,A.RetSeq

Returns
ID  Col_Name    Value
1   col1        xyz
1   col2        mno
1   col3        ABC,ZZZ
2   emp_id      123
2   emp_status  New Hire
2   emp_name    Smith, John A

The UDF if Needed
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>'+ replace((Select @String as [*] For XML Path('')),@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')

A: The short answer is: you can't.
The long answer is: you can, if you 1) choose a different delimiter that will not appear in your strings - how about semicolon or dollar sign? or 2) define an escape-character that means "the character after this should be parsed differently than it normally would", but I'm not sure if that's doable in your context, or 3) stop using CSV and use fixed width fields, eg: field1 is always 10 characters, etc, then no delimiter needed


text:
Q: Java requireNonNull always returns true when Unit Testing Im trying to implement requireNonNull check on my object when Unit testing using JUnit, Im expecting an Exception to be throw but never is...
public TheClass(final String name) {
    requireNonNull(!StringUtils.isBlank(name), "name cannot be null/empty");

    this.name = name;
}

//Test
@Test(expected = IllegalArgumentException.class)
public void testInstantiateWithNullName() {
    new TheClass(null);
}

Any Ideas....
Iv also ran the test with 'expected = NullPointerException.class'

A: Presumably, your StringUtils.isBlank returns a boolean representing whether the given String is null or empty.
You're passing that boolean value to requireNonNull. Since that value isn't null, no exception is thrown.
Pass the name directly
requireNonNull(name, "name cannot be null/empty");

Though you should probably change the error message since this only checks if the argument is null. It does not consider the argument as a String and check if it is empty.

A: You could simply use
if(name != null)

You're passing a boolean value to a method that will return false if null is not received, therefore it will always consider it to be non-null. If you really want to use requireNonNull then you can do
requireNonNull(name, "name cannot be null");

However, I think what you really want is
if(name != null && !name.isEmpty())

A: With guava you can do:
checkArgument(StringUtils.isNotBlank(name), "name cannot be null/empty");

Note that this throws an IllegalArgumentException if isNotBlank is false;


text:
Q: Export a pdf and open it in email attachment I'm new to this, so every line of code here is put together with bits and pieces I picked up from here and there by myself and what i have learned from it.
So what what I'm trying to do is attach the pdf created in this code, but when I add the string (T) in .Attachments.Add it wont open the email app if I remove the (T) it opens the email, so i cant see what i am doing wrong here....
Sub Transpose()

 Dim Data_Array
 Dim OutPut_Array()
 Dim LR As Long, Counter As Long, LR2 As Long
 Dim i As Long

 Application.ScreenUpdating = False

  'Find the last row of your data in Sheet3 Column A
  'I added 1 so that the conditional statement below
  'doesn't exclude the last row of data
  With Sheets(1)
     LR = .Cells(Rows.Count, "K").End(xlUp).Row + 1
     Data_Array = .Range("K3:K18" & LR).Value2
  End With

    'See explanation in the edit section below
    On Error Resume Next
    For i = LBound(Data_Array, 1) To UBound(Data_Array, 1)

        'if the cell is not blank then increase the counter by one
        'and for each non blank cell in the Data_Array,
        'add it to the OutPut_Array
        'If its not blank then output the prepopulated OutPut_Array to Sheet4 and
        'set the counter back to zero
        If Trim(Data_Array(i, 1)) <> vbNullString Then
            Counter = Counter + 1

            ReDim Preserve OutPut_Array(1 To 1, 1 To Counter)

            OutPut_Array(1, Counter) = Data_Array(i, 1)

        Else

            With Sheets(2)
                LR2 = .Cells(Rows.Count, "B").End(xlUp).Row
                .Range("B" & LR2 + 1).Resize(1, Counter).Value2 = OutPut_Array
            End With

            Counter = 0
        End If

    Next i

    'Worksheets("SQ-AP-I-S360_Esp totais Reg Da").Activate
    'Sheet(1).Activate

' With Sheets(1)

  '  ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
  '  "C:\Users\danie\Desktop\test ub\Espessuras de Under Body " & Range("E5").Value & Format(Now(), " dd-mm-yy"), _
  '  Quality:=xlQualityStandard, IncludeDocProperties:=True, _
  '  IgnorePrintAreas:=False, OpenAfterPublish:=True

'End With

  'Save PDF VERSION

     'send_attachment()

Dim OApp As Object, OMail As Object, signature As String

Dim T As String

 T = "C:\Users\danie\Desktop\test ub\Espessuras de Under Body " & Range("E5").Value & Format(Date, " dd-mm-yy")
    ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    T, Quality:= _
    xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=True

Set OApp = CreateObject("Outlook.Application")
Set OMail = OApp.CreateItem(0)

With OMail

End With

signature = OMail.body

With OMail
   ' .To = ""
    .Subject = "Espessuras de Under Body " & Range("E5") & Format(Date, " dd-mm-yy")
    .Attachments.Add T
    '.body = ""
    '.Send
    .Display
End With

Set OMail = Nothing
Set OApp = Nothing

'ActiveWorkbook.Save

End Sub


text:
Q: Си. Что должна возвращать функция, которая определяет, входит в состав данного символьной строки указанное пользователем ключевое слово Что должна возвращать эта функция? И как на основе определить в каком из предложений больше раз встречается ключевое слово?
Написала программу, но как сделать все в функции?
Написать функцию, которая определяет, входит в состав данного символьной строки указанное пользователем ключевое слово. На основе разработанной функции определить, в каком из предложений больше раз встречается заданное ключевой набор символов.
int main()
{
   char cszSentences[5][100] = {0 };
   for (int i=0, i<5.i++)
   {
       gets(cszSentences[i])
   }
   char szKeyword[10];
   printf("Choose a keyword\n");
   gets(szKeyword);
   int iLen = strlen(szKeyword);
   int n = 0;
   for (int i = 0; i < 5; i++)
   {
      for(const char *src = cszSentences[i]; (src = strstr(src, szKeyword)) != 0;
          src += iLen)
      {
         n++;
      }
      printf("in %d sentence is %d keywords\n", i+1, n);
      n = 0;
   }
}


text:
Q: how to handle JSON.stringify when string is empty I'm trying to handle an object which doesn't exist in the array.
 var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);

So, when the javascript code gets here, it fall over because there happens to be nothing in the actual string it is trying to parse.  I've tried catching it with "typeof", but that doesn't work either.  I'm stumped.
So, the data.flightStatuses[i] array exists, just not the .airportResources.departureGate.
I tried to see if it exists using "typeof data.flightStatuses[i].airportResources.departureGate".  It still falls over.
alert (typeof data.flightStatuses[i])  // this comes back "object"
    alert (typeof data.flightStatuses[i].airportResources.departureGate)  // it dies...

A: Should be fairly straight forward like this:
if (data.flightStatuses[i].airportResources.departureGate) {
   var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
}

A: It looks like your problem is with airportResources, and not with departureGate.
Try this:
var departureGate = null,
    ar = data.flightStatuses[i].airportResources;
if(ar && 'departureGate' in ar){
    departureGate = JSON.stringify(ar.departureGate);
}

Cheers

A: You can check if the departuregate is defined as a property at all like this, and then do the action you wanted, for example:
if(data.flightStatuses[i].airportResources.hasOwnProperty('departureGate') {
    var departureGate = JSON.stringify(data.flightStatuses[i].airportResources.departureGate);
} else {
    var departuregate = null; // for example
}

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty


text:
Q: How can I speed up the binary GCD algorithm using __builtin_ctz? clang and GCC have a int __builtin_ctz(unsigned) function. This counts the trailing zeros in an integer. The Wikipedia article on this family of functions mentions that the binary GCD algorithm can be sped up using __builtin_ctz, but I don't understand how.
The sample implementation of the binary GCD looks like this:
unsigned int gcd(unsigned int u, unsigned int v)
{
    // simple cases (termination)
    if (u == v)
        return u;

    if (u == 0)
        return v;

    if (v == 0)
        return u;

    // look for factors of 2
    if (~u & 1) // u is even
        if (v & 1) // v is odd
            return gcd(u >> 1, v);
        else // both u and v are even
            return gcd(u >> 1, v >> 1) << 1;

    if (~v & 1) // u is odd, v is even
        return gcd(u, v >> 1);

    // reduce larger argument
    if (u > v)
        return gcd(u - v, v);

    return gcd(v - u, u);
}

My suspicion is that I could use __builtin_ctz as follows:
constexpr unsigned int gcd(unsigned int u, unsigned int v)
{
    // simplified first three ifs
    if (u == v || u == 0 || v == 0)
        return u | v;

    unsigned ushift = __builtin_ctz(u);
    u >>= ushift;

    unsigned vshift = __builtin_ctz(v);
    v >>= vshift;

    // Note sure if max is the right approach here.
    // In the if-else block you can see both arguments being rshifted
    // and the result being leftshifted only once.
    // I expected to recreate this behavior using max.
    unsigned maxshift = std::max(ushift, vshift);

    // The only case which was not handled in the if-else block before was
    // the odd/odd case.
    // We can detect this case using the maximum shift.
    if (maxshift != 0) {
        return gcd(u, v) << maxshift;
    }

    return (u > v) ? gcd(u - v, v) : gcd(v - u, u);
}

int main() {
    constexpr unsigned result = gcd(5, 3);
    return result;
}

Unfortunately this does not work yet. The program results in 4, when it should be 1. So what am I doing wrong? How can I use __builtin_ctz correctly here? See my code so far on GodBolt.

A: Here's my iterative implementation from the comments:
While tail-recursive algorithms are often elegant, iterative implementations are almost always faster in practice. (Modern compilers can actually perform this transform in very simple cases.)
unsigned ugcd (unsigned u, unsigned v)
{
    unsigned t = u | v;

    if (u == 0 || v == 0)
        return t; /* return (v) or (u), resp. */

    int g = __builtin_ctz(t);

    while (u != 0)
    {
        u >>= __builtin_ctz(u);
        v >>= __builtin_ctz(v);

        if (u >= v)
            u = (u - v) / 2;
        else
            v = (v - u) / 2;
    }

    return (v << g); /* scale by common factor. */
}

As mentioned, the |u - v| / 2 step is typically implemented as a very efficient, unconditional right shift, e.g., shr r32, to divide by (2) - as both (u), (v) are odd, and therefore |u - v| must be even.
It's not strictly necessary, as the 'oddifying' step: u >>= __builtin_clz(u); will effectively perform this operation in the next iteration.
Supposing that (u) or (v) have a 'random' bit distribution, the probability of (n) trailing zeroes, via tzcnt, is ~ (1/(2^n)). This instruction is an improvement over bsf, the implementation for __builtin_clz prior to Haswell, IIRC.

A: Thanks to helpful commentators, I have found the crucial mistake: I should have used min instead of max
This is the final solution:
#include <algorithm>

constexpr unsigned gcd(unsigned u, unsigned v)
{
    if (u == v || u == 0 || v == 0)
        return u | v;

    // effectively compute min(ctz(u), ctz(v))
    unsigned shift = __builtin_ctz(u | v);
    u >>= __builtin_ctz(u);
    v >>= __builtin_ctz(v);

    const auto &[min, max] = std::minmax(u, v);

    return gcd(max - min, min) << shift;
}

int main() {
    constexpr unsigned g = gcd(25, 15); // g = 5
    return g;
}

This solution also has very nice, nearly branch-free compile output.
Here are some benchmark results of all the answers so far (we actually beat std::gcd):


text:
Q: iOS app posting to facebook but via link is not found I am trying to figure out where I set the redirect for when a user clicks "via app" after someone post with my app. Right now when I click on my via link it tells me that the page is not found. I would like to set this link to the Facebook page I made for my app.
I have checked all the setting at my developers.facebook.com. I am thinking it is something set inside the graph api.

A: I had to create a page for my app. That is where it was trying to redirect to. You can create/set your page in App Details.


text:
Q: Trouble Inserting Data in SQLite Using long Always Returns -1 I'm having trouble finding what's missing in my code. I'm trying to insert data but "long result == db.insert" in my DatabaseHelper class always returns -1". I cannot pin point what I'm doing wrong. Please help. Any Idea would be very appreciated.
My DatabaseHelper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "drivefinal.db";
public static final String TABLE_NAME = "drive_table";
public static final String ID = "ID";
public static final String NUMBER = "Number";
public static final String FNAME = "First Name";
public static final String LNAME = "Last Name";
public static final String COORDINATE = "Coordinate";
public static final String ADDRESS = "Address";
public static final String NOTES = "Notes";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT ,NUMBER TEXT,FNAME TEXT,LNAME TEXT,COORDINATE TEXT,ADDRESS TEXT,NOTES TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
    onCreate(db);
}

public boolean insertData(String number, String fName, String lName, String coordinate, String address, String notes){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(NUMBER, number);
    contentValues.put(FNAME, fName);
    contentValues.put(LNAME, lName);
    contentValues.put(COORDINATE, coordinate);
    contentValues.put(ADDRESS, address);
    contentValues.put(NOTES, notes);

    long result = db.insert(TABLE_NAME,null ,contentValues);
        if(result == -1 )
            return false;
        else
            return true;
}

My main activity file:
public void addData(){
    btnSave.setOnClickListener(
        new View.OnClickListener(){
            @Override
            public void onClick(View v){
                boolean isInserted = myDb.insertData(editTextnumber.getText().toString(),
                        editTextfname.getText().toString(),
                        editTextlname.getText().toString(),
                        editTextcoordinate.getText().toString(),
                        editTextaddress.getText().toString(),
                        editTextnotes.getText().toString());

                        if(isInserted)
                            Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
            }
        }

        );
}

}

A: Your table definition creates column names that are not the same as the column names you are trying to use when inserting.
e.g. your table will have the column name FNAME not First Name (etc).
Secondly you would have issues trying to use a column named First Name as it includes a space and would have to be enclosed e.g. [First Name].
I'd suggest using :-
public static final String NUMBER = "Number";
public static final String FNAME = "FirstName"; //<<<<<<<<<< space removed
public static final String LNAME = "LastName"; //<<<<<<<<<< space removed
public static final String COORDINATE = "Coordinate";
public static final String ADDRESS = "Address";
public static final String NOTES = "Notes";

Along with :-
db.execSQL("create table if not exists " + TABLE_NAME +"(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + NUMBER + " TEXT," + FNAME + " TEXT," + LNAME + " TEXT," + COORDINATE + " TEXT," + ADDRESS + " TEXT," + NOTES + " TEXT)");

To introduce the changes (i.e. for the onCreate method to run, as it only runs automatically when creating the database) you would have to do one of the following :-

*

*Delete the App's data.

*Uninstall the App.

*Change the database version number e.g. change super(context, DATABASE_NAME, null, 1); to super(context, DATABASE_NAME, null, 2);
and then rerun the App.


text:
Q: Confused at regular expressions-Python import re
caps = "bottle caps/ soda caps/ pop caps"

regex = re.findall(r"\w[1-6]", caps)

print(regex)

output is:
[]

however if I do this
import re
caps = "bottle caps/ soda caps/ pop caps"

regex = re.findall(r"\w[1-6]*", caps)

ouput is:
['b', 'o', 't', 't', 'l', 'e', 'c', 'a', 'p', 's', 's', 'o', 'd', 'a', 'c', 'a', 'p', 's', 'p', 'o', 'p', 'c', 'a', 'p', 's']

how do I make it output:
["bottle caps", "soda caps, "pop caps"]

I know you guys would recommend using the .split but I wanna understand regular expressions more
I've tried this as well:
import re
caps = "bottle caps/ soda caps/ pop caps"

regex = re.findall(r"\w[1-6]?\s*\w[1-3]*", caps)

print(regex)

output:
['bo', 'tt', 'le', 'ca', 'ps', 'so', 'da', 'ca', 'ps', 'po', 'p c', 'ap']

whats happening?

A: You appear to be confusing {1,6}, which means "the previous pattern repeated 1 to 6 times", with [1-6], which means "any of the characters in the range 1 to 6".
So, what you have:
\w[1-6]

Debuggex Demo
… will match a word character, followed by a digit from 1-6.

Putting the * on the end just means 0 or more of that digit pattern, which means any word character followed by zero or more digits from 1-6.

But if you use the right syntax, you get what you want:
\w{1,6}

Debuggex Demo

A: You can use r"(\w+[\s\b]+\w+)" which means: \w+ = a word; [\s\b] = space or word boundary:
import re
caps = "bottle caps/ soda caps/ pop caps"

output = re.findall(r"(\w+[\s\b]+\w+)", caps)
print output # ['bottle caps', 'soda caps', 'pop caps']

(\w+[\s\b]+\w+)

Debuggex Demo

A: You're confusing yourself with what is actually a defined character class, [1-6] will match a single character between the range 1 and 6. You were probably meaning {1,6} instead which will match the preceding regex token between 1 and 6 times, known as the range operator.
By preceding the character class [1-6] with the * operator in the second attempt, you're telling the regex engine to match the preceding token "zero or more" times, which ends up matching each word character individually because you have no numeric characters in your string.
Instead, you could simply write the regex as:
>>> re.findall(r"\w+ \w+", caps)
['bottle caps', 'soda caps', 'pop caps']


text:
Q: JsonMappingException on android spring httprequest I have this call in async task. All parameters are correct. In postman or advance rest client the call work fine and It return a json with a list of objects. But if I try to do this call in android with spring I have this error:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token
   at [Source: org.apache.http.conn.EofSensorInputStream@1961b5e; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
   at [Source: org.apache.http.conn.EofSensorInputStream@1961b5e; line: 1, column: 1]

This is the expected json response
[
{
    "id": 57,
    "user_id": 2,
    "category_id": 5,
    "notification_title": "test 9",
    "notification_body": "breve 9",
    "description": "Sd sdfds sdfs dfsd fdsf",
    "image": null,
    "code": "2-5942525969dfa",
    "start_date": null,
    "expiration_date": null,
    "created_at": "2017-06-15 09:24:41",
    "updated_at": "2017-06-15 09:24:41"
},
{
    "id": 56,
    "user_id": 2,
    "category_id": 4,
    "notification_title": "test 8",
    "notification_body": "breve desc 8",
    "description": "Sdfsdf sdfds dsfs dsfds",
    "image": null,
    "code": "2-59424e24570a2",
    "start_date": null,
    "expiration_date": null,
    "created_at": "2017-06-15 09:06:44",
    "updated_at": "2017-06-15 09:06:44"
}]

this is my AsyncTask
new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {

            JSONObject body = new JSONObject();

            try {
                body.put("api_token", Config.API_TOKEN);
                body.put("user_id", Config.USER_ID);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                return template.postForObject(
                        Config.SERVICE_URL_BASE + "/getallposts",
                        body.toString(),
                        String.class
                );
            } catch (Exception e) {
                listener.onError(e.getMessage());
            }

            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (response != null) {
                try {
                    List<JSONObject> jsonObjects = ResponseConverter.toJSONArray(response);
                    listener.onSuccess(jsonObjects);
                } catch (JSONException e) {
                    listener.onError(context.getResources().getString(R.string.cannot_load_posts));
                }
            } else {
                listener.onError(context.getResources().getString(R.string.cannot_load_posts));
            }
        }

    }.execute();

Can someone help me please?

A: Problem solved, the spring framework rest tempolate version was wrong, I used the 1.0.1 RELEASE but the correct versione is:
    compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'


text:
Q: Pandas option to treat leading zeros entry as string Is there a read_csv option to parse columns with leading zeros as strings? I've seen suggestions to preprocess and modify the csv to add quotes, but am wondering if one of the 52 kwargs options can do this for me.
Similar to this question, but explicitly asking if there's a pandas option, rather than preprocessing or manually passing dtype={strcols:object}.

A: Ask, and you shall receive. Specify the dtype as a dictionary of {column name: type} :
In [22]: s = """0001,2
0002,3
"""

In [23]: pd.read_csv(StringIO(s), header=None, dtype={0: str})
Out[23]:
      0  1
0  0001  2
1  0002  3

[2 rows x 2 columns]


text:
Q: Clojure Enlive: Applying snippet on a list I am trying to define an enlive template for a html table, that shows data from a map.
template-div for this example is right here. Dummy content that for the cells in the template is here.
defsnippet for cell value and deftemplate are defined as:
(require '[net.cgrand.enlive-html :as html])

(html/defsnippet value-cell (template-div) [:div.Row :div.Cell] [value]
          (html/content value))

However, when I try the snippet
(value-cell (mapv vals (:event-data dummy-content)))

All the values are in one tag like this
({:tag :div, :attrs {:class "Cell"},
:content ("end time 1" "date 1" "event name 1" "start time 1"  "performer 1" "end time 2" "date 2" "event name 2" "start time 2" "performer 2")})

And I need every item from a list to be a value in the tag.

A: You are passing a list of values to value-cell, so value-cell should look something like:
(html/defsnippet value-cell (template-div)
  [:div.Row :div.Cell]
  [values]
  (html/clone-for [value values]
                  (html/content value)))


text:
Q: what is the use of string args[] in main method
Possible Duplicate:
What is "String args[]"? in Java

What is the purpose of this method in java. If we not use what happens?
If i give some array size then what happens

A: It's for passing in command line arguments:
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/essential/environment/cmdLineArgs.html
I think you have to have it declared in the main method (but you don't have to use it). I don't think you can give it an array size.

A: The args array contains all command line parameters passed in to your Java application.  For example, if you call your application like this:
java foo arg1 arg2 22 3 + 5

Then args[] will be an array of the following strings:
"arg1", "arg2", "22", "3", "+", "5"

You can give it any name you want -- it doesn't have to be called args, but you cannot specify a size.  This is so because you're not defining the parameter, you're merely specifying its type.  Its size is determined based on the number of command line parameters passed in.

A:
What is the use of string args[] in main method?

It passes any command line arguments to your Java application.  For example, if you run your app as:
java -cp ... com.example.app1.App1 1 2 3 4

then the JVM tries to execute com.example.app1.App1.main(String[]), with an argument equivalent to that created by the expression new String[]{"1", "2", "3", "4"}.

What is the purpose of this method in java. If we not use what happens?

It provides an entry point that allows you to run the application from the command line.  If you don't supply a suitable main method, you'll be able to compile the application, but not run it.  If you supply a main method without the String[] argument, it won't be recognized as an entry point.

If i give some array size then what happens?

You get a Java compilation error; e.g.
public static void main(String[10] args) { ...

is invalid Java.  An array type declaration does not have a size, because the size is not part of an array type.  The size of a Java array is a runtime attribute that is only determined when the array instance is created.

A: Passing arguments from the command Line. Which can be used by the program as a set of parameters to operate upon or produce a result based on a set of known parameters.

A: The args parameter contains the command line arguments passed to the JVM when starting your program, analogous to the argv parameter to the C/C++ main function. You can declare it either as a String[] or as a varargs String....
The Java Language Specification doesn't seem to define the semantics of args, so I presume it is up to the JVM itself to determine how to populate the array. I can imagine that platforms such as Android can have other ways of populating the array.


text:
Q: How can we show Nifty window modal popup on page load? I want to show my nifty window modal popup on page load. This is my nifty window popup modal code:

Modal Dialog

This is my first nifty modal window.

            <button class="md-close">Close me!</button>

Thanks in advance.

A: I've looking in to the source code of the demos, and I believe that this would do the trick:
$(function() {
     $('#modal-1').addClass('md-show');
});


text:
Q: How to select an option from the dropdown when the dropdown has same ID I'm trying to select a value from a drop-down.
This is the HTML:
<select id="selectFilter">
  <option value></option>
  <option value="FEE">FEE</option>
  <option value="PW">PW</option>

My code to select is:
select('PW', :from => 'selectFilter')

I get an error since the id selectFilter is the same at two places
Ambiguous match, found 2 elements matching "selectFilter" (Capybara::Ambiguous)

How do I select the options I need?

A: HTML id attributes are supposed to be unique on the page. You need to rename at least one of your selectFilters so they don't collide.
If for some reason you really can't/won't pick unique ids, Capybara's select will also find names and labels, but you have to provide something unique for it to find the right element.

A: If you really do have two elements with the same id then you really should fix your HTML.  If on the other hand you have one select with that id and another select with that as the name, placeholder, or label text you can do
find('#selectFilter').find(:option, 'PW').select_option

which would find specifically by id and may solve your issue.
If you do actually have two elements with the id and refuse to/can't  fix your HTML then you can scope the initial find to one part of the page somehow like
find('#some_section').select('PW', from: 'selectFilter')

or if there is only one 'PW' option on the page you could just do
find(:option, 'PW').select_option


text:
Q: Excel: How to use conditional formatting to highlight missing data? I'm wondering how to use conditional formatting in order to highlight specific cells in a column that return an error message in another column after applying a function to it.
eg) Column 1 has data 1 ... n
    Column 2 has data f(1) ... f(n); f(n) being a function that sometimes returns errors.
I want to color the cells in Column 1 that return the error in column 2. How would you do this? Thanks!

A: You can use a simple ISERROR().
Let's say that column 1 is A and column 2 is B.
Select cell A1 and then select the whole column. Cell A1 should be slightly less dark than the other cells (it's the active cell in the selected range). Once you have this, go to conditional formatting and under 'New rule' and 'Use a formula to determine which cells to highight', put the formula:
=ISERROR(B1)

Pick a formatting (e.g. Fill and yellow) and click OK. That should highlight the cells for which column B has errors.


text:
Q: Python connect to Teradata in AWS EC2 I want to pull data from a Teradata instance. Client code runs Python2.7+ on AWS EC2 instance.
I installed unixODBC driver and sudo pip install teradata but I am still getting the following exception:
  File "/usr/local/lib/python2.7/site-packages/teradata/tdodbc.py", line 369, in determineDriver
"Available drivers: {}".format(dbType, ",".join(drivers)))
teradata.api.InterfaceError: ('DRIVER_NOT_FOUND', "No driver found for 'Teradata'.  Available drivers: PostgreSQL,MySQL")

The code is as follows:
import sys
import teradata
# my own imports
td = TeradataClient(DEFAULT_HOSTNAME, DEFAULT_USERNAME, DEFAULT_PASSWORD)
td.select(query, outfile)

The TeradataClient class I created which calls Teradata is as follows:
class TeradataClient:
    def __init__(self, hostname, username, password):
        self._hostname = hostname
        self._username = username
        self._password = password
        self._udaExec = teradata.UdaExec(appName="MyApp", version="1.0", logConsole=False)

    def select(self, query, outfile, sep=DEFAULT_SEPARATOR, nullstr=DEFAULT_NULL_STR):
        with self._udaExec.connect(method="odbc", system=self._hostname, username=self._username,
                                          password=self._password) as session:
            print 'Connection to Teradata established'
            with open(outfile,'w') as fp:
                with session.cursor() as cursor:
                    for row in cursor.execute(query):
                        lineparts = [str(x if x!=None else nullstr) for x in row]
                        fp.write('%s\n' %sep.join(lineparts))

How can I fix this? Is there another ODBC driver that needs to be installed?

A: This fixed the issue for me:
export ODBC_VERSION=14.10
export ODBCINI=/opt/teradata/client/$ODBC_VERSION/odbc_64/odbc.ini
export ODBCINSTINI=/opt/teradata/client/$ODBC_VERSION/odbc_64/odbcinst.ini
export LD_LIBRARY_PATH=/opt/teradata/client/$ODBC_VERSION/odbc_64/lib:/opt/teradata/client/$ODBC_VERSION/tdicu/lib64:$LD_LIBRARY_PATH
export NLSPATH=/opt/teradata/client/$ODBC_VERSION/odbc_64/msg/tdodbc.cat

note:

*

*change $ODBC_VERSION as needed.

*update /etc/resolv.conf for the system kwarg in udaExec.connect

A: I ran into this issue today and found that it is caused by one of the latest versions of the teradata python package.  Installing version 15.10.0.10 with pip allowed me to connect from my RHEL instance.

A: It sounds like you need to install the Teradata ODBC driver.
Available on the Teradata Developer Exchange.
http://downloads.teradata.com/download/connectivity

A: I know I am about 2 years late, but I had the same issue today and found a solution to it. Please go to /usr/lib64 and check the following two symlinks:
lrwxrwxrwx 1 root root 20 Oct 18 10:56 libodbcinst.so -> libodbcinst.so.2.0.0
lrwxrwxrwx 1 root root 20 Oct 18 10:56 libodbcinst.so.2 -> libodbcinst.so.2.0.0

If they don't point to teradata, it will not work! They should point to the teradata odbc installation dir:
Fix (use at your own risk, without any warrenty) ;):
sudo rm /usr/lib64/libodbc.so
sudo rm /usr/lib64/libodbcinst.so
sudo ln -s /opt/teradata/client/16.20/lib64/libodbc.so /usr/lib64/libodbc.so
sudo ln -s /opt/teradata/client/16.20/lib64/libodbcinst.so /usr/lib64/libodbcinst.so

The result:
lrwxrwxrwx 1 root root 47 Oct 25 20:10 libodbcinst.so -> /opt/teradata/client/16.20/lib64/libodbcinst.so
lrwxrwxrwx 1 root root 43 Oct 25 20:10 libodbc.so -> /opt/teradata/client/16.20/lib64/libodbc.so

And voilá, the connection to Teradata should be running smooth as butter!


text:
Q: How to merge or handle duplicate column in dataframe? I have a df that looks like this:
column1 columnId   column1
aaa        1
bbb        2       bbb
ccc        3

Is there anyway I can take all my duplicate columns and merge them with existing data?
New df would look like this:
column1 columnId
aaa        1
bbb        2
ccc        3

note, this is an example I have 18 duplicate columns but deduplicated I have 9.
Thank you in advance

A: Using groupby with first
df.groupby(level=0,axis=1).first()
Out[915]:
  column1  columnId
0     aaa         1
1     bbb         2
2     ccc         3


text:
Q: What is the difference between these Python codes? Code 1:
if 5 > 2:
 print ("Five is greater than two!")

Code 2:
if 5 > 2:
print ("Five is greater than two!")

What is the difference between these codes?
Code 1 has an extra space before print function and Code 2 doesn't have space before print, but when I am trying to run Code 1: it is showing "expected an indented block":

A: Unlike languages like C that use special tokens to define blocks (i.e., { and }), Python defines blocks by indentation. In the second snippet, the print statement isn't properly indented under the if, resulting in an empty if block (which is illegal in Python), and then an unrelated print statement.

A: You need indentation!
Even the one space indentation isn't so good, the best is to use four:
if 5 > 2:
    print ("Five is greater than two!")

Related: Python: using 4 spaces for indentation. Why?


text:
Q: SharedPrefs, how to save the state of two toggle buttons? I am making a project in which i am using two toggle buttons and i have to save there state so that it can work in background as per it is saved or not. I am able to save the state of first togglebutton but not able to save the state of second togglebutton and the second one can also start and stop service as per . So can anyone tell what must i do so that i can save the state of togglebuttons
public class MainActivity extends AppCompatActivity {
public ToggleButton led1, led2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    led1 = (ToggleButton) findViewById(R.id.toogleButton1);
    led2 = (ToggleButton) findViewById(R.id.toogleButton2);

            SharedPreferences sharedPrefs = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE);
            led1.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));

            SharedPreferences sharedPrefs1 = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE);
            led2.setChecked(sharedPrefs1.getBoolean("NameOfThingToSave", true));

}

public void clickHendler(View v) throws InterruptedException {

    switch (v.getId()) {

        case R.id.toogleButton1:
            if (led1.isChecked())
            {
                SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.togglebutton", MODE_PRIVATE).edit();
                editor.putBoolean("NameOfThingToSave", true);
                editor.commit();
            }
            else
            {
                SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.togglebutton", MODE_PRIVATE).edit();
                editor.putBoolean("NameOfThingToSave", false);
                editor.commit();
            }
        break;

        case R.id.toogleButton2:
            if (led2.isChecked())
            {
                SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE).edit();
                editor.putBoolean("NameOfThingToSave", true);
                editor.commit();
            }
            else
            {
                SharedPreferences.Editor editor = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE).edit();
                editor.putBoolean("NameOfThingToSave", false);
                editor.commit();
            }
            break;
    }
}

A: You can't just use the same key to store values for both toggle button. Do it like this :
public ToggleButton led1, led2;
public SharedPreferences sharedPrefs;

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 led1 = (ToggleButton) findViewById(R.id.toogleButton1);
 led2 = (ToggleButton) findViewById(R.id.toogleButton2);

 sharedPrefs = getSharedPreferences("com.example.peter.zapisywaniedanychtogglebutton", MODE_PRIVATE);
 led1.setChecked(sharedPrefs.getBoolean("Button_one_value", true));
 led2.setChecked(sharedPrefs.getBoolean("Button_two_value", true));

}

public void clickHendler(View v) throws InterruptedException {

 SharedPreferences.Editor editor = sharedPrefs.edit();

 switch (v.getId()) {

  case R.id.toogleButton1:
   if (led1.isChecked()) {
    editor.putBoolean("Button_one_value", true);
   } else {
    editor.putBoolean("Button_one_value", false);
   }
   editor.commit();
   break;

  case R.id.toogleButton2:
   if (led2.isChecked()) {
    editor.putBoolean("Button_two_value", true);
   } else {
    editor.putBoolean("Button_two_value", false);
   }
   editor.commit();
   break;
 }
}


text:
Q: div to fill the height of parent I want to fill the height remaining of the parent with black color.
I put a div with class fill-black in this page :
http://diary.applyss.me/blouses/2-7-chemisier.html#/1-taille-s/11-couleur-noir
In the center column, I put the div just below the text Détails du produit
I tried to use some flex properties, I want this div to fill the height of the parent. Is is possible using only CSS ?
I tried :
.fill-black {
    display: flex;
    flex-flow: column nowrap;
    align-items: stretch;
    background: #000;
}

Here is a visual of what I want : http://b3.ms/6x1nzg1rMDQG
I put height to 200px, but I want this height to be responsive.


text:
Q: How to map two components of the same type with Fluent NHibernate AutoMap Conventions We are using Fluent NH with convention based mapping.  I have the following:
public class Foo() : Entity
{
  public BarComponent PrimaryBar { get; set; }
  public BarComponent SecondaryBar { get; set; }
}

public class BarComponent
{
  public string Name { get; set; }
}

I have it to the point where it will create the foo table with a single name field.  I've tried the following Override and it doesn't work.
  public class FooOverride : IAutoMappingOverride<Foo>
    {
        public void Override(AutoMapping<Foo> mapping)
        {
            mapping.Component(x => x.PrimaryBar).ColumnPrefix("primary");
            mapping.Component(x => x.SecondaryBar).ColumnPrefix("secondary");
        }
    }

Do I really need to do a full override mapping or can what I have here be made to work somehow?

A: I ran into this a couple of years ago when I started with FNH. It's one of the few scenarios I've seen where FNH Automapping does not "just work".
The approach that was suggested to me at the time, which I've used successfully (with entities however, not components) is to create empty, intermediate entities, and reference them in the descendant class.
In your case, you could create two new, empty classes that inherit from BarComponent (say, PrimaryBarComponent and SecondaryBarComponent).
Then, in your Foo class, declare them as:
public PrimaryBarComponent PrimaryBar { get; set; }
public SecondaryBarComponent SecondaryBar { get; set; }

This is a kluge, in my opinion, but it works fine with entities and lists of entities, and does not require any overrides or conventions.
I've never used components with FNH, so I don't know if a similar approach will work, but it might be worth investigating.

A: I ended up getting the way I have described in the question working.  It turned out to be a problem with our AutoMappingConfiguration which inherits from DefaultAutomappingConfiguration.  We weren't identifying Components properly.


text:
Q: Low performance of groupbykey in spark After reading the Spark documentation, I find that groupByKey function has a low performance compared with reduceByKey. But what I need is to get the average, maximum and minimum value of a certain key. I don't think this could be done by reduceByKey method. I can just create an customized reduceByKey function to realize those goals?

A: Let's say you have an RDD[(String, Double)] and you want to calculate avg, min, max over the double values using reduceByKey.
This could by done by duplicating the values as many times as operations you like to apply and then applying the different operations with reduceByKey.
Like this:
val srcData:RDD[(String, Double)] = ???
srcData.cache
val count = srcData.count
val baseData = srcData.map{case (k,v) => (k,(v,1,v,v))}
val aggregates = baseData.reduceByKey { case (v1,v2) =>
    (v1._1 + v2._1, v1._2 + v2._2, Math.max(v1._3, v2._3), Math.min(v1._4,v2._4))}
val result = aggregates.collect()
            .map{case (id, (sum, count, max, min)) => (id, sum/count, max, min)}


text:
Q: C++ Curl download only if res == 0? I'm download files from a web server using this code, this is working and after some help on here I now get error codes returned. This is the code I'm using:
void downloadFile(const char* url, const char* fname) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl){
        fp = fopen(fname, "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
        res = curl_easy_perform(curl);
        cout << res;
        if (res != 0) {
            cout << curl_easy_strerror(res);
            return;
        }

        curl_easy_cleanup(curl);
        fclose(fp);
    }
}

What I'm trying to is only create the local file if res is 0 otherwise show the error code and stop the application.
Up to now everything I've tried has resulted in a file being created and often it will contain the return information from the server.
How do I only create the final file if res = 0 and if not show the error message and quit the application. ?
Thanks

A: I think you should not use write_data write function but a custom one:
size_t store_content(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    std::string &content = static_cast<std::string>(*userdata);
    content += std::string(ptr, size*nmemb);
    return size*nmemb;
}

void downloadFile(const char* url, const char* fname) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    std::string content;
    curl = curl_easy_init();
    if (curl){
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, store_content);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
        curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);
        res = curl_easy_perform(curl);

        if (res != 0) {
            fp = fopen(fname, "wb"); // TODO: check errors
            fwrite(content.data(), content.size(), 1, fp); // TODO: check errors
            fclose(fp);
        }

        curl_easy_cleanup(curl);
    }
}

CURLOPT_WRITEFUNCTION is used to set a function called when data is received by libcurl.
CURLOPT_WRITEDATA is used to set a pointer to data you want to be passed to the callback given by CURLOPT_WRITEFUNCTION


text:
Q: Why NgForm object gives incorrect values for valid and Invalid properties I'm an angular beginner, and I wanted to disable the submit button if the form is invalid, and enable it once the form become valid.
I used the NgForm variable to obtain the form validity status:
<form #currencyForm="ngForm">

// some input elements with sync validations and async validations
// some disabled elements with no validation at all (just default values)

<button mat-raised-button color="primary" type="submit"  [disabled]="currencyForm.invalid" (click)=submitClicked(currencyForm)>Submit</button>
</form>

the submitClicked() method used to log the currencyForm object, please notice the values of the valid\invalid properties:

while the form looks like this:

so the form is invalid but the log showing that form is valid, that's why the submit button is always enabled..
and to fix that I need to understand why form values are invalid..
thanks a head
Update, Form Code:
<form class="example-form" #currencyForm="ngForm" >
    <mat-dialog-content>

          <mat-form-field>
            <input type="text" matInput #currency_name maxlength="30" placeholder="Currency Name" required [(ngModel)]="currency.name" name="name" [formControl]="nameFormControl" >
            <mat-hint align="end">{{currency_name.value?.length || 0}}/30</mat-hint>
                <mat-error *ngIf="nameFormControl.invalid && (nameFormControl.dirty || nameFormControl.touched)">{{getNameErrorMessage()}}</mat-error>

            </mat-form-field>

          <mat-form-field>
            <input type="text" matInput #currency_symbol maxlength="3" placeholder="Symbol" required [(ngModel)]="currency.symbol" name="symbol" [formControl]="symbolFormControl">
            <mat-hint align="end">{{currency_symbol.value?.length || 0}}/3</mat-hint>
            <mat-error *ngIf="symbolFormControl.invalid && (symbolFormControl.dirty || symbolFormControl.touched)">{{getSymbolErrorMessage()}}</mat-error>
          </mat-form-field>

          <mat-form-field>
            <input  matInput #decimals maxlength="1" placeholder="Decimals after point" required [(ngModel)]="currency.decimals_after_point" name="decimals_after_point" [formControl] = "decimalsFormControl">
            <mat-hint align="end">{{decimals.value?.length || 0}}/1</mat-hint>
            <mat-error *ngIf="decimalsFormControl.invalid && (decimalsFormControl.dirty || decimalsFormControl.touched)">{{getDAPErrorMessage()}}</mat-error>
          </mat-form-field>

        <mat-checkbox  [disabled]="true" [value]="data.functional_currency_exist" [checked] = "data.functional_currency_exist" >Operational</mat-checkbox>

 </mat-dialog-content>
    <mat-dialog-actions>

         <button mat-raised-button color="primary" type="submit"  [disabled]="currencyForm.invalid" (click)="submitClicked(currencyForm)">Submit</button>
         <button mat-raised-button color="accent" (click) = "closePanel()">Cancel</button>

    </mat-dialog-actions>
    </form>

A: Try it this way.
[disabled]="!currencyForm.valid"

instead of doing this
[disabled]="currencyForm.invalid"

I do remember that I once had the same issue as described above. And doing it my way solved it. Sorry, but I can't explain it in more detail as there are no more details. Somehow the invalid-flag does not work properly but valid does.


text:
Q: Red5 Media Server + jwPlayer not working as expected hi i'm running the red5 media server on my win 2003 server, it's assigned to its own IP-address. i've set up a testcase using jwplayer for streaming a video, unfortunately it doesn't work as expected (works locally, ports are open, when using port 5080 i can run the red5-demos from external)
i'm using the following settings for jwplayer:
  jwplayer('mediaspace').setup({
    'flashplayer': 'player.swf',
    'file': 'test.flv',
    'protocol': 'rtmp',
    'streamer': 'rtmp://myserver.com:1935',
    'controlbar': 'bottom',
    'width': '470',
    'height': '320'
  });

the problem is that jwplayer shows up an error:
Server not found: rtmpt://myserver.com:80

although i've defined protocol rtmp on port 1935, jwplayer is trying to use rtmpt on port 80? any ideas what's wrong? thanks

A: I think JWPlayer tries by default to fallback to RTMPT on port 80.
So that message:
Server not found: rtmpt://myserver.com:80

could be translated in the humen readable message:
I tried to connect to rtmp://myserver.com:1935, was not able to connect,
falled back to rtmpT (rtmp over HTTP Tunneling to bypass firewalls)
on port 80. But still failed

Sebastian


text:
Q: Search data in file using python, but searching the data by name I have file form.txt I want to search a data in file just using by name, so if I wrote a name the data in file by the name will show up. Anyone know how to do it?. I'm newbie at this python and don't know how to do it, thanks by the way!!
form.txt:

Farhan Hermansyah,Male,Moscow,25 December 2002, Christian, Russian,Not
Married, High School, Parung Permata Indah, 08123123123,
russian1sd4b3st@gmail.com, CEO
Tedy,Male,Japan, 21 Februari 1990, Jewish, Indonesian, Married, P.Hd, Grovesttreet, 1231123,imhandsome@gmail.com, General Manager

code.py
def search(name) :
name = input("Enter The Name You Want To Look :")
f = open("form.txt", "r")
for name in f :
         print(readlines[0]

A: # read txt file
filetxt = open("s.txt")

data = filetxt.readlines()

def searchName(name,text):
    index = text.find(name)
    if (index >=0):
        return 1
    else:
        return 0

for i in data:
    if (searchName("Tedy",i)):
        print(i)
    else:
        pass

this code should work when your data is like in example above.

A: I am not sure, but I think you are looking for this:
name = input()
with open('filename.txt', 'r') as f:
    for line in f.readlines():
        if name == line.split(',')[0]:
            print(line)