google analytics is showing an odd page on my site

We pushed a small UI change to the site last night. The google analytics code is in the header and has not been touched at all (entire header for the site and all the pages have not been touched at all)

Since the change, we are seeing a lot of hits logged to the page "/site/loading" which is not a page on our site. Even when we visit the site to test, we are occasionally seeing the active page show up as "/site/loading" instead of "/" or the specific page we are visiting. The pages are loading fine and the site is working fine. The error is happening somewhat randomly. Occasionally when someone visits the home page, it shows up as "/site/loading" and occasionally shows up correctly as "/"

Unclear why this is happening or what we might have done to trigger this changed behavior. Until yesterday, our tracking seemed fairly accurate.

Appreciate any ideas or suggestions


Change marker position - ui-gmap-google-map

I have problem with marker in ui-gmap-google-map. I want change position my marker but when I selected other city my marker doesn't wants change position.
Can anybody help?

Contoller

  setListeners = () ->
    $scope.$watch('selectedField.id', (val) ->
      if val
        $scope.marker = {
          id: 0,
          coords: {
            latitude: val.marker.latitude
            longitude: val.marker.longitude
          },
        }
    , true)

View

<ui-select ng-model="selectedField.id" theme="select2">
  <ui-select-match>
    <span ng-bind="$select.selected.street"></span>
  </ui-select-match>
  <ui-select-choices repeat="item in (fieldsList  | filter: $select.search)">
     <span ng-bind="item.street"></span>
  </ui-select-choices>
</ui-select>

...

<ui-gmap-google-map center='map.center' zoom='map.zoom'>
  <ui-gmap-marker
    idKey='marker.id'
    coords='marker.coords'
    options='marker.options'
    >
  </ui-gmap-marker>
</ui-gmap-google-map>


View returning null

Outline of my code is :

public class MainActivity extends Activity {
Client client;
MyImageView iv;
Bitmap b;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MyImageView iv = new MyImageView(this);
    Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.untitled);
    iv=(MyImageView)findViewById(R.id.ImageView1);}
    iv.setImageBitmap(bMap);
}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.example.zooming.MyImageView
    android:id="@+id/ImageView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:clickable="true"
    android:scaleType="matrix" />
</LinearLayout>

MyImgaeView.java

MyImageView extends View {
    public MyImageView(Context ct){
       super(ct);
       //some other works
       gestureDetector = new GestureDetector(new MyGestureDetector());
       new ConnectTask().execute("");
       }
     //Other code
     class MyGestureDetector extends SimpleOnGestureListener {
         @Override
         public boolean onDoubleTap(MotionEvent event) {
                iv=(MyImageView)findViewById(R.id.ImageView1);
                Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
                iv.setImageBitmap(bMap);
                    return true;
         }

   }
   class connectTask extends AsyncTask<String,Bitmap,Bitmap>
   {
       @Override
       protected Bitmap doInBackground(String... message) {
               //some code to get the bitmap
               publishProgress(mybitmap);
       return null;
       }

       @Override
       public void onProgressUpdate(Bitmap... values) {
       super.onProgressUpdate(values);
       iv=(MyImageView)findViewById(R.id.ImageView1);
       if(iv==null)
           Log.i("Exception",ex.toString());
       iv.setImageBitmap(values[0]);
       }
   }

}

iv is always returning null in ConnectTask(AsynTask) while its working fine in MyGestureDetector...why?  also when i am making the ConnectTask the inner class of MainActivity then its working fine...!!


Could not align social buttons horizontally

First of all, and before someone closes this question as "exact copy", I searched the site for and answer and couldn't find any which could help :)

I have a web page which has a social bar looks kinda like Bootstrap social bar in their front page. My site uses Bootstrap as the site template.

My problem with social buttons. I added Google+, Twitter and Facebook button and now I'm struggling in aligning correctly... thanks to Facebook button.

The code I'm using is exactly the same official code from the 3 social networks and I placed each button in an <li> of a <ul> (again, refer to Bootstrap front page for an example). Note: I added some background colour and some padding for make things clear.

The result of that is the image you see below (screen-shot from IE). Google+ and Twitter play nicely while Facebook makes things hard... or is it the opposite?

It's the same behaviour in all browsers I used for testing (IE, Firefox, Chrome and Opera)

UPDATE: Visit this Fiddle to see an example.


How can I Hide XML Fields And Reuse that file for Another Activity?

I want hide some fields in existed XML and use that XML as Input for Another Activity

Thanks in Advance.....


cmake: check if file exists at build time rather than during cmake configuration

I have a custom build command that needs to check if a certain file exists. I tried using

IF(EXISTS "/the/file")
...
ELSE()
...
ENDIF()

but that test is only evaluated one; when cmake is first run. I need it to perform the test every time a make is done. What's the method to check at make-time? Thanks.


verify creation of database objects such as triggers, procedures , permissions

I am creating triggers & procedures on a table from a winform application which uses sql server 2005 express.

I want that when the user clicks the create trigger/procedure button, then it creates both the objects & displays on a new Form that triggers & procedures are created with the names and tables on which they are created.

I mean that how do i verify that the objects are created. i want to verify and show it to the user that the objects are created on the so and so table.


Solr indixing large content website

I am using Solr 5.2 , I have a website with large content (bilingual), that needs to be indexed for search functionality, I need to index some meta data about each content (category, title, date,..), and I also need to index the content of the webpage, based on your knowledge and experience, is it correct to copy all the fields in a single field, and use this field for search, I am doing the following now

<fieldType name="compound_text" class="solr.TextField" positionIncrementGap="100" multiValued="true">
    <analyzer>
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.StopFilterFactory" words="lang/stopwords_ar.txt" ignoreCase="true"/>
      <filter class="solr.ArabicNormalizationFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
</fieldType>
<field name="compound_text_field" type="compound_text" multiValued="true" indexed="true" stored="true"/>
<field name="author_name"         type="strings"  indexed="false" stored="false"/>
<field name="category"            type="strings"  indexed="false" stored="true"/>
<field name="content_ar"            type="strings"  indexed="false" stored="true"/>
<field name="content_en"            type="strings"  indexed="false" stored="true"/>
<field name="content_title"       type="compound_text" indexed="true" stored="true" multiValued="true"/>
<field name="publish_date" type="tdate"/>
<copyField source="content_ar" dest="compound_text_field"/>
<copyField source="content_en" dest="compound_text_field"/>
<copyField source="content_title" dest="compound_text_field"/>
<copyField source="source" dest="compound_text_field"/>
<copyField source="category" dest="compound_text_field"/>
<copyField source="author_name" dest="compound_text_field"/>
<fieldType name="text_suggest" class="solr.TextField" positionIncrementGap="100">
    <analyzer>
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.ArabicNormalizationFilterFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
</fieldType>
<field name="text_suggest_field" type="text_suggest" indexed="true" stored="true"/>
<copyField source="content_title" dest="text_suggest_field>


Duplicate Symbol Error for architecture i386?

I am getting following error while build app.

I have checked the following things but still error not gone

1. file exists twice.
2. Import ".m" intead of .h
3. `File missing`
4. Duplicate function

Any other thing too check?

 duplicate symbol _downloadCompleted in:
   /Xcode/DerivedData/WAI2go-ckzrqcnbjsisokcplqkvzwxhclrg/Build/Intermediates/WAI2go.build/Debug-iphonesimulator/WAI2go.build/Objects-normal/i386/Middleware.o
    Xcode/DerivedData/WAI2go-ckzrqcnbjsisokcplqkvzwxhclrg/Build/Intermediates/WAI2go.build/Debug-iphonesimulator/WAI2go.build/Objects-normal/i386/ZipArchive.o
duplicate symbol _onDownloadCompleted in:
   Developer/Xcode/DerivedData/WAI2go-ckzrqcnbjsisokcplqkvzwxhclrg/Build/Intermediates/WAI2go.build/Debug-iphonesimulator/WAI2go.build/Objects-normal/i386/Middleware.o
   Library/Developer/Xcode/DerivedData/WAI2go-ckzrqcnbjsisokcplqkvzwxhclrg/Build/Intermediates/WAI2go.build/Debug-iphonesimulator/WAI2go.build/Objects-normal/i386/ZipArchive.o
duplicate symbol _onImageDownloadCompleted in:
    Developer/Xcode/DerivedData/WAI2go-ckzrqcnbjsisokcplqkvzwxhclrg/Build/Intermediates/WAI2go.build/Debug-iphonesimulator/WAI2go.build/Objects-normal/i386/Middleware.o
    Developer/Xcode/DerivedData/WAI2go-ckzrqcnbjsisokcplqkvzwxhclrg/Build/Intermediates/WAI2go.build/Debug-iphonesimulator/WAI2go.build/Objects-normal/i386/ZipArchive.o
ld: 3 duplicate symbols for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)


clearTextField() is not working in UIAutomator

i am new bee to uiautomator and when i am trying to clear the text field text with clearTextField() its not at all clearing. Can some one guide me how can i do this.

tried in this way also

while(!"".equals(obj.getText())
obj.clearTextField();

Thanks in advance.


Access violation error while creating linked list

Trying to create Lined List. I am having problem in the deleteNode function created in LinkedList.cpp file. Experiencing given error

Unhandled exception at 0x00D04C3C in LinkedList.exe: 0xC0000005: Access violation reading location 0x00000004.

previous->link = temp->link;

LinkedList.h file

class Node
{
public:
    int data;
    Node *link;
};
class LList
{
private:
Node *Head, *Tail;
//void recursiveTraverse(Node *);
public:
    LList();
    ~LList();
    void create();
    Node *getNode();
    void append(Node *);
    void insert(Node *, int);
    void rtraverse();
    void deleteNode(int);
    void display();
};

LinkedList.cpp

    #include "stdafx.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
LList::LList()
{
    Head = nullptr; Tail = nullptr;
}
LList::~LList()
{
    Node *Temp;
    while (Head != nullptr)
    {
        Temp = Head;
        Head = Head->link;
        delete Temp;
    }
}
void LList::create()
{
    char choice;
    Node *newNode = nullptr;

    while (5)
    {
        cout << "Enter Data in the List (Enter N to cancel) ";
        cin >> choice;
        if (choice == 'n' || choice == 'N')
        {
            break;
        }
        newNode = getNode();
        append(newNode);

    }

}

Node *LList::getNode()
{
    Node *temp = new Node;
    //cout << "Enter Data in the List";
    cin >> temp->data;
    temp->link = nullptr;
    return temp;
}
void LList::append(Node *temp)
{
    if (Head == nullptr)
    {
        Head = temp;
        Tail = temp;
    }
    else
    {
        Tail->link = temp;
        Tail = temp;
    }
}
void LList::display()
{
    Node *temp = Head;
    if (temp == nullptr)
    {
        cout << "No Item in the List" << endl;
    }
    else
    {
        while (temp != nullptr)
        {
            cout << temp->data << "\t";
            temp = temp->link;
        }
        cout << endl;
    }
}
void LList::insert(Node *newNode, int position)
{
    int count = 0; Node  *temp, *previous = nullptr;
    temp = Head;
    if (temp == nullptr)
    {
        Head = newNode;
        Tail = newNode;
    }
    else
    {
        while (temp == nullptr || count < position)
        {
            count++;
            previous = temp;
            temp = temp->link;
        }
        previous->link = newNode;
        newNode->link = temp;
    }

}
void LList::deleteNode(int position)
{
    int count = 1; Node * temp, *previous = nullptr;
    temp = Head;
    if (temp == nullptr)
    {
        cout << "No Data to delete." << endl;
    }
    else
    {
        while (count <= position + 1)
        {
            if (position == count + 1)
            {
                count++;
                previous = temp;
                previous->link = temp->link;
            }
            else if (count == position + 1)
            {
                count++;
                previous->link = temp->link;
            }
            count++;
            temp = temp->link;
        }
    }
}

Main.cpp goes here


versioning of the content

I am developing a PHP/mysql package to  add/edit questionnaire.. I want some pakage to save the versions of edits of questions and rollback to previous version. can anyone suggest such package..?


Python, next iteration of the loop over a loop

I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code)

    ok = 0
    for x in range(0,10):
        if ok == 1:
            ok = 0
            continue
        for y in range(0,20):
            if y == 5:
                ok = 1
                continue

What about in this situation?

for attribute in object1.__dict__:
    object2 = self.getobject()
    if object2 is not None:
        for attribute2 in object2:
            if attribute1 == attribute2:
                # Do something
                #Need the next item of the outer loop

The second example shows better my current situation. I dont want to post the original code because it's in spanish. object1 and object2 are 2 very different objects, one is of object-relational mapping nature and the other is a webcontrol. But 2 of their attributes have the same values in certain situations, and I need to jump to the next item of the outer loop.


Hive User Impersonation for Sentry

I was reading on that for while using sentry you must disable hive user impersonation.

Is it necessary to disable to impersonation? If Yes is there any other way to impersonate hive user with sentry enabled?


Does Titanium Studio have an "Immediate Window"?

I'm new to Titanium Studio and am wondering, does it had an equivalent to Visual Studio's "Immediate Window," so that I can do runtime execution of random statements and the like?  Thanks!

Nathan


Android app + webserver API using Federated login or OpenID (WITHOUT GAE)

I have an Android app that needs to upload data to an API (API will then save data in MySQL DB). I would like to use a Federated login (Google) or OpenID authentication procedure so that user does not need to register email + password for my app, but rather can use Google (or other account) that is saved in AccountManager.

Up until early this year, the solution was using GAE, as per Nick Johnson's famous recipe.  But since Google started charging for the use of GAE, this is not a viable solution anymore.  PLEASE DO NOT RECOMMEND USE OF GAE.

Has anyone ever managed to solve the problem of authenticating with Federated Login OR OpenID and then getting authorization on a third-party (your) webserver API?

NOTE: OAuth would be a straightforward solution for authorization except that it would rely on interacting (in a trusted manner) with a previously authenticated consumer, which is not the case when you authenticate the app user (on the mobile) using FedLogin or OpenID. OAuth works if my app (mobile + webserver) authenticates user (and I store login + password — which is EXACTLY what I am trying to avoid), but not if Google (or FB) do this for you.


how to clone an object in android?

Sorry for a novice question, but what would be the best way to copy/clone an object in java/android?

rlBodyDataObj rlbo = bdoTable.get(name);

right now code assigns an object from a hashTable, yet I need to get a clone of it, so that I'd be able to use it multiple times.

Thanks!


Using $(warning) inside Android.mk shows a false error in Eclipse. How can I fix this?

I'm working on an Android project, using the Eclipse ADT environment provided by Google. This project has a somewhat complex Android.mk file, that can be easily misconfigured.
In order to ensure correct build flow and output warning and diagnostic messages to the console output, I rely on the $warning() command.

The $warning() commands are working fine, with the expected output being shown in the Build console; however, the Eclipse IDE is flagging the lines where I invoke the $warning() commands as having errors. These errors are propagating hierarchically to the Project Explorer Navigation window, where the Android.mk and the jni folder are also shown as having errors.

Here is an example of a command that triggers an error:

$(warning value of BUILD_CONFIG IS '$(BUILD_CONFIG)')

Although everything is working as expected, I'm being a little pedantic and would like to remove these false errors from the IDE. Is this possible?


jquery selected value in drop down

I have a drop down. How do I get the selected option, not the value but innerHTML. I want CO from the example. This alert($('#mydropdown').val()); gives me the value 1 but I dont want that.

<select name='mydropdown' id='dd'>
<option value=1 selected>CO</option>
<option value=2>CA</option>

<option value=3>TX</option>

</select>


How to display all attributes of model subclass on first initialization?

Problem

When a child model is initialized for the first time, only defaults of the child are set as attributes.

When a second(and all subsequent) child is being initialized, the attributes of child display defaults of child and it's parent.

Fiddle

var Parent = Backbone.Model.extend({
    defaults: {
        name: "john",
        lname: "smith",
        age: 30,
        language: "english",
        location: "belgium"
    }
});

var Child = Parent.extend({
    defaults: {
        hobby: "doing nothing",
            age: 24,
        occupation: "student"
    },
    initialize: function () {
        this.constructor.__super__.initialize.apply(this, arguments);
        _.defaults(this.defaults, this.constructor.__super__.defaults);
        console.log(this.attributes);
    }
});

attributes of child initialized for the first time :

 var child1 = new Child();

child1.attributes :

 hobby: "doing nothing"
 age: 24
 occupation: "student"

attributes of same Child class, initialized for the second time:

var child2 = new Child();

child2 attributes:

age: 24
hobby: "doing nothing"
language: "english"
lname: "smith"
location: "belgium"
name: "john"
occupation: "student"

Question

Why are not all defaults(child's and parent's) are being set as attributes when a child model is initialized for the first time ?

Because i've to display a Backbone.Collection inside a <ul> and every model's attributes are configurable through a html form inside each <li>. But because of this problem, i can't get to all attributes of the first model in the collection.


NetworkX: how to properly create a dictionary of edge lengths?

Say I have a regular grid network made of 10x10 nodes which I create like this:

import networkx as nx
from pylab import *
import matplotlib.pyplot as plt
%pylab inline

ncols=10

N=10 #Nodes per side
G=nx.grid_2d_graph(N,N)
labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds=[(N-j-1,N-i-1) for i,j in inds]
posk=dict(zip(vals,inds))
nx.draw_networkx(G, pos=posk, with_labels=True, node_size = 150, node_color='blue',font_size=10)
plt.axis('off')
plt.title('Grid')
plt.show()

Now say I want to create a dictionary which stores, for each edge, its length. This is the intended outcome:

d={(0,1): 3.4, (0,2): 1.7, ...}

And this is how I try to get to that point:

from math import sqrt

lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}

But there clearly is something wrong as I get the following error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-c73c212f0d7f> in <module>()
      2 from math import sqrt
      3
----> 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
      5
      6

<ipython-input-7-c73c212f0d7f> in <dictcomp>(***failed resolving arguments***)
      2 from math import sqrt
      3
----> 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
      5
      6

TypeError: 'int' object is not iterable

What am I missing?


Csv file to an array

I have a csv file which contains the following values:

18/10/2013,  news item 1
18/10/2013,  news item 2
17/10/2013,  news item 3
16/10/2013,  news item 4

How do I go about putting this into an array in JavaScript, ordered by date?

Once I have got it into an array, I also need to get the text values.

So far I have something like this:

Function readTextFile(){

var rawFile = new XMLhttpRequest();
Var myArray;

rawFile.open("GET", csvfile, true);
rawFile.onreadystatechange = function(){

if(rawFile.readyState === 4){
  if(rawFile.Status === 200 || rawFile.Status === 0)
{

}
}
}

Sorry if the text above is not formatted properly, I am posting from my phone. thanks


Border color order

I have a table with every border set to 1px width solid.
I want the top, left and bottom border to be black, and the right border to be white.
So, i used this css code

border-right-color: white;
border-left-color: black;
border-top-color: black;
border-bottom-color: black;
border: solid 1px;

The problem comes in IE9, where the top right corner pixel will be white, but the bottom right corner will be black.

I suspect the problem comes form the way IE9 reorganize the style, because when i look at the css of my table in the developper tools console, it is ordered like this :

border-top-color: black;
border-right-color: white;
border-bottom-color: black;
border-left-color: black;
border-top-width: 1px;
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-top-style: solid;
border-right-style: solid;
border-bottom-style: solid;
border-left-style: solid;

This let me think that, maybe, the order used to defined colors makes it so the top border is colored black, then the right border is colored white (overwritting the top right corner), then the bottom border is colored black (overwritting the bottom right corner) and finnaly the left border is colored left.

The thing is that, on a white background, the top and bottom borders do not appear to be the same length (by one pixel). It may not be much, but I need those two borders to fit with other lines on my page.

So, how could i fix this? Is it really about the order the borders are colored, and if it is, how could I change that?


Using pattern in Shell Parameter Expansion

I am reading a page and trying to extract some data from it. I am interested in using bash and after going through few links, i came to know that 'Shell Parameter Expansion' might help however, i am finding difficulty using it in my script. I know that using sed might be easier but just for my knowledge i want to know how can i achieve this in bash.

shopt -s extglob

str='My work</u><br /><span style="color: rgb(34,34,34);"></span><span>abc-X7-27ABC | </span><span style="color: rgb(34,34,34);">build'
echo "${str//<.*>/|}"

I want my output to be like this: My work|abc-X7-27ABC |build

I thought of checking whether it accepts only word instead of pattern and it seems to be working with words.

For instance,

echo "${str//span style/|}" works but

echo "${str//span.*style/|}" doesn't

On the other hand, i saw in one of the link that it does accept pattern. I am confused why it's not working with the patern i am using above.

How to make sed do non-greedy match?
(User konsolebox's solution)


What is difference between char and varchar

CREATE TABLE IF NOT EXISTS `test` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `country` varchar(5) NOT NULL,
  `state` char(5) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

I tried following query to insert data

INSERT INTO `test`.`test` (`id` ,`country` ,`state`)
VALUES (NULL , 'south-india', 'Gujarat');

When I execute above query It will shows following warning

Warning: #1265 Data truncated for column 'country' at row 1
Warning: #1265 Data truncated for column 'state' at row 1

I found Reference that VARCHAR is variable-length.CHAR is fixed length.

Then what you mean by

VARCHAR is variable-length.

CHAR is fixed length.


Plotting on the video (Matlab)

I'd like to have a plot on my frame sequence in Matlab environment. For example, I have a specific value for each frame and I want to see its plot on the input video, let's say at the bottom. The values will be in a specific range.

In summary, I need to see the plot on the video, which will be updated frame by frame.

Any ideas will be very helpful. Thanks in advance!


Preload or not preload?

I'm making a puzzle game, where I use few types of sprites many times. So I have a question about the game performance. Which is better, to create the sprite in for/in loop later in setup() method, or to preload the sprite in initializer of class, and then just copy the sprite in setup()? For example:

func setup() {
    for i in 0...10 {
       let sprite = SKSpriteNode(imageNamed: "FirstSpriteName")
       sprite.position = etc...
    }
}

or preload the sprite when I initialize the class:

let firstSprite = SKSpriteNode(imageNamed: "FirstSpriteName")

and later in the setup() func:

func setup() {
    for i in 0...10 {
        let sprite = firstSprite.copy()
        sprite.position = etc...
    }
}


Does append() create a copy of the arguments or append the actual argument's reference to the list?

When I run

x = [0, 1]
y = [2, 3]
x.append(y)
x[2][1] = 4
print y

it prints out

[2, 4]

So, basically, is it appending the reference of the argument to the list? not a copy that is totally unrelated to the argument?


Python cannot find package setuptools

I get the error

Could not import setuptools which is required to install from a source distribution.
Traceback (most recent call last):
File "/home/comp1/anaconda3/lib/python3.5/site-packages/pip/req/req_install.py", line 387, in setup_py
import setuptools  # noqa
File "/home/comp1/anaconda3/lib/python3.5/site-packages/setuptools/__init__.py", line 10, in <module>
from setuptools.extern.six.moves import filter, filterfalse, map
ImportError: No module named 'setuptools.extern.six'

even though the same code runs perfectly on a variety of our computers. I do have setuptools installed. I also tried to remove and reinstall it.

EDIT: For some reason, now it works. I don't think we can call it solved, because I did not do anything, but I also don't have the issue anymore.


How can I parse an empty element with tinyxml2?

Using tinyXml2, I can parse
<MSG_TIME>2010-07-01 14:28:20</MSG_TIME>
 just fine, but
<MSG_TIME></MSG_TIME>
 and
<MSG_TIME/>
 both throw exceptions in C++ when those are perfectly valid XML (to my knowledge). Does anyone have a fix or suggestion for this? I do not control the source of this XML, and I need to be error tolerant.


How to print in iOS 4.2?

I want to integrate the print functionality in my app.

The document I want to print will be in .doc or .txt format.
I am not very experienced in iPhone development yet, so finding it difficult to implement it by following the Apple documentation.

If someone could help me by posting some sample code, will be a great help.


Collection View Xcode Swift 3 padding and spacing

I have this code for a collection view:

let sectionInsets = UIEdgeInsets(top: 50.0, left: 1.0, bottom: 1.0, right: 1.0)
fileprivate let itemsPerRow: CGFloat = 3

var items = ["1", "2", "3"]

I use this code in sizeforitemAt:

//2
    let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
    let availableWidth = view.frame.width - paddingSpace
    let widthPerItem = availableWidth / itemsPerRow

However it skips cells and leaves them blank. What I'm looking for is 3 cells per row with 50 padding on top and 1,1,1 on left right and bottom. Can anyone please help me?

Denis


using dapper to replace a fully fledged OR/M

I'm really impressed by Dapper micro OR/M, I really would like to use it as a side by side companion of some fully fledged OR/M, and my be evantually in place of it. I did not figure out anyway if there is some strategy to deserialize a hierarchy from db: for example the returned object for a recordset row would depend on a field ( the so called 'discriminator' in NH for example ). Furthermore the hierarchy can split more table via a join, so the type that represent the row will depend on the existence of the record in the other table. Having a hierarchy represented by a mixture of the two strategy above would be something that NH for example does not support, but that exist in the 'relational life'. So the questions:

does Dapper handle such a scenario ?

does this scenario wanish the Dapper efforts in term of performance ?

Another topic is caching. Dapper cache for queries is a little to much aggressive, wouldn't be better to have some "session like context" and have a query cache for each session, or would this again offend the main Dapper motivations ?


Angular equivalent to Backbone collection.get

Backbone has great methods for extracting and updating individual models (single datasets) which are part of a collection (array of objects).

I'm just learning Angular at the moment, and am being blown away by the binding, filtering and templating (much prefer to underscore). It makes light work of many tasks.

I'm struggling though, to find a simple way to pull a single object out of an array of objects. From what I've read on-line, my options are to use a filter on ng-repeat (which seems a bit odd as I'm not "repeating" anything, or to pull in jquery and use $.grep. Another way might be to build my own filter or to write something in raw javascript.

Which way would you use to pull a single object out of an array? Bear in mind that in Backbone, each object in a collection has a unique 'id' property, and I'm using the same paradigm with my business data in Angular. I'd rather not pull in jquery or underscore just to do that.

Apologies if an Angular method exists - I find the documentation a bit tricky to navigate. If it does, then please give an example of it in use. Many thanks.


Why do we need TensorFlow tf.Graph?

What is the purpose of:

with tf.Graph().as_default()

I have some tensorflow code that uses the above.
However, the code has only one graph, so why do we need this?


hide #dialog ui , when clicked outside ,example checked. pls

$(function() {
    $( "#dialog" ).dialog({
      autoOpen: false,
      show: {
        effect: "blind",
        duration: 2000
      },
      hide: {
        effect: "explode",
        duration: 500
      }
    });
$( "#opener" ).click(function() {
      $( "#dialog" ).dialog( "open" );
    });


how to replace image of imageview in lollipop?

Here i am facing a problem regarding android v5(lollipop). The common method
Imageview.setImageResource(//id) happily work with below android v5(lollipop), but not work in lollipop, so please suggest me your knowledge regarding this


Nested table with table-layout: fixed affecting parent table

I'm giving my nested table (within a <td> element) the style table-layout: fixed. For some reason, this is affecting my parent table as well:

Demo:

document.getElementById('set-fixed').addEventListener('click', function() {
  document.getElementById('result').innerHTML = (
    document.getElementById('nested').classList.toggle('fixed')
    ? 'fixed'
    : 'not fixed'
  )
})

table {
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
  padding: 2px;
}

table.fixed {
  table-layout: fixed;
}

<p>Set nested table's style <code>table-layout: fixed</code>: <button id="set-fixed">Toggle</button> (current: <span id='result'>not fixed</span>)</p>
<table width="100%">
  <tr>
    <th>Name</th>
    <th>Description</th>
    <th>Column 3</th>
    <th>Column 4</th>
  </tr>
  <tr>
    <td colspan="4">
      <table id='nested' width="100%">
        <tr>
          <td>Foo</td>
          <td>Baaaaaaar!</td>
          <td>Baz</td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td>Taco</td>
    <td>Beautiful, cheesy, and delicious.</td>
    <td>A</td>
    <td>B</td>
  </tr>
  <tr>
    <td>Marshmallow</td>
    <td>Too sweet for my tastes!</td>
    <td>A</td>
    <td>B</td>
  </tr>
</table>

Is this a bug with Firefox, or intentional (according to the relevant official spec)? What can I do to make my nested table's layout fixed without affecting my parent table?


jquery toggle open all div on one click

Please take a look at below codes, for whatever reason I am unable to open one div only when I click on the edit link, it opens all divs when I click the edit link.  This is what I have:

( function($) {
    $(document).ready(function() {
        // hides the slickbox as soon as the DOM is ready
        $('.slickbox').hide();
        // toggles the slickbox on clicking the noted link
        $('.slick-toggle').click(function() {
        $('.slickbox').toggle(400);
        return false;
        });
    });
} ) ( jQuery );

Here is the HTML part:

<li id="list_47">
<div>
    <div id="row">
        <div class="title id="bannerid59"><img src="banner_45_10.jpg" /></div>
        <div class="action"><a href="#" class=".slick-toggle">Edit</a></div>
    </div>
    <div id="row-right">
        <span class="small">Sort Order: 2</span><br>
    </div>
</div>
<div class="slickbox">blah blah box 1</div>
</li>

<li id="list_48">
<div>
    <div id="row">
        <div class="title id="bannerid60"><img src="banner_45_11.jpg" /></div>
        <div class="action"><a href="#" class=".slick-toggle">Edit</a></div>
    </div>
    <div id="row-right">
        <span class="small">Sort Order: 2</span><br>
    </div>
</div>
<div class="slickbox">blah blah box 2</div>
</li>

I have looked through other examples or solutions with no luck (such as replacing $('.slickbox').toggle(400); with $(this).next(".slickbox").slideToggle(400);)

Any pointer is greatly appreciated.  thanks.


ng-click not working inside the ng-repeat

I'am trying to display the products based on the brands but ng-click inside ng-repeat not working.
But ng-click outside the ng-repeat working fine.Is there any conflict inside ng-repeat...?

Module

var myApp = angular.module('myapplication', ['ngRoute', 'ngResource','uiSlider']);

My View

<a style="cursor:pointer" ng-click="Brandfilters = ''">All Brands</a>

<div class="list-group-item" ng-repeat="product in products | unique: 'brand'" >
   <a style="cursor:pointer" ng-click="Brandfilters='{{product.brand}}'">{{product.brand}}</a>
</div>

My Controller

myApp.controller("StoreListCtr", ['$scope', '$http', '$resource',  '$location',
      function($scope, $http, $resource, $location) {

        $scope.products = Products.query();
        $scope.Brandfilters = null;
        $scope.lower_price = 100;
        $scope.upper_price = 500;

        $scope.priceRange = function(products) {
          return (products['cost'] >= $scope.lower_price
                          && products['cost'] <=$scope.upper_price);
        };
}])


Mininet uses openvSwitch?

I am new to Mininet and openvSwitch.

I know that mininet creates a virtual network using my pc resources.

And I know that openvSwitch creates virtual switches.

But I couldn't understand if mininet uses virtual switches created by openvSwitch to create the virtual network.


How to disable or enable view if toggle is on and off in pbrevalviewController

In a PBRevealViewController, how to disable user interaction of view when view toggle is on and enable when toggle is off?


lex parser not displaying hex correctly

I'm trying to identify a hex number from a parsed text file and everything is about 99% accurate however I keep having an issue with this certain instance 0xa98h. whenever it finds this line it will output 0xa98 instead of ignoring it altogether since it is not valid. I've tried so many variations to this code and have yet to find a way to exclude that issue.

[-]?[0][x|X][0-9A-F]+ {cout << yytext << " Number" << endl; }


Using C++ together with OpenGL in Xcode

My goal is to develop a cross-plattform based application in C++ and OpenGL.

Since I am using a Macbook Pro, its natural IDE is Xcode, so I would like to use it. I've successfully compiled pure C++ code in Xcode, by using the Command Line tool as a template for the projects.

My question is how can I compile OpenGL code without messing with Cocoa and Objective-C. The main reason behind this is that since I want to deploy cross-plattform applications, I want to stick to C++ as much as possible.

While this is true, It wouldn't be that much of a problem if I necessary had to use a little of Objective-C and Cocoa. But I would like to get my main project code in C++ and the less possible amount of Objective-C/Cocoa, understanding by "main project code" the code specific to my application, such as my classes, objects, and stuff related to the aim of the application, ie. , the main body of the code.

If using C++/OpenGL without messing with Obj-C/Cocoa is not worth in terms of complexity, then the question could be reformulated as simply what is the way to compile simple OpenGL code in Xcode?


What are external entities and notations in DTD?

I have been reading about these topics in W3C Recommendation and Wikipedia. I am not sure if I have fully understood them. Could someone explain clearly to me what external entities and notations are in DTD? What are their uses exactly?

Here are some examples of external entity declarations:

<!ENTITY open-hatch SYSTEM
         "http://www.textuality.com/boilerplate/OpenHatch.xml">
<!ENTITY open-hatch PUBLIC
         "-//Textuality//TEXT Standard open-hatch boilerplate//EN"
         "http://www.textuality.com/boilerplate/OpenHatch.xml">
<!ENTITY hatch-pic SYSTEM
         "../grafix/OpenHatch.gif"
         NDATA gif >

Correct me if I am wrong. A general, internal entity replaces the entity name (&ent;) in the document body with the string declared. Does an external entity replaces the entity name with the entire content of an external document?


Encryption with RSA Algorithm-letter 'w','x','y','z'

I have been writing code for RSA Algorithm. It works well but, but unfortunately it showed wrong answer for small 'w','z','x','y'.

My encryption algorithm is simple. With two distinct prime number and 'e' I generate the public key, then by generating 'd' I created the private key. Then with the BIGMOD(fast exponentiation) algorithm I just calculate the modulus part to encrypt & decrypt. Here's my code:

#include<stdio.h>
#include<string.h>

long long int square(long long int a);
long long int BigMod(int M,int E,int N);
void encrypt(int l,int E,int N);
void decrypt(int E,int N );

int main()
{
    main_RSA();
    return 0;
}

void main_RSA()
{

    int p,q;
    printf("Write two distinct Prime number separated by space:");
    scanf("%d %d",&p,&q);
    int n=p*q;
    int phi=(p-1)*(q-1);
    int e;
    printf("Enter a prime number 'e' as GCD(e,(P-1)*(Q-1)) : ");
    scanf("%d",&e);
    printf("public key( e , n ) : ( %d %d )\n",e,n);
    int d,RES=-1;
    for(d=1;;d++){
        RES=(d*e)%phi;
        if(RES==1)break;
    }
    printf("Private Key( d,n ) : ( %d %d )\n",d,n);
    printf("Please input your string : ");
    char arr[1000000];
    fflush(stdin);
    gets(arr);
    int i;
    FILE *fp=fopen("RSAlog.dll","w");
    fclose(fp);
    for(i=0;arr[i];i++){
        int ASCII=arr[i];
        encrypt(ASCII,e,n);
    }
    printf("\n");
    FILE *fpp=fopen("RSAlog.dll","a");
    fprintf(fp,"-1");
    fclose(fpp);
    decrypt(d,n);
}
long long int BigMod(int b,int p,int m)  //b^p%m=?
{
    if(p==0)return 1;
    else if(p%2==0)return square(BigMod(b,p/2,m))%m;
    else return ((b % m) * BigMod(b,p-1,m)) % m;

}

long long int square(long long a)
{
    return a*a;
}

void encrypt(int m ,int e,int n){
    FILE *fp;
    fp=fopen("RSAlog.dll","a");
    int c=BigMod(m,e,n);
    printf("%d ",c) ;
    fprintf(fp,"%d ",c);
    fclose(fp);
}

void decrypt(int d,int n){
    FILE *fp;
    fp=fopen("RSAlog.dll","r");
    while(1){
        int c;
        fscanf(fp,"%d",&c);
        //printf("%d ",c);
        if(c==-1)break;
        int m=BigMod(c,d,n);
        printf("%c",m);
    }
}

Output:

Write two distinct Prime number separated by space:7 17
Enter a prime number 'e' as GCD(e,(P-1)*(Q-1)) : 5
public key( e , n ) : ( 5 119 )
Private Key( d,n ) : ( 77 119 )
Please input your string : the quick brown fox runs over the lazy dog
114 83 33 2 78 87 56 29 116 2 98 88 76 0 94 2 51 76 1 2 88 87 94 47 2 76 118 33 88 2 114 83 33 2 75 20 5 32 2 53 76 52
the quick bro n fo☺ runs over the la♥☻ dog

Can anybody help me?


How specify Ajax jquery url path if all codes in one file

I have issue with specifying the Ajax jQuery url path. I have one function  contains all Html markup codes, php sned mail codes and Ajax jQuery code as follow

How i can specify url property in ajax code?

Info: i use wordpress theme and this function within my plugin directory

<?php
    function bsncontact() {

        //All php codes here
?>
        <form id="ajax-contact" class="navbar-form" action="" method="POST">
            <!-- other html markup codes -->
        </form>
        <script type="text/javascript">
            jQuery(function(){
            jQuery.ajax({
                type: 'POST',
                url: '',
                data: "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message,
                success: function(text) {

                }
           });
           });
       </script>
<?php
}
?>


How to pass special char to perl script?

1) In php user enter: query like '%key%' or query like '%door%'

2) I am calling perl script as

ob_start();
passthru("perl -w search.pl 'query');

3) In the perl if i print

print "query: $ARGV[0]\n";

4) It prints as
query like ^m'%key%'^M or query like ^m'%door%'^M

Any suggestions to print as user entered value.


BOM being added to any return or die response

I'm using jQuery to retrieve a json response from an endpoint

die(json_encode(array('success' => 3, 'message' => 'You must use at least 1 credit or more.')));

Whenever I check the JSON response received in chrome developer tools I'm getting a red dot showing \ufeff is being added before the json response. I've encoded the PHP file with UTF-8 in Notepad++ however it still adds the BOM character infront of any response. If I return anything or change the die it will still show the BOM character in the response.

I've tried the same file on my localhost and it works absolutely fine however on the server it adds the character.

I'm at a loss as to what's causing the issue, any help would be greatly appreciated.


Check if .ISO is already mounted in powershell, if not then mount

I have an ISO file that I copied off of an old game disk. But in order for me to play the game, I have to mount the ISO.
I wrote a small Batch file that runs the .ps1 PowerShell file to mount the ISO and then runs the EXE to start the game after it has been mounted. My problem is, if I run the script more than once it will mount the ISO again.

I want to check if the ISO is attached, mount it if it is not, or run the EXE if it is.

Here's what I have to mount the ISO:

Batch.

ECHO "Mounting Stunt Track Driver"

@ECHO off

Powershell.exe -executionpolicy remotesigned
-File  "C:\Users\Allen\Documents\Games\Hot Wheels Stunt Track
Driver\setup\hot98\mount.ps1"

start /d "C:\Users\Allen\Documents\Games\Hot Wheels Stunt Track
Driver\setup\hot98" stunt.exe

PowerShell

#mounts the image
Mount-DiskImage -ImagePath "C:\Users\Allen\Documents\Games\Hot Wheels Stunt
Track Driver\setup\hot98\HotwheelsStuntTrack.iso"


CSS property so that the text inside <div> element does not extend outside of background of <div>

What can I add to CSS property so that the text inside the div element does not extend out of my background color? I'm guessing that because the actual width of the div element is width of full page, so I will have to shrink my div element.

Please see example here

example

<div class="test">sadfssdfjklsdfjklsdfsdfksdfkhsdfksdfkhsdfkhsdkhfsdhkfksdhkhsdfkhsdk</div>

.test {
background: grey;
width: 400px;
height: 100px;
}


How to know if user is logged with google or facebook using passport.js?

It easy to find if user is logged in. But how can I check if user is logged with specific oauth client?. ex. Google or Facebook


D3js v4: scaleOrdinal does not have the rangePoints()

I'm migrating the parallel coordinates source code here to the newest d3js version (d3js 4.5.0). I'm stuck to this line:

var x = d3.scale.ordinal().rangePoints([0, width], 1)

It seems that in d3js v4 the rangePoints function does not exist anymore. I can change to d3.scaleOrdinal(), but it has only the range function, not the rangePoints function. Any clue on for this?


In AngularJS, Is there a global way to check if any $timeout is pending?

I am using Protractor to test my code written in AngularJS

Probably there is some $timeout running in my AngularJS code which is making Protractor wait too long until it times out and gives error. But I am not able to figure out where in my code I am doing a continuous timeout/polling. Might be some library I am using but not sure.

Is there a global way to check in Angular how many timeouts are pending overall?

I am getting this error:

Uncaught exception: Timed out waiting for Protractor to synchronize
  with the page after 10 seconds. Please see
  https://github.com/angular/protractor/blob/main/docs/faq.md

I have also tried increasing default timeout of page load from 10secs to upto 60secs which is way more than enough for my page to load. But still no success.

This also brings me to another question: What are the advantages of using $timeout over the normal setTimeout in javascript


Silverlight RadGridView refresh

I'm deleting a user from my GridView, but when I delete it. I first need to refresh my page to see the result.

Anybody any idea?

This is where I try to rebind the datasource

if (e.PropertyName == "deleted")
            {
                RadGridView1.ItemsSource = null;
                RadGridView1.DataContext = null;
                RadGridView1.DataContext = _viewModel;
                _viewModel.GetCovrUsers();

                RadGridView1.ItemsSource = _viewModel.CovrUsers;
                this._viewModel.PropertyChanged -= _viewModel_PropertyChanged;

            }


merge same array index according to key and build a new array

I am trying to merge array index such as

011,021,031, 012,022,032, 013,023,033, 014,024,034 .

$temp = array();
foreach($samplearray as $key => $val){
    foreach($val as $key1 => $val1){
       //what should logic here
    }
}

sample array

$samplearray = array ( "AA"  => array ( 0  => array ( "created by" => "011",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                                ),
                                1  => array ( "created by" => "012",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                2  => array ( "created by" => "013",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                3  => array ( "created by" => "014",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            )
                                ),
                "BB"  => array ( 0  => array ( "created by" => "021",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                1  => array ( "created by" => "022",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                2  => array ( "created by" => "023",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                3  => array ( "created by" => "024",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            )
                                ),
                "CC"  => array ( 0  => array ( "created by" => "031",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                1  => array ( "created by" => "032",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                2  => array ( "created by" => "033",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            ),
                                3  => array ( "created by" => "034",
                                                "date" => "12-03-14",
                                                "time" => "12.00 pm"
                                            )
                                )
                );

Required output

$newArray = array ( 0  => array ( "created by" => "011",
                                    "date" => "12-03-14",
                                    "time" => "12.00 pm"
                                ),
                    1  => array ( "created by" => "021",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    2  => array ( "created by" => "031",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    3  => array ( "created by" => "012",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    4  => array ( "created by" => "022",
                                    "date" => "12-03-14",
                                    "time" => "12.00 pm"
                                ),
                    5  => array ( "created by" => "032",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    6  => array ( "created by" => "013",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    7  => array ( "created by" => "023",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    8  => array ( "created by" => "033",
                                    "date" => "12-03-14",
                                    "time" => "12.00 pm"
                                ),
                    9  => array ( "created by" => "014",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    10  => array ( "created by" => "024",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                    11  => array ( "created by" => "034",
                                "date" => "12-03-14",
                                "time" => "12.00 pm"
                                ),
                );


Sandboxing my App with Scripting Bridge to send email

I'm using a scripting bridge for sending mails from my Mac App. Now I need to sandbox the app and sending mails is not longer working while sandboxing is enabled.

Does anybody know how to fix that?

Thanks,
Andreas

Code:
`

/* create a Scripting Bridge object for talking to the Mail application */
    MailApplication *mail = [SBApplication applicationWithBundleIdentifier:@"com.apple.Mail"];

/* create a new outgoing message object */
MailOutgoingMessage *emailMessage =
[[[mail classForScriptingClass:@"outgoing message"] alloc]
 initWithProperties:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [self.subjectField stringValue], @"subject",
  [[self.messageContent textStorage] string], @"content",
  nil]];

/* add the object to the mail app  */
[[mail outgoingMessages] addObject: emailMessage];
...

`


Bootstrap 3.0.3: dropdown menu-items not clickable on mobile

On my website the links in the dropdown menu's are not working on mobile devices (Android ánd iOS). That means that when I click on a menu item on desktop, it works fine, and when I click the same item on my iPod touch it just closes the dropdown and does nothing. The parent items function well.

For example: when I press 'Activiteiten' and then press 'Wandelroute', nothing happens on mobile. When I draw my window (on desktop) at a width of 320px (like the width of a mobile device) the menu just works. I doubt whether my code causes the problem or the mobile device does.

What I've tried so far:

I've put jQuery and Bootstrap in the right order;

Included bootstrap-dropdown.js;

Included the following code:

.dropdown-backdrop
{ position: static; }

And then there's that other strange thing. On this page of the same website, the menu functions okay on mobile devices. I've got absolutely no idea what's different on that page compared to the other ones.

I'm using Joomla 3.x, jQuery 1.11.1 and Bootstrap 3.0.3.


Entity Framework Include Record with certain value in a Navigation Property

I am using Entity Framework 6 Code First and I'm configuring the mapping of my domain model with Fluent API. I don't see how to create a navigation properties for a Table which is a little tricky.
I have several objects which can make noise, I would like to record that noise in a NoiseRecord Table.

I need some kind of conditional mapping, something like that :

modelBuilder.Entity<NoiseRecord>().HasRequired(n=>n.Origine.OrigineType()=="Car").WithMany(c=>c.NoiseRecords);

That would be the mapping of the Car Navigation Property to avoid that, for example, it includes record related to Planes.

Here is my code

public interface INoisy
{
    int ID {get; set;}
    string OriginType()
    ...
    //And other useful things not related to persistence
}

public class Car : INoisy
{
    ...
    ICollection<NoiseRecord> NoiseRecords { get; set; }
    string OrigineType()
    {
        return "Car";
    }
}

public class Plane : INoisy
{
    ...
    ICollection<NoiseRecord> NoiseRecords {get; set;}
    string OrigineType()
    {
        return "Plane";
    }
}

And a couple of other classes implement INoisy also.
Below is the NoiseRecord Table.

public class NoiseRecord
{
    public int RecordID {get; set;}
    public INoisy NoiseOrigine {get; set;}
    public double NoiseMagnitude {get; set;}
}

I'm looking for a way to achieve that with Fluent API.

Thank you !


Index into NumPy array ignoring NaNs in the indexing array

I have an array of zeros

arr = np.zeros([5,5])
array([[ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.],
   [ 0.,  0.,  0.,  0.,  0.]])

I want to assign values based on index so I did this .

out = np.array([[nan,2.,4.,1.,1.],[nan,3.,4.,4.,4.]])

arr[out[0].astype(int),np.arange(len(out[0]))] = 1
arr[out[1].astype(int),np.arange(len(out[1]))] = 1

Assignment works fine if there is 0 instead of nan.

How can I skip assignment in case of nan? and Is it possible to assign values at once from a multidimensional index array rather than using for loop ?


C strlen using pointers

I have seen the standard implementation of strlen using pointer as:

int strlen(char * s) {
  char *p = s;
  while (*p!='\0')
    p++;
  return p-s;
}

I get this works, but when I tried to do this using 3 more ways (learning pointer arithmetic right now), I would want to know whats wrong with them?

This is somewhat similar to what the book does. Is this wrong?

int strlen(char * s) {
  char *p = s;
  while (*p)
    p++;
  return p-s;
}

I though it would be wrong if I pass an empty string but still gives me 0, kinda confusing since p is pre increment: (and now its returning me 5)

int strlen(char * s) {
  char *p = s;
  while (*++p)
    ;
  return p-s;
}

Figured this out, does the post increment and returns +1 on it.

int strlen(char * s) {
  char *p = s;
  while (*p++)
    ;
  return p-s;
}


Creating Purchase Info Record in SAP

I am trying to create a Purchase Info Record (ME11) in SAP using the below JCo code:

It executes without fail and throws no error, but i am not able to get the newly created info record in SAP. In ME13 it says info record not found. Can i know what am i missing?

IFunctionTemplate ft1 = mRepository.getFunctionTemplate("ZME_INITIALIZE_INFORECORD");
    JCO.Function function1 = ft1.getFunction();
    mConnection.execute(function1);

    IFunctionTemplate ft = mRepository.getFunctionTemplate("ZME_DIRECT_INPUT_INFORECORD");
    JCO.Function function = ft.getFunction();
    JCO.ParameterList importparams =function.getImportParameterList();

    //  Setting HeadData Structure Information
    JCO.Structure headStructure = importparams.getStructure("I_EINA");
    //headStructure.setValue("105","MANDT");
    //headStructure.setValue("5300259768", "INFNR");
    headStructure.setValue("MYPART0006", "MATNR");
    //headStructure.setValue("MYPART0006", "IDNLF");
    headStructure.setValue("100002","LIFNR");
    headStructure.setValue("10000","MATKL");
    headStructure.setValue("KGS","MEINS");
    headStructure.setValue("1","UMREZ");
    headStructure.setValue("1","UMREN");
    headStructure.setValue("SG","URZLA");
    headStructure.setValue("KGS","LMEIN");
    //headStructure.setValue("0000005300259768","URZZT");

    JCO.Structure headStructure1 = importparams.getStructure("O_EINA");
    //headStructure1.setValue("105","MANDT");
    //headStructure1.setValue("5300259768", "INFNR");
    headStructure1.setValue("MYPART0006", "MATNR");
    //headStructure1.setValue("MYPART0006", "IDNLF");
    headStructure1.setValue("100002","LIFNR");
    headStructure1.setValue("10000","MATKL");
    headStructure1.setValue("KGS","MEINS");
    headStructure1.setValue("1","UMREZ");
    headStructure1.setValue("1","UMREN");
    headStructure1.setValue("SG","URZLA");
    headStructure1.setValue("KGS","LMEIN");

    //headStructure1.setValue("0000005300259768","URZZT");
    System.out.println("General Data Set");

    JCO.Structure purchaseDataStructure = importparams.getStructure("I_EINE");
    //purchaseDataStructure.setValue("105","MANDT");
    //purchaseDataStructure.setValue("5300259768", "INFNR");
    purchaseDataStructure.setValue("1000","EKORG");
    purchaseDataStructure.setValue("1000", "WERKS");
    purchaseDataStructure.setValue("003","EKGRP");
    purchaseDataStructure.setValue("USD","WAERS");
    purchaseDataStructure.setValue("3","APLFZ");
    purchaseDataStructure.setValue("1","PEINH");
    purchaseDataStructure.setValue("1","BPUMZ");
    purchaseDataStructure.setValue("1","BPUMN");
    purchaseDataStructure.setValue("1000","EFFPR");
    purchaseDataStructure.setValue("0001","BSTAE");
    purchaseDataStructure.setValue("100000","NETPR");
    purchaseDataStructure.setValue("X","KZABS");

    JCO.Structure purchaseDataStructure1 = importparams.getStructure("O_EINE");
    //purchaseDataStructure1.setValue("105","MANDT");
    //purchaseDataStructure1.setValue("5300259768", "INFNR");
    purchaseDataStructure1.setValue("1000","EKORG");
    purchaseDataStructure1.setValue("1000", "WERKS");
    purchaseDataStructure1.setValue("003","EKGRP");
    purchaseDataStructure1.setValue("USD","WAERS");
    purchaseDataStructure1.setValue("3","APLFZ");
    purchaseDataStructure1.setValue("1","PEINH");
    purchaseDataStructure1.setValue("1","BPUMZ");
    purchaseDataStructure1.setValue("1","BPUMN");
    purchaseDataStructure1.setValue("1000","EFFPR");
    purchaseDataStructure1.setValue("0001","BSTAE");
    purchaseDataStructure1.setValue("100000","NETPR");
    purchaseDataStructure1.setValue("X","KZABS");

    mConnection.execute(function);

    IFunctionTemplate ft2 = mRepository.getFunctionTemplate("ZME_POST_INFORECORD");
    JCO.Function function2 = ft2.getFunction();

    JCO.ParameterList importparams2 =function2.getImportParameterList();
    importparams2.setValue("MYPART0006", "I_MATNR");
    importparams2.setValue("MYPART0006", "O_MATNR");
    mConnection.execute(function2);


Returning a value of a high order function doesn't

I have the following:

def retSomething(x: Int): Int => Int = x*x

assert(retSomething(5)(5) == 25)
assert(retSomething(1)(1) == 1)
assert(retSomething(1)(0) == 0)

But the assertions fail. Surely that is correct, but it says implementation is missing when running it.


Change an element css while hovering on another element in css?

Is there any way to change an element's css while focusing or hovering on one of it's children?

Ex: while I move my mouse on A, B's background color changes.
if B is a descendant A, it is possible.

--A

-----B

using #A:hover #B { background-color: blue }

DEMO

in sibling:

---A

---B

It is : #A:hover ~ #B { background-color: blue; }

DEMO

assume B is a descendant of A.

what if I want to change #A background, while I am hovering on B. how could it be?

--A

-----B


Using Spritesheets in Tkinter

I'm writing a GUI in Python's Tkinter, and I can't find how to use the canvas's create_image method to only draw a single sprite from a spritesheet. Thanks in advance to anyone who can tell me what I need to do for this!


How can one combine overriding with stackable traits in Scala?

In Swing and Wicket applications it is normal to override methods in classes that are provided by the framework. For example:

val form = new Form("form") {
  override def onSubmit() { println("Form was submitted") }
}

Where for the example Form can be defined as:

abstract class Form(id: String) {
  def onSubmit()
  def error(msg: String) { println(msg) }
}

Many form implementation need error handling. For this I created a stackable trait:

trait FormErrorHandler extends Form {
  abstract override def onSubmit() {
    try super.onSubmit()
    catch { case e: Exception => error("error during submit " + e.getMessage) }
  }
}

If I now try to combine this I get compiler errors:

val form = new Form("form") {
  override def onSubmit() { println("Form was submitted") }
} with FormErrorHandler // DOES NOT COMPILE

I worked around it with:

class MyForm extends Form("form") {
  override def onSubmit() { println("Form was submitted") }
}
val form = new MyForm with FormErrorHandler

but it just doesn't read as well; I have to name a class that is normally anonymous.

Any suggestions to make this look nice?
Would the syntax construct I tried make sense for a future Scala version?


How get Vertical Button view from xml

I want create a Button in Vertically.May be we can by extending a button and re-render(rotate) the canvas to vertical we can get the custom Button. But i need it from xml.check the graphical representation.i need a button like this.


Jaeger standarlone without docker

Cannot find any information if Jaeger can be executed without docker?
Does a standalone jar exist, or will there be a release in the future for Jaeger like Zipkin has ?


ArrayList becoming huge in program to guess number between 1000-9999

The program guesses a number between 1000-9999 and the user says how many numbers of the guess are the right number and in the right spot (but only inputs the amount of correct numbers). However, every time I try it, I get a huge list of duplicates but only one entry of the correct number. How would I go about making sure there are no duplicates in my ArrayList? I'd prefer being pointed in the right direction and not just given the answer, thanks! Here is my code (main method was written by my professor and I shouldn't need to change it):

import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;

public class GuessingGame {

    public int numGuesses = 0;
    public ArrayList<Integer> numbers = new ArrayList<Integer>();
    public int guess;

    public GuessingGame ( ) {
        for (int i = 1000; i < 10000; i++) {
            numbers.add(i);
        }
        //populating numbers ArrayList

    }

    public int myGuessIs() {
        numGuesses++;
        //increases number of guesses
        int tempIndex = (int) (Math.random() * numbers.size());
        int myguess = numbers.get(tempIndex);
        //creates a new guess
        guess = myguess;
        //sets global variable
        return myguess;
    }

    public int totalNumGuesses() {
        return numGuesses;
        //returns guesses needed to reach solution
    }

    public void updateMyGuess(int nmatches) {
        ArrayList<Integer> temp = new ArrayList<Integer>();
        ArrayList<Integer> temp2 = new ArrayList<Integer>();
        int first = guess/1000;
        int second = (guess/100)%10;
        int third = (guess/10)%10;
        int fourth = guess%10;
        //variables for each digit of guess
        if (nmatches == 1) {
            for (int i = 0; i < numbers.size(); i++) {
                if (numbers.get(i)/1000 == first) temp.add(numbers.get(i));
                if ((numbers.get(i)/100)%10 == second) temp.add(numbers.get(i));
                if ((numbers.get(i)/10)%10 == third) temp.add(numbers.get(i));
                if (numbers.get(i)%10 == fourth) temp.add(numbers.get(i));
            }
            numbers.clear();
            numbers.addAll(temp);
        }else if (nmatches == 2) {
            for (int i = 0; i < numbers.size(); i++) {
                if (numbers.get(i)/1000 == first &&
                    (numbers.get(i)/100)%10 == second) temp.add(numbers.get(i));
                if (numbers.get(i)/1000 == first &&
                    (numbers.get(i)/10)%10 == third) temp.add(numbers.get(i));
                if (numbers.get(i)/1000 == first &&
                    numbers.get(i)%10 == fourth) temp.add(numbers.get(i));
                if ((numbers.get(i)/100)%10 == second &&
                    (numbers.get(i)/10)%10 == third) temp.add(numbers.get(i));
                if ((numbers.get(i)/100)%10 == second &&
                    numbers.get(i)%10 == fourth) temp.add(numbers.get(i));
                if ((numbers.get(i)/10)%10 == third &&
                    numbers.get(i)%10 == fourth) temp.add(numbers.get(i));
            }
            numbers.clear();
            numbers.addAll(temp);
        }else if (nmatches == 3) {
            for (int i = 0; i < numbers.size(); i++) {
                if (numbers.get(i)/1000 == first && (numbers.get(i)/100)%10 == second
                    && (numbers.get(i)/10)%10 == third) temp.add(numbers.get(i));
                if (numbers.get(i)/1000 == first && (numbers.get(i)/10)%10 == third
                    && numbers.get(i)%10 == fourth) temp.add(numbers.get(i));
                if ((numbers.get(i)/100)%10 == second && (numbers.get(i)/10)%10 == third
                    && numbers.get(i)%10 == fourth) temp.add(numbers.get(i));
            }
            numbers.clear();
            numbers.addAll(temp);
        }else {
            for (int i = 0; i < numbers.size(); i++) {
                if (numbers.get(i)/1000 == first) temp2.add(numbers.get(i));
                if ((numbers.get(i)/100)%10 == second) temp2.add(numbers.get(i));
                if ((numbers.get(i)/10)%10 == third) temp2.add(numbers.get(i));
                if (numbers.get(i)%10 == fourth) temp2.add(numbers.get(i));
            }
            numbers.removeAll(temp2);
        }
        //creates new smaller ArrayList with better guesses
        //sets numbers as the smaller list
        //update the guess based on the number of matching digits claimed by the user
        for (int i = 0; i < numbers.size(); i++) {
            System.out.println(numbers.get(i) + "   " + i);
        } //troubleshooting

    }

    public static void main(String[] args) {

        GuessingGame gamer = new GuessingGame( );

        JOptionPane.showMessageDialog(null, "Think of a number between 1000 and 9999.\n Click OK when you are ready...", "Let's play a game", JOptionPane.INFORMATION_MESSAGE);
        int numMatches = 0;
        int myguess = 0;

        do {
            myguess = gamer.myGuessIs();
            if (myguess == -1) {
                JOptionPane.showMessageDialog(null, "I don't think your number exists.\n I could be wrong though...", "Mistake", JOptionPane.INFORMATION_MESSAGE);
                System.exit(0);
            }
            String userInput = JOptionPane.showInputDialog("I guess your number is " + myguess + ". How many digits did I guess correctly?");
            // quit if the user input nothing (such as pressed ESC)
            if (userInput == null)
                System.exit(0);
            // parse user input, pop up a warning message if the input is invalid
            try {
                numMatches = Integer.parseInt(userInput.trim());
            }
            catch(Exception exception) {
                JOptionPane.showMessageDialog(null, "Your input is invalid. Please enter a number between 0 and 4", "Warning", JOptionPane.WARNING_MESSAGE);
                numMatches = 0;
            }
            // the number of matches must be between 0 and 4
            if (numMatches < 0 || numMatches > 4) {
                JOptionPane.showMessageDialog(null, "Your input is invalid. Please enter a number between 0 and 4", "Warning", JOptionPane.WARNING_MESSAGE);
                numMatches = 0;
            }
            if (numMatches == 4)
                break;
            // update based on user input
            gamer.updateMyGuess(numMatches);

        } while (true);

        // the game ends when the user says all 4 digits are correct
        System.out.println("Aha, I got it, your number is " + myguess + ".");
        System.out.println("I did it in " + gamer.totalNumGuesses() + " turns.");
    }
}


Instantiate a prefab in a function with unity

I'm trying to instantiate some prefabs in my scene, I'm forced to do it in a function (not main thread) because I instantiate a prefab only when I receive some data throught an TCP protocol.

Right now, I'm just testing with a cube prefab, but it's not working :

     private void addAircraft(Plane plane)
    {
        listPlane.Add(plane);
        //THIS 2 LINES ARE THE PROBLEM
        GameObject cube = Instantiate(Resources.Load("Cube", typeof(GameObject))) as GameObject;
        cube.transform.position = new Vector3((float)plane.X, 0, (float)plane.Y);
        //
        planeId_Object_Dictionnary.Add(plane.Flight, cube);
        Debug.Log("Plane " + plane.Flight + " is added");
    }

It return me the error :

Load can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

Even if, a lot of people have encounterd this problem, I can't find a solution that allows me to instantiate my prefab in a function.


how to convert Htmlnode of HtmlAgilityPack to webbrowser HtmlElement

I was creating a application that automatically inserts data into html input tags.
I have xPath for specific tag like '/html/body/form/div/div[2]/div/div/input' and I managed to get HtmlNode with the help of HtmlAgilityPack

var documentAsIHtmlDocument3 = (mshtml.IHTMLDocument3)webBrowser.Document.DomDocument;
StringReader sr = new StringReader(documentAsIHtmlDocument3.documentElement.outerHTML);
htmlDocument.Load(sr);
    if (htmlDocument.DocumentNode != null)
    {
        HtmlNode currentNode = htmlDocument.DocumentNode.SelectSingleNode(xPath);
    }

Now i need to somehow select HtmlElement from Webbrowser.Document which corresponds to current HtmlNode . Can somebody help me with that?

BTW: I am not creating any spamming bot.

Hi everyone again. I found solution with recursion, lots of if statements and no htmlagilitypack, but unfortunately i can't post it right now. It seems that i don't have enough reputation.

Still, if it doesn't make too much effort, can you please tell me how to solve this problem with htmlagilitypack, because my code seems really nasty.


ui-router: trying to reload page with no params

I'm encountering a reload problem with ui-router.

My navbar links to a submitForm page:

<a ui-sref=".submitForm">

submitForm can also take parameters, if someone is trying to edit a previously created form.  The navbar should always link to a no parameters version.

However, if I'm on a version with parameters, then the navbar just reloads the page with the same parameters.

Any idea why or how I can fix this? Thanks!


PHP image and link convertor function

i am relatively new to PHP and i need a function that converts all URLs to clickable links and any URL that has an image extension (i.e. jpg, png, gif) to an image.

So what i have so far is

    function linkandimage($str) {
     $return = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', $str);
   return $return;
    }

This works find with links, but i haven't gotten a solution for images. Any help would be great,

thanks


JSF checkbox value not sent to bean

While the view can get all values from the bean, when a checkbox (h:selectBooleanCheckbox) is toggled the bean is not updated. The setSelected() method in Item is never called from the view.

I've tried changing the scope of the bean to application, using a map instead of a value for the selected property and a foolish attempt at writing my own ajax javascript function.

The application I'm working with is a bit legacy so I'm using Tomcat 6, JSF 1.2 and Richfaces 3.3.3.Final.

It seems like it should be simple, I think I'm missing something obvious, but I've been at this for two days and can't figure out why the bean isn't updated.

My view is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:c="http://java.sun.com/jstl/core"
    xmlns:fn="http://java.sun.com/jsp/jstl/functions"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich">
<head>
<title>JSF</title>
</head>
    <body>
        <h:form id="tableForm">
            <rich:dataTable id="table" value="#{managedBean}" var="item" width="100%">
                <rich:column label="Select" align="center" width="40px" >
                    <f:facet name="header">
                        <h:outputText value="Select" />
                    </f:facet>
                    <h:selectBooleanCheckbox value="#{item.selected}" >
                        <a4j:support execute="@this" event="onclick" ajaxSingle="true"/>
                    </h:selectBooleanCheckbox>
                </rich:column>
                <rich:column label="Name" align="center" width="40px">
                    <f:facet name="header">
                        <h:outputText value="Name" />
                    </f:facet>
                    <h:outputText value="#{item.name}" />
                </rich:column>
            </rich:dataTable>
        </h:form>
    </body>
</html>

I have a managed bean ItemBean in session scope:

import org.richfaces.model.ExtendedTableDataModel;
public class ItemBean extends ExtendedTableDataModel<Item>{
    public ItemBean() {super(new ItemProvider());}
}

ItemProvider is:

import org.richfaces.model.DataProvider;

public class ItemProvider implements DataProvider<Item>{

    private List<Item> items = new ArrayList<Item>();

    public ItemProvider(){
        for(int i = 0; i < 10; i++){
            items.add(new Item(i, "Item "+i));
        }
    }

    public Item getItemByKey(Object key) {return items.get((Integer)key);}

    public List<Item> getItemsByRange(int fromIndex, int toIndex) {
        return new ArrayList<Item>(items.subList(fromIndex, toIndex));
    }

    public Object getKey(Item arg0) {return arg0.getId();}

    public int getRowCount() {return items.size();}
}

and Items are:

public class Item {
    private final int id;
    private final String name;
    private boolean selected;

    public Item(int id, String name) {
        this.id = id;
        this.name = name;
        selected = false;
    }

    public int getId(){
        return id;
    }

    public String getName(){
        return name;
    }

    public boolean isSelected(){
        return selected;
    }

    public void setSelected(boolean selected){
        this.selected = selected;
    }
}


How to read the content of the text file and keep adding the output to another string in different iteration

This is my code :

File file = new File(ReadTextFile.class.getClassLoader().getResource("file/Url.txt").getFile());
Scanner in = new Scanner(file);

if (file.exists()) {
    while (in.hasNext()) {//in.hasNext()
          postFixString = in.next();
    }
}
in.close();
String newFormedUrl = url + postFixString;
return newFormedUrl;

The file contents are:

hello
goodbye

Question: I have to modify the above code so that the contents of the file are read one line at a time . How to achieve that?

EDIT: The contents of the file are not to be concatenated toghter. The method have to read one line at a time ,return that and then the content has to get appeneded to another string.

eg:
file content are:

/hello
/goodbye

1.first time the program run ,return /hello, which gets appended to another
  string and is displayed to the user.
2.If user select "ok"
3.Go back to #1 and display the next string which is  /goodbye.
4. Keep iterating till the end of file.


Is MongoDB conditional aggregation available in Meteor 1.4.x ?

I'm trying to publish certain fields to a page based on a parameter of a document in a mongo collection.  This is from the MongoDB manual: https://docs.mongodb.com/manual/reference/operator/aggregation/cond/

Does Meteor support conditional aggregation?

    return Cases.find({
            subscribers: { $in: [this.userId] }
            }, {
            fields: { $cond: [ { $eq: ['classified', true] } , Cases.privateFields, Cases.publicFields ] }
        });


Proper way to update a value when a object of another model is saved

I'd like to update the value of balance of people that are involved in a transaction (creditor and debitors) as soon as I save the transaction (from admin). Here's my models:

#models.py
class Person(models.Model):
    first_name = models.CharField(max_length = 30)
    last_name = models.CharField(max_length = 30)
    phone_number = models.CharField(max_length = 30)
    email = models.EmailField('e-mail')
    balance = models.DecimalField(max_digits = 5, decimal_places = 2)

class Transaction(models.Model):
    creditor = models.ForeignKey(Person,related_name = 'creditor')
    debtors = models.ManyToManyField(Person, related_name = 'debtors')
    value = models.DecimalField(max_digits = 5, decimal_places = 2)
    split = models.BooleanField()
    date = models.DateField()

Here's what I thought about, but I only works when the transaction is beeing changed (does not work for the first time save):

#admin.py
class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name','last_name','balance')

class TransactionAdmin(admin.ModelAdmin):
    list_display = ('creditor','value','date')
    list_filter = ('date',)
    date_hierarchy = 'date'
    ordering = ('-date',)
    filter_horizontal = ('debtors',)

    def save_model(self,request,obj,form,change):
            obj.save()
            if obj.split:
                    split_value = obj.value/(obj.debtors.all().count()+1)
                    for debtor in obj.debtors.all():
                            p = Person.objects.get(id = debtor.id)
                            p.balance = p.balance - split_value
                            p.save()
                    p = Person.objects.get(id = obj.creditor.id)
                    p.balance = p.balance + (obj.debtors.all().count())*split_value
                    p.save()

admin.site.register(Person,PersonAdmin)
admin.site.register(Transaction,TransactionAdmin)

I'm new to Django and really confused about the proper way of doing this. I'd appreciate any help on this.


How to develop a custom shipping module for a new carrier in Netsuite?

I'm interested in developing a custom plugin for a new carrier.  I see Netsuite offers UPS, FedEx, USPS, Endecia, etc. I found this page on Netsuite (http://www.netsuite.com/portal/developers/dev-resources.shtml) but it's not very clear how a developer like me can go about developing this.  Does Netsuite even let outside developers create their own shipping modules? I'm interested in developing my own tax module as well one day.


Is there a multilingual temporal expression tagger that can run on Hadoop?

I need to extract dates from lots of text. The more languages the better; English,Spanish, and Portuguese at a minimum. Does such a tool exist? In Java and Mavenized? Here's what I've found:

http://code.google.com/p/heideltime/ many languages and an impressive online demo, but requires some odd external dependencies that I suspect will make cluster deployment hard/impossible

http://nlp.stanford.edu/software/sutime.shtml Well documented, but English only. Easy to train?

http://natty.joestelmach.com/ English only

https://github.com/samtingleff/jchronic English only

http://code.google.com/p/nltk/source/browse/trunk/nltk_contrib/nltk_contrib/timex.py English only

Where else should I look?


Is there a way to get superscripts to show up in highchart exports

I'm using the sup tag in various places on a Highcharts chart, however I noticed that the superscripts do not display at all when performing an export to any of the supported formats.

Here's a fiddle that shows the problem:
http://jsfiddle.net/u7gqgybj/1/

It displays as expected when viewing the page, but when you export to say "PNG" the superscript goes away.

The word "true" in the title should be superscript.

In addition to I've tried a CSS approach and that also doesn't display correctly upon export

<span style="vertical-align:super;font-size:0.83em;">foo</span>

Any insight would be appreciated.


I get null values while adding on the same index of an array

Hey i was trying to recognize numbers from a string and convert them into a String array, but with this code what i get is:

IE:    [null1, null2, exc..]

I dont know how to take out this null value.

I also would like to find a way to do this, without an array, because i should increase its length manually.

Any tips? Thanks!

public class ProvaToArray {
    public static void main(String[] x) {
        String s = "1-2-3-4-lorem23ip567um1";
        String[] ris = toArray(s);
        System.out.println(Arrays.toString(ris)); //should printout  [1, 2, 3, 4, 23, 567, 1]
    }

    public static String[] toArray(String s){
        String[] l = new String[10];
        int count = 0;
        for(int i = 0; i < s.length() - 1; i++){
            if(estNumber(s.charAt(i) + "")){
                l[count] += "" + s.charAt(i);
                if(!estNumber(s.charAt(i+1) + "")){
                    count++;
                }
            }
            if(i+1 == s.length()-1){
                if(estNumber(s.charAt(i+1) + "")){
                    l[count] = "" + s.charAt(i+1);
                }
            }
        }
        return l;
    }

    public static boolean estNumber(String i){
        if(i.matches("^-?\\d+$"))
            return true;
        else
            return false;
    }
}


MVC4 Razor : HTTPPost and Dictionary

I'm trying to send via httppost a model that contains a dictionnary but that disctionnary is always null...
Here is my model :

public class RoomListModel
    {
        public Dictionary<PersonModel, List<LocationModel>> list { get; set; }
        public String mess { get; set; }
        public RoomListModel(Dictionary<PersonModel, List<LocationModel>> list, String mess)
        {
            this.mess = mess;
            this.list = list;
        }

        public RoomListModel()
        {
        }
    }

In a first view, that kind of model is correctly filled and displayed (i've done some tests). Then I try to send it filled from a view to my controller. Here is my view :

@for (int i = 0; i < Model.list.Count(); i++) {
                <tr>
                    <td>
                        @Html.EditorFor(m => m.list.ElementAt(i).Key.isSelected)
                    </td>
                    <td>
                        @Html.DisplayFor(m => m.list.ElementAt(i).Key.login)
                        @Html.HiddenFor(m => m.list.ElementAt(i).Key.login)
                    </td>
                    <td>
                        @Html.DisplayFor(m => m.list.ElementAt(i).Key.role)
                        @Html.HiddenFor(m => m.list.ElementAt(i).Key.role)
                    </td>
                    <td>
                        @for (int j = 0; j < Model.list.ElementAt(i).Value.Count(); j++)
                        {
                            @Html.EditorFor( m => m.list.ElementAt(i).Value.ElementAt(j).isSelected )
                            @Html.DisplayFor( m => m.list.ElementAt(i).Value.ElementAt(j).id )
                            @Html.HiddenFor( m => m.list.ElementAt(i).Value.ElementAt(j).id )
                            @Html.HiddenFor( m => m.list.ElementAt(i).Value.ElementAt(j).name)<br />
                        }
                    </td>
                </tr>
            }

But when that form is send, i've got a nullReferenceException :

[HttpPost]
        public ActionResult CreateInventory(RoomListModel mod)
        {
            int nbPer = 0;
            foreach (var per in mod.list)
            {
                if (per.Key.isSelected)
                {
                    nbPer++;
                }
            }
            if (nbPer == 0)
            { ...

On mod.list.

Could you please tell me what's wrong with my code ? Is it because of the Dictionnary object ? Thanks !


How to monitor Tuxedo via mib

Currently I am tring to write a program to monitor Tuxedo. from the official documents, I found MIB is suitable for writting program to monitor it. I have read a quite lot of document of here http://docs.oracle.com/cd/E13203_01/tuxedo/tux90/rf5/rf5.htm#998207. Although there are so many instructions of very class, there is no any guide to tell me how to use it from the beginning. I have tried to search on github however unfortuanately there is no any code relating to tuxedo mib. Does any one have some good sample code?

Thanks a lot.


Qt : Write in file

I'm learning how QT is working. I have this little code :

QApplication app(argc, argv);
QWidget fenetre;
fenetre.setFixedWidth(400);
fenetre.setFixedHeight(400);

QPushButton *bouton = new QPushButton("Quit", &fenetre);
bouton->setFixedHeight(50);
bouton->setFixedWidth(100);
bouton->move(170,310);

QLabel *label = new QLabel("Something", &fenetre);
label->move(30,200);
QLineEdit *line = new QLineEdit(&fenetre);
line->move(200,200);

QWidget::connect(bouton, SIGNAL(clicked()),qApp, SLOT(quit()));

fenetre.show();

I'm wondering how could I put the content of QLineEdit label in a file (.txt) continuously.
The goal is to keep what the user put in the QLineEdit box in a text file when the program is finished.

Thanks


Connect to Cloud Bigtable from Google App Engine

It appears that I cannot create a connection from Java class running on AppEngine.

I use the following library/dependency:

<dependency>
   <groupId>com.google.cloud.bigtable</groupId>
   <artifactId>bigtable-hbase-1.1</artifactId>
   <version>0.1.9</version>
</dependency>

And the following lines of code:

import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.*;
Configuration conf = HBaseConfiguration.create();
connection  = ConnectionFactory.createConnection(conf);

It appears that the ConnectionFactory.createConnection() method tries to use a restricted class.

Could you help us in explaining how we can use this on GAE?

I get the following error when running locally on devserver:

 Caused by: java.lang.NoClassDefFoundError: java.lang.management.ManagementFactory is a restricted class. Please see the Google  App Engine developer's guide for more details.
    at     com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:52)
        at org.apache.hadoop.util.ReflectionUtils.<clinit>(ReflectionUtils.java:137)
        at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:191)
    at com.google.appengine.tools.development.agent.runtime.RuntimeHelper.checkRestricted(RuntimeHelper.java:70)
    at com.google.appengine.tools.development.agent.runtime.Runtime.checkRestricted(Runtime.java:65)
    at org.apache.hadoop.hbase.security.UserProvider.instantiate(UserProvider.java:45)
    at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:214)
    at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:119)
    at org.energyworx.datastore.BigTableTSStorage.<init>(BigTableTSStorage.java:104)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at java.lang.Class.newInstance(Class.java:379)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:373)
    ... 71 more


Module within imported package is not visible until explicitly imported

I have a problem I have come across a few times with various packages. I import the package as a whole and try to access a module, but it is apparently not there. However once I explicitly import it separately, it's available back in my original imported namespace. What's happening here?

Example below:

import email
print(email.policy)
AttributeError: 'module' object has no attribute 'policy'

from email import policy
print(email.policy)
<module 'email.policy' from 'C:\\Anaconda3\\lib\\email\\policy.py'>


First- and last-child in bootstrap/sass not working

I am having trouble using the first- and last-child pseudo classes in my Bootstrap/Sass code. Basically, I am looking to create a whole bunch of blank space above/below the first and last header only. Compass is running, and it's not giving me an error, but when I hard refresh my page in the browser nothing changes. Here is my code, CSS first:

$headings-small-color: black;

@import "bootstrap-compass";
@import "bootstrap-variables";
@import "bootstrap";

h1 {
  font-family: 'Almendra SC', serif;
}

h1:first-child, h1:last-child {
  margin-top: 200 px;
}

small {
  font-family: 'Fanwood text', serif;

}

<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Cat Graveyard</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="stylesheets/styles.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Fanwood+Text|Almendra+SC' rel='stylesheet' type='text/css'>
  </head>

  <body>

    <img src="Cat_graveyard_cover2.jpg" class="img-responsive" alt="Cover image">

    <div class="container-fluid">
      <div class="row">
        <div class="col-sm-8 col-md-offset-2">
          <h1>Here Lieth <small>the poor victims of two notorious whiskered criminals.</small></h1>
          <h1>Warning: <small>Graphic images of mangled inanimate objects below.</small></h1>
          <h1>Viewer Discretion <small> is advised for sensitive stuffed animals.</small></h1>
        </div>
      </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
  </body>

</html>

I do realize that the more appropriate "Sassy" way would be to use a variable for these pseudo classes (and if you would like to give me an example, that'd be okay with me!), but right now my goal is just to get it to work.

I'm assuming my issue has to do with specificity re: Bootstrap. I'm at a loss of how to fix this, however. In the CSS generated by Compass, the CSS I wrote for the pseudo classes appear last. But, when I "inspect element" in the browser it shows the bootstrap CSS overriding the CSS I wrote.

IDK what to do at this point, any insight would be greatly appreciated!


randomize observations by groups (blocks)

I have a data frame with I obsevations, and each observation belongs to one of g categories.

set.seed(9782)
I <- 500
g <- 10
library(dplyr)

anon_id <- function(n = 1, lenght = 12) {
  randomString <- c(1:n)
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, letters, LETTERS),
                                    lenght, replace = TRUE),
                             collapse = "")
  }
  return(randomString)
}

df <- data.frame(id = anon_id(n = I, lenght = 16),
                 group = sample(1:g, I, T))

I want to randomly assign each observation to one of J "urns", given some vector of probabilities p. That is the probability of being assign to urn J=1 is p[1]. The added complexity is that I want to do this block by block.

If I ignore the blocks, I can do this easily:

J <- 3
p <- c(0.25, 0.5, 0.25)
df1 <- df %>% mutate(urn = sample(x = c(1:J), size = I, replace = T, prob = p))

I thought about this method to do it by "block"

# Block randomization
randomize_block <- function(g) {
  df1 <- df %>% filter(group==g)
  size <- nrow(df1)
  df1 <- df1 %>% mutate(urn = sample(x = c(1:J),
                                     size = size,
                                     replace = T,
                                     prob = p))
  return(df1)

}

df2 <- lapply(1:g, randomize_block)
df2 <- data.table::rbindlist(df2)

Is there a better way?