vendredi 11 septembre 2015

Is Prototype an anti pattern?

When Joshua Bloch mentions that Cloneable interface is broken in Java, why is the Prototype pattern, which uses clone() method to facilitate object creation, not considered an anti-pattern in Java development?

"It's a shame that Cloneable is broken, but it happens." - Joshua Bloch



via Chebli Mohamed

How to find the time an attribute was added to a version in Clearcase

I'm trying to figure out how long on average I take to review files at work. The way our review system works, someone checks a new version in and applies a Reviewer attribute to the file with the name of the reviewer. Then after the reviewer finishes the review, they apply an Approved attribute with the value "yes" or "no".

So to find the time it takes for me to review something, I need to find the difference in creation time of the two attributes. Is there a way to find these creation times in clearcase?

I can definitely get the time the version itself was created using cleartool describe, but I didn't see a way to do it for the attributes.



via Chebli Mohamed

Close CSS dropdown menu onclick

I'm very new to CSS and HTML combination. I'm trying to make use of following code for dropdown menu. But when mouse is moved away from dropdown menu, it gets closed. I would like to close it onclick outside the dropdown menu. Can anyone suggest me a fix in CSS to achieve this? JSFiddle for me code is at following location Fiddle link. Your help will be much appreciated. HTML looks like this.

<div id="main">
<div class="wrapper">
    <div class="content">
        <content>
            <div>
                <ul> 
                     <a href="#"><li>Lorem ipsum dolor</li></a>
                     <a href="#"><li>Consectetur adipisicing</li></a>
                     <a href="#"><li>Reprehenderit</li></a>
                     <a href="#"><li>Commodo consequat</li></a>

                </ul>
            </div>
        </content>
    </div>
    <div class="parent">Drop Down Parent 1</div>            
</div>

And CSS looks like this

#main {
margin: 30px 0 50px 0;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
}
#main .wrapper {
display: inline-block;
width: 180px;
margin: 0 10px 0 0;
height: 20px;
position: relative;
}
#main .parent {
height: 100%;
width: 100%;
display: block;
cursor: pointer;
line-height: 30px;
height: 30px;
border-radius: 5px;
background: #F9F9F9;
border: 1px solid #AAA;
border-bottom: 1px solid #777;
color: #282D31;
font-weight: bold;
z-index: 2;
position: relative;
-webkit-transition: border-radius .1s linear, background .1s linear, z-index 0s linear;
-webkit-transition-delay: .8s;
text-align: center;
}
#main .parent:hover, #main .content:hover ~ .parent {
background: #fff;
-webkit-transition-delay: 0s, 0s, 0s;
}
#main .content:hover ~ .parent {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
z-index: 2;
}
#main .content {
position: absolute;
top: 0;
display: active;
z-index: 2;
height: 0;
width: 180px;
padding-top: 30px;
-webkit-transition: height .5s ease;
-webkit-transition-delay: .4s;
border: 1px solid #777;
border-radius: 5px;
box-shadow: 0 1px 2px rgba(0, 0, 0, .4);
}
#main .wrapper:active .content {
height: 123px;
z-index: 3;
-webkit-transition-delay: 0s;
}
#main .content div {
background: #fff;
margin: 0;
padding: 0;
overflow: hidden;
height: 100%;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
#main .content:hover {
height: 123px;
z-index: 3;
-webkit-transition-delay: 0s;
}



via Chebli Mohamed

ng-options to work with response from promise

I am receiving a promise like so.

var GetAgentsPromise = LeadsServiceTest.GetAgents($http);
        GetAgentsPromise.then(function(response) {
            $scope.ClientAgents.id =  response.data.d.AgentIDs;
            $scope.ClientAgents.name = response.data.d.FullNames;
            console.log($scope.ClientAgents);             
        });

My select looks like so

 <select ng-model="ClientAgents">
                        <option ng-repeat="ClientAgent in ClientAgents" value="ClientAgent.id" id="SortTypeSelect" class="form-control ng-pristine ng-valid ng-touched" style="width: 70%;">{{ClientAgent.name}}</option>
                    </select>

What am I doing wrong and why ?

My response is returning the correct data.



via Chebli Mohamed

SAS - how to find variable name in string which is similar to a specified sub-string

I want to find if a variable exisits in a string (&fixed) and if so, which word number.

%LET fixed = %STR(variable1 region1 variable3);

%IF %INDEX(&fixed, regio) %THEN
  %DO;
    %LET regioxc = %SCAN(&fixed, %SYSFUNC(FIND(&fixed, regio)));
  %END;

I want to create a macro variable called regioxc, which could be equal to either region1 one time, and the next time the macro is run it could be equal to regiodc, or something else (always with the beginning string 'regio'), if that is the region variable specified within the &fixed string. This only works if the regio variable is specified first within the &fixed string, but in this case it is the second variable, so this does not work. I cannot find a robust method of creating the variable (word) count value from the &fixed string to be able to use the scan function. I know it should be 2, in this case. Any help here would be much appreciaited.



via Chebli Mohamed

Why String.Prototype replace doesn't work inside nested functions?

I have declared in same script file the following sub-string replace function :

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index + character.length);
}

If I use this function in the main script file (for example right after its declaration), it works properly with string output.

If I use this function inside nested functions, more exactly I have a function inside another function and I call "replaceAt" inside the second function, it doesn't work and it truncates all characters after the "index" specified in "replaceAt". I also specify that this is a content script in a Chrome extension.

Example (works okay outside functions, in main file) :

var h = '000000';
h = h.replaceAt(3, "1");
console.log(h);

Example (truncates everything after "index") :

function do_lut() {
    function nfu_change(e, i) {
        if (e.checked) {
            if (temp != null) {
                console.log(i + " - " + temp);
                temp = temp.replaceAt(i, "1");
            } else {
                temp = '000000000000000'.replaceAt(i, "1");
            }
        }
    }
}

Temp is just a string variable declared as empty global. Also, the above is not the full statement with event passing etc, just for exemplification.



via Chebli Mohamed

Angularjs Service does not work

I define a Service to share a variable between two controllers, but when i set the variable in a controller and then get this from another controller it does not get the correct value , this is the service:

 App.service("ProductService", function () {
    var productTotalCount = {};
    return {
        getproductTotalCount: function () {
            return productTotalCount;
        },

        setproductTotalCount: function (value) {
            productTotalCount = value;
        }
    }
});

and this is the controller which i set productTotalCount:

 App.controller("ProductController", function ($scope, $http, $rootScope, ProductService) {
    $scope.GetAllProducts = $http.get("GetAllProductsInformation").success(function (data) {

        $rootScope.Products = data.Data;
        ProductService.setproductTotalCount(data.TotalCount); // i set productTotalCount here and it's value became 19
    });
    $scope.editProduct = function (data) {

        $scope.model = data;
        $rootScope.$broadcast('modalFire', data)
    }
});

and when i get the productTotalCount in this controller it return object instead of 19 :

 App.controller('Pagination', function ($scope, ProductService) {
    debugger;
    $scope.totalItems = ProductService.getproductTotalCount(); // it should return 19 but return object!!
    $scope.currentPage = 1;
    $scope.itemPerPage = 8;
});

what is the problem?



via Chebli Mohamed

Difficulty in getting the matrix of red, green,blue

 a = imread('Sample1.jpg');
 imshow(a)

This gives me the image but my problem is stated as below

It happens that I have an image in RGB format then how to get 3 different matrix of red ,green,blue respectively in Mat lab , I have also searched the documentation but can't get satisfactory reply , I also want to store this values.



via Chebli Mohamed

Return the row of first non-blank cell

Let's say I have the array A1:A5 in excel:

    A  
1    
2  
3  'test'  
4  
5  'test2'

How can I return "3"? I'm looking for something in Excel formulas. The blanks are genuine blanks.



via Chebli Mohamed

How do I track when multiple objects touch in MATLAB?

I have x,y pixel coordinates of multiple objects that have been tracked from an image (3744x5616). The coordinates are stored in a structure called objects, e.g.

objects(1).centre = [1868 1236]

The objects are each uniquely identified by a numerical code, e.g.

objects(i).code = 33

I want to be able to record each time any two objects come within a radius of 300 pixels each other. What would be the best way to check through if any objects are touching and then record the identity of both objects involved in the interaction, like object 33 interacts with object 34.

Thanks!



via Chebli Mohamed

How to compute for the mean and sd

I need help on 4b please

  1. ‘Warpbreaks’ is a built-in dataset in R. Load it using the function data(warpbreaks). It consists of the number of warp breaks per loom, where a loom corresponds to a fixed length of yarn. It has three variables namely, breaks, wool, and tension.

    b. For the ‘AM.warpbreaks’ dataset, compute for the mean and the standard deviation of the breaks variable for those observations with breaks value not exceeding 30.

    data(warpbreaks)
    warpbreaks <- data.frame(warpbreaks)
    AM.warpbreaks <- subset(warpbreaks, wool=="A" & tension=="M")
    
    mean(AM.warpbreaks<=30)
    sd(AM.warpbreaks<=30)
    
    

This is what I understood this problem and typed the code as in the last two lines. However, I wasn't able to run the last two lines while the first 3 lines ran successfully. Can anybody tell me what is the error here? Thanks! :)



via Chebli Mohamed

data frame or matrix of quantiles

I used following code to get the quantiles (25 %, 50 %,75 % and 99 %) of x and replicate 100 times.

x<-c(1,2,3,5,4,5,6,7,8,5,4,3,2)
sample.boot=numeric()

for (i in 1:100){
       sample.boot[i]<-quantile(sample(x,replace = T),c(0.25,0.50,0.75,0.99))
}
sample.boot

This is not giving desired output. I want all four quantiles replicated 100 times and stored as data frame or in a matrix as below.

4 5 5 7
2 4 6 7
.......
.......
3 5 5 6



via Chebli Mohamed

Cordova Android Classification as Malware

I made a Cordova App with Version 5.2.0 A friend of me send me a Picture that states (freely translated from German):

AVG AntiVirus FREE Alert

App is classified as Malware. Click on Deinstallation to remove the App

Does anybody know where this comes from? Of course I implemented no Malware. Google only gave me this article and it is up to Cordova 4.0.1 Any ideas how to fix this?



via Chebli Mohamed

Removing duplicates within a cell

I can't find a way to remove duplicate values inside a same cell in Excel. For example, in A1, I have:

DOG DOG DOG

I want to have only DOG.

Actual code:

Sub test()
for i = 14 to 16
  transNumb= commRead(i, 23, 4)
next

If transNumb <> "    " and transNumb <> "F PA" then
        transNumbAcum = transNumbAcum + " " + transNumb
End if

Set exlTest = objExcel.Workbooks.Open(strPathExc)
objExcel.Application.Visible = True
exlTest.Sheets("ACCOUNT_CODE Day").Activate 
exlTest.Sheets("ACCOUNT_CODE Day").Cells(37, 4).Value = +transNumbAcum
exlTest.Close xlSaveChanges

objExcel.Quit
End sub

Code output: This will result certain values in the Excel cell (37, 4), such as:

2000 3000 0300 0300 2000

I am lost as to how to delete the repeated values in the cell.

EDIT:

I have these values in my cell A46: 2000 3000 4000 5000 3000 2000

Code I'm trying (doesn't seem to work)

Set d = CreateObject("Scripting.Dictionary")
            a = Split(objExcel.Sheets("ACCOUNT_CODE Day").Range("A46"), " ")

            For i = 0 To UBound(a)
            If Not d.Exists(a(i)) Then d.Add a(i), ""
            Next

            'Now your Dictionary should have unique values from your cell and you can recombine them:
            Set exlTest = objExcel.Workbooks.Open(strPathExc)
            objExcel.Application.Visible = True
            exlTest.Sheets("ACCOUNT_CODE Day").Activate 
            'exlTest.Sheets("ACCOUNT_CODE Day").Cells(37, 4).Value = +transNumbAcum
            'exlTest.Close xlSaveChanges
            'objExcel.Quit  

            objExcel.Sheets("ACCOUNT_CODE Day").Range("A46") = Join(d.Keys, " ")
            exlTest.Close xlSaveChanges



via Chebli Mohamed

Why DependencyProperty.UnsetValue is being passed into Equals()

I'm developing a simple WPF application. Currently, the application only manages a list of video games in a ComboBox. The game list is serialized to/from an XML file.

The feature that is currently broken is the ability to select a game from the ComboBox which makes it the "active" game to be managed. The active game will be stored as an application setting. To achieve this, I'm using two-way databinding and binding the SelectedItem in the ComboBox to the SelectedGame in the ViewModel.

When I run the application and select an item from the ComboBox, I get a null reference exception on the Game.Equals(Game other) method. While debugging, I saw that DependencyProperty.UnsetValue is being passed as the argument to the overriden Game.Equals(object obj) method which causes obj as Game to make obj null.

I don't understand why Equals is being called in the first place when all I'm doing is selecting an item from the ComboBox value, so I'm guessing it's something native to WPF. The code doesn't seem to hit any other breakpoints before heading to the Equals method, so I'm not even sure how to debug the issue. I also don't understand where DependencyProperty.UnsetValue is coming from. I'm just utterly lost here and would appreciate any insight, including how I can debug this further.

EDIT: As Glen alluded to, Equals must be called by some underlying component of WPF. My solution, at least for now, was to simply add a null check to my Equals override.

Model Class

public class Game : IEntity, IEquatable<Game>
{
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("ExecutablePath")]
    public string ExecutablePath { get; set; } 

    public Game(string name, string executablePath)
    {
        Name = name;
        ExecutablePath = executablePath;
    }

    private Game() { } // Required for XML serialization.

    public bool Equals(Game other)
    {
        return Name.EqualsIgnoreCase(other.Name);
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as Game);
    }
}

ViewModel

public class GamesViewModel
{
    // The GameRepository retrieves the game collection from the XML file.
    private readonly GameRepository _gameRepository;

    public ObservableCollection<Game> Games
    {
        get { return new ObservableCollection<Game>(_gameRepository.Items); }
    }

    public Game SelectedGame
    {
        get { return Settings.Default.ActiveGame; }
        set
        {
            if (!Settings.Default.ActiveGame.Equals(value))
            {
                Settings.Default.ActiveGame = value;
                Settings.Default.Save();
            }
        }
    }

    public GamesViewModel()
    {
        _gameRepository = RepositorySingletons.GameRepository;
    }
}

View

<UserControl x:Class="ENBOrganizer.UI.Views.GamesView"
             xmlns="http://ift.tt/o66D3f"
             xmlns:x="http://ift.tt/mPTqtT"
             xmlns:mc="http://ift.tt/pzd6Lm" 
             xmlns:d="http://ift.tt/pHvyf2" 
             xmlns:local="clr-namespace:ENBOrganizer.UI.ViewModels" 
             mc:Ignorable="d" >
    <UserControl.DataContext>
        <local:GamesViewModel />
    </UserControl.DataContext>
    <Grid>
        <ComboBox Name="GamesComboBox" ItemsSource="{Binding Games}" SelectedItem="{Binding SelectedGame}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                        <TextBlock Text="{Binding Name}" VerticalAlignment="Center" Padding="5,0,0,0" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</UserControl>



via Chebli Mohamed

How to prevent web service from starting if install condition not met on WebSphere Application Server?

We have a web service running on WebSphere Application Server.

When certain critical properties are missing, we want to prevent the EAR containing the web service from starting outright thus preventing more esoteric and complicated errors downstream.

What is the best way to achieve that? We tried throwing runtime errors, they log well, but that does not prevent the application from starting.

Thank you in advance for any help, Bertrand



via Chebli Mohamed

Dynamics CRM 2015 - update Opportunity Owner id via javascript

I'm trying to update the OwnerId on an opportunity in Dynamics CRM 2015.

So far I am using the following code but my changes are not taking effect.

Xrm.Page.data.entity.attributes.get('ownerid').setValue('487ecd0c-d8c1-e411-80eb-c4346bade4b0')
Xrm.Page.data.entity.save();

This is a view of the GetValue call.

enter image description here

The attribute type is "lookup" and when I call getIsDirty(), it returns false after I do setValue, so I'm not sure if that's the correct way to set the value on a "lookup" type.



via Chebli Mohamed

Bash readline history previous line before history expansion

There are usually the keys Up and Ctrl+P mapped to previous-history Readline command in Bash which moves back in history to previous line with history expanded.

How to move to the previous line before History expansion? E.g. to line like

!!:gs/20010910/20010911/



via Chebli Mohamed

Should I use sync or blocking channels?

I have several go routines and I use unbuffered channels as sync mechanism. I'm wondering if there is anything wrong in this(e.g. compared with a WaitGroup implementation). A known "drawback" that I'm aware of is that two go routines may stay blocked until the 3rd(last) one completes because the channel is no buffered but I don't know the internals/what this really means.

func main() {
    chan1, chan2, chan3 := make(chan bool), make(chan bool), make(chan bool)
    go fn(chan1)
    go fn(chan2)
    go fn(chan3)
    res1, res2, res3 := <-chan1, <-chan2, <-chan3
}



via Chebli Mohamed

Polymer 1.0: google-signin sign in still success when user revoke permissions

I am using a google-signin element to have access to user's access scopes. I found, if I as a user authorize the my app with certain scopes, then revoke those scopes without clicking on "Sign out" button (basically the google-signin element), the google-sign is result as onSigninSuccess event even without the authorization.

This is weird. It should be onSigninFailure because the app doesn't have the corresponding scopes of authorizations from the user.



via Chebli Mohamed

Printing numbers

I am writing a program to display as below

when n=3
1 2 3
7 8 9
4 5 6

when n=5
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10

my program is

#include<stdio.h>
#include<conio.h>
int main()
{
    int n=5,r=1,c=1,i=1,mid=0;
    if(n%2==0)
      mid=(n/2);
    else 
      mid=(n/2)+1;
      printf("mid = %d\n",mid);
    while(r<=n)
    {
      while(c<=n)
      {
        printf("%d ",i);
        c++;
        i++;
      }
      r++;
      if(r<=mid)
       i=i+n;
      else
       i=i-(2*n);
      printf("\n");
      c=1;
    }
    getch();
    return 0;
}

when I give n=3, I am getting my expected output. but when I give n=5 I am getting as below

1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
11 12 13 14 15

Could someone please help how to achieve expected output.



via Chebli Mohamed

How to process data in object collection?

Now, in my object collection,obj:

{date:2015/9/11,name:Ann,apple:1},
{date:2015/9/12,name:Ann,apple:0},
{date:2015/9/13,name:Ann,apple:1},
{date:2015/9/11,name:Bob,apple:1},.....

and I print it out like this:

2015/9/11  Ann     1  
2015/9/12  Ann     0  
2015/9/13  Ann     1  
2015/9/11  Bob     1  
2015/9/12  Bob     1  
2015/9/13  Bob     1  

Here is my code

var index, objLen
for (index = 0, objLen = obj.length; index<objLen; ++index){
    console.log(obj[index].date +'\t'+ obj[index].name +'\t'+ result[index].apple)
}

I wish to output:

2015/9/13  Ann     2  
2015/9/13  Bob     3 

This shows how many apples Ann and Bob have eaten in this three days

I want to know how to get the output.



via Chebli Mohamed

Difference between \z and \Z and \a and \A in Perl

Hello Can you please tell me the difference between \z and \Z as well as \a and \A in Perl with a simple example ?



via Chebli Mohamed

Boost Geometry doesn't copy the attributes of my custom point class

I am attempting to use Boost Geometry with a custom vertex class that has x,y and many parameters for rendering such as texture coordinates. I registered the custom class using BOOST_GEOMETRY_REGISTER_POINT_2D and the algorithms such as union_ work but only x,y are valid. (I am a C++ veteran but have never learned generic programming.) I can demonstrate the problem when I take an instance of my vertex and use boost::geometry::append( boostPolygon, myVertex );

I can trace the append call in the debugger and I see that a default constructed instance of my vertex is being created and then the accessors of my vertex class are being called to copy the x, and y values leaving all the rest of the parameters as set in the default constructor.

What I really want is for boost::geometry::append() to behave exactly like boostPolygon.outer().push_back( myVertex); So I replaced the append call with the above push_back and it added the points to the polygon as I wanted but then when I called union_() on the polygons they lost all the members other than x and y again.

I figure that what I want is a typical use-case so it is best to ask rather than guess how to handle this. I've seen the examples of how to adapt a class but my template kung-fu isn't enough to follow along. So do I need to add more adaption or is there something simple I need to do?

Scott



via Chebli Mohamed

Java 8 stream processing not fluent

I have a problem with Java 8 streams, where the data is processed in sudden bulks, rather than when they are requested. I have a rather complex stream-flow which has to be parallelised because I use concat to merge two streams.

My issue stems from the fact that data seems to be parsed in large bulks minutes - and sometimes even hours - apart. I would expect this processing to happen as soon as the Stream reads incoming data, to spread the workload. Bulk processing seems counterintuitive in almost every way.

My input is a Spliterator of unknown size and I use a forEach as the terminal operation.



via Chebli Mohamed

Background of user control hide the controls inside of him

http://ift.tt/1NmaMtn

I Have user control i set him background, but the problem is that the background hide the controls inside of him



via Chebli Mohamed

EasyMock record phase mock as argument

Is it possibile with EasyMock during the register phase to register a method call whose arguments is a mock? E.g:

String s = 'a string';

ClassA a = createMock(ClassA.class);
ClassB b = createMock(ClassB.class);
ClassC c = createMock(ClassC.class);

expect(c.bFactoryMethod()).andReturn(b);
a.someMethod(s, b);
replayAll();

ClassToTest toTest = new ClassToTest();
toTest.wrapperMethodThatCallsSomeMethod(s);
verifyAll();

EasyMock complains about:

java.lang.IllegalStateException: missing behavior definition for the preceding method call



via Chebli Mohamed

Regex:javascript

I am trying to make regex for email my regex is:

^(?:[0-9a-zA-z.!!@#$%^&*+={}'/-]+@[a-zA-Z]{1}[a-zA-Z]+[/.][a-zA-Z]{2,4}|)$

According to this regex it should accept special characters as mentioned in rule but should not accept [ and ] but it accepting [ and ].

I want to use this regex but it should exclude [ and ].



via Chebli Mohamed

how to retrieve LogCat data after use Log.d(); statement as we get logcat information earlier

I have just used Log.d(); statement to debug my app and for this I created a filter configuration. I got it working so that it shows the feedback.

But Now I deleted this Log.d(); from my app. But I can't access the Logcat Information as I got earlier. It's not a error. I just want to get my logcat as I used before Log.d(); statement.



via Chebli Mohamed

Encountered the symbol "DECLARE" and Encountered the symbol "end-of-file"

I'm following a tutorial from Oracle, and in the last step I'm trying to execute a SQL script where I get the errors from DECLARE and end-of-file. Any idea where I went wrong? The following is the script:

create or replace
PROCEDURE ENQUEUE_TEXT(
 payload IN VARCHAR2 )
AS
 enqueue_options DBMS_AQ.enqueue_options_t;
 message_properties DBMS_AQ.message_properties_t;
 message_handle RAW (16);
 user_prop_array SYS.aq$_jms_userproparray;
 AGENT SYS.aq$_agent;
 header SYS.aq$_jms_header;
 MESSAGE SYS.aq$_jms_message;
BEGIN
 AGENT := SYS.aq$_agent ('', NULL, 0);
 AGENT.protocol := 0;
 user_prop_array := SYS.aq$_jms_userproparray ();
 header := SYS.aq$_jms_header (AGENT, '', 'aq1', '', '', '', user_prop_array);
 MESSAGE := SYS.aq$_jms_message.construct (0);
 MESSAGE.set_text (payload);
 MESSAGE.set_userid ('Userid_if_reqd');
 MESSAGE.set_string_property ('JMS_OracleDeliveryMode', 2);
 --(header, length(message_text), message_text, null);
 DBMS_AQ.enqueue (queue_name => 'userQueue', enqueue_options => enqueue_options,
message_properties => message_properties, payload => MESSAGE, msgid => message_handle );
 COMMIT;
END ENQUEUE_TEXT;
DECLARE
  PAYLOAD varchar2(200);
BEGIN
  PAYLOAD := 'Hello from AQ !';
  ENQUEUE_TEXT(PAYLOAD => PAYLOAD);
END;



via Chebli Mohamed

int or float to represent numbers that can be only integer or "#.5"

Situation

I am in a situation where I will have a lot of numbers around about 0 - 15. The vast majority are whole numbers, but very few will have decimal values. All of the ones with decimal value will be "#.5", so 1.5, 2.5, 3.5, etc. but never 1.1, 3.67, etc.

I'm torn between using float and int (with the value multiplied by 2 so the decimal is gone) to store these numbers.

Question

Because every value will be .5, can I safely use float without worrying about the wierdness that comes along with floating point numbers? Or do I need to use int? If I do use int, can every smallish number be divided by 2 to safely give the absolute correct float?

Is there a better way I am missing?

Other info

I'm not considering double because I don't need that kind of precision or range.

I'm storing these in a wrapper class, if I go with int whenever I need to get the value I am going to be returning the int cast as a float divided by 2.



via Chebli Mohamed

becomeFirstResponder does not work in cellForRowAtIndexPath

When calling textView becomeFirstResponder from cellForRowAtIndexPath returns false, why?

But from other method i.e. from didSelectRowAtIndexPath it works.

Is it in connection that I am using iOS 8 introduced UITableViewAutomaticDimension row height approach?!



via Chebli Mohamed

scrollView is nil when called from viewdidload

I want to scrolling view when navigationItem clicked. But..here is some error.

  1. I want to make snapchatlike scroll view. It works fine, but... when I call scrollView out of viewdidload function, scrollView is nil!

  2. I already make snapchat like swipe view. but I want to make swipe view when navigation Item(heart mark) clicked.

My ViewController viewdidload func - it works fine

@IBOutlet weak var scrollView: UIScrollView!


var V1 : LeftViewController = LeftViewController(nibName: "LeftViewController", bundle: nil)
var V2 : CenterViewController = CenterViewController(nibName: "CenterViewController", bundle: nil)
var V3 : RightViewController = RightViewController(nibName: "RightViewController", bundle: nil)



override func viewDidLoad() {

    super.viewDidLoad()



    self.addChildViewController(V1)
    self.scrollView.addSubview(V1.view)
    V1.didMoveToParentViewController(self)

    self.addChildViewController(V2)
    self.scrollView.addSubview(V2.view)
    V2.didMoveToParentViewController(self)

    self.addChildViewController(V3)
    self.scrollView.addSubview(V3.view)
    V3.didMoveToParentViewController(self)

    var V2Frame : CGRect = V2.view.frame
    V2Frame.origin.x = self.view.frame.width
    V2.view.frame = V2Frame


    var V3Frame : CGRect = V3.view.frame
    V3Frame.origin.x = 2 * self.view.frame.width
    V3.view.frame = V3Frame

    println(self)
    println(scrollView)
    println(V2.view.frame)

    self.scrollView.setContentOffset(CGPointMake(V2Frame.origin.x, self.view.frame.size.height), animated: false)



    self.scrollView.contentSize = CGSizeMake(self.view.frame.width * 3, self.view.frame.size.height)        }

My ViewController clickEvent func - why scrollView is nil?

    func clickEvent() {
    V2.view.frame = CGRect(x: 375.0, y: 0.0, width: 320.0, height: 568.0)
    let scrollView = UIScrollView(frame: CGRect(x: 0.0, y: 0.0, width: 320.0, height: 568.0))


    self.scrollView?.scrollRectToVisible(V2.view.frame, animated: true)

    println(self)
    println(scrollView)
    println(V2.view.frame)
    //self.scrollView.setContentOffset(CGPointMake(V2.view.frame.origin.x, self.view.frame.size.height), animated: true)
}

I call clickEvent in Viewcontroller from other CenterViewController - it can call fine but...in ViewController clickEvent functions' scrollView is nil.. How can I fix it?

func clickEvent(sender: AnyObject) {

   ViewController().clickEvent()
}



via Chebli Mohamed

How to disable a button until some text field are filled?

Using Java FX 8, I have two text fields and a button to validate. I want this button to be disabled until both fields have a valid value.

What is the best way to do this ?

Thanks,



via Chebli Mohamed

How to test application using app authenticity enabled on remote worklight server?

We are trying to test our IBM MobileFirst Platform Foundation-based mobile application with IBM Rational Test Workbench MobileTest version 8.7.

One issue we are running into is that the testing fails due to application authenticity tests failure when trying to test against a remote worklight server. We tried to test it locally and that works. However, we are wondering if turning off the app authenticity is the only way to test using a remote worklight server. If anyone knows of any setting etc to get around the issue without having to turn off app authenticity every time we test on a pre-production build ( using remote server ) please let us know. It will be a great help.



via Chebli Mohamed

Batch script for loop

I have a problem with for loop in batch script. When I try:

for /f "delims=;" %g in ('dir') do echo %g%

i see this

'dir' is not recognized as an internal or external command,
operable program or batch file.

Did I miss somethig? Why windows command doesn't work?



via Chebli Mohamed

single web page cache prevention

Is it possible to create a basic single page web page which doesn't get stored into a users browser cache?

Or

Is it possible to create a basic single page web page which deletes itself from the users browser cache?

I understand that such a page can't be fool proof because the user could simply take a screenshot to capture the data on the web page.



via Chebli Mohamed

Specifying a Range of Rows Based on Checkbox

So I have scoured the internet to put together this small macro, but I haven't had any luck figuring out what I'm doing wrong. I know the answer is going to be simple, but it certainly beyond me. The goal is to have a checkbox insert several rows from a separate sheet, then delete those same rows if you uncheck the box. The copy and insert functions are working perfectly, but I do not know how to write the line for the range of rows to delete. The Code below is obviously not correct, because rngD is specified for testing. rngD should be the 7 rows below the check box, or maybe there is a better way to do it. Thanks a lot for checking this out, and I'm open to any constructive criticism.

Working in Excel 2013

Sub Insert_LL()


Dim ws As Worksheet
Dim chkB As CheckBox
Dim rngA As Range
Dim rngD As Range
Dim lRow As Long
Dim lRowD As Long
Dim llRows As Range


Set llRows = Range("Lesson_Learned")
Set ws = ActiveSheet
Set chkB = ws.CheckBoxes(Application.Caller)
lRow = chkB.TopLeftCell.Offset(1).Row
lRowD = chkB.TopLeftCell.Offset(7).Row
Set rngA = ws.Rows(lRow)
Set rngD = ws.Rows("18:24") 'needs to specify the range of rows dependant where the checkbox is located'


Application.ScreenUpdating = False


    Select Case chkB.Value
        Case 1
            llRows.Copy
            rngA.Insert Shift:=xlDown
        Case Else
            rngD.Delete
    End Select

Application.CutCopyMode = False
Application.ScreenUpdating = True


End Sub



via Chebli Mohamed

Insert only paid account numbers into a new sheet

Very new to VBA. I need to copy all paid account numbers into Column A of the current sheet. The Accounts sheet has the account numbers in column A and in column B either "Paid" or "Unpaid". I just keep getting error after error and I'm not sure if I'm fixing it or making it worse, but the last error I couldn't get past was for the line Cells(t,1).Value =i: "Application Defined or Object Defined Error."

Sub Button1_Click()

  Dim t As Integer
  Dim i As Range

  Dim sheet As Worksheet
  Set sheet = ActiveWorkbook.Sheets("Accounts")

  Dim rng As Range
  Set rng = Worksheets("accounts").Range("A:A")

  'starting with cell A2
  target = 2
  'For each account number in Accounts
  For Each i In rng
  'find if it's paid or not
    If Application.WorksheetFunction.VLookup(i, sheet.Range("A:B"), 2, False) = "PAID" Then
      'if so, put it in the target cell
      Cells(t, 1).Value = i
      t = t + 1
    End If
  Cells(t, 1).Value = i
  t = t + 1
  Next i

End Sub



via Chebli Mohamed

Coding array with NSCoder Swift

I'm trying to implement the NSCoder, but am currently facing a stubborn issue. My goal is to save the array of strings via NSCoder to a local file and load it when the app opens next time.

Here is the class i've created, but i'm not sure how i should handle the init and encoder functions:

class MyObject: NSObject, NSCoding {

var storyPoints: [String] = []

init(storyPoints : [String]) {
    self.storePoints = storePoints
}


required init(coder decoder: NSCoder) {
    super.init()

???

}

func encodeWithCoder(coder: NSCoder) {
???
}

}

Moreover, how do i access it in my view controller? where should i declare a path for saving the NSCoder? It's not really clear enough.

Looking forward to any advices.

Thank you.



via Chebli Mohamed

Ember.js how to observe array keys changed by input

I have an object with a couple decades of settings, some settings depend on other settings, so, I need to observe if some setting changed.

import Ember from 'ember';

export default Ember.Controller.extend({
   allPermissionChanged: function () {
      alert('!');
  }.observes('hash.types.[].permissions'),
  permissionsHash: {
    orders:{
      types: [
        {
          label: 'All',
          permissions: {
            view: true,
            edit: false,
            assign: false,
            "delete": false,
            create: true
          }
        },

        }
      ],
      permissions:[
        {
          label:'Просмотр',
          code:'view'
        },
        {
          label:'Редактирование',
          code:'edit'
        },
        {
          label:'Распределение',
          code:'assign'
        },
        {
          label:'Удаление',
          code:'delete'
        },
        {
          label:'Создание',
          code:'create'
        }
      ]
    }
  }

});

Next I try to bind each setting to input

<table class="table table-bordered">
    <thead>
    <tr>

      {{#each hash.types as |type|}}
          <th colspan="2">{{type.label}}</th>
      {{/each}}
    </tr>

    </thead>
    <tbody>
    {{#each hash.permissions as |perm|}}
        <tr>
          {{#each hash.types as |type|}}
            {{#if (eq (mut (get type.permissions perm.code)) null)}}
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            {{else}}
                <td>{{perm.label}}</td>
                <td>{{input type="checkbox"  checked=(mut (get type.permissions perm.code)) }}</td>

            {{/if}}
          {{/each}}
        </tr>
    {{/each}}
    </tbody>

</table>

But observer doesn't work.

Also I prepared Jsbin example - http://ift.tt/1NmaLWj



via Chebli Mohamed

AngularJS Directive Isolated Scope Issue

I'm fairly new to AngularJS and am trying to put together a small demo application. The part I'm trying to get working is as follows:

  • User enters stock market code into text field that is two-way bound with ng-model.
  • Directive has a bind-to-click function that retrieves some data from an API.
  • Once data is returned, the directive is compiled and appended to a div.
  • The directive is supposed to accept a text variable through an isolated scope and display it. This is the part that is not working properly.

Code

Directives

financeApp.directive('watchlistItem', function () {
    return {
        restrict: 'E',
        templateUrl: 'app/directives/watchlistItem.html',
        replace: true,
        scope: {
            asxCode: "@"
        }
    }
});

financeApp.directive('myAddCodeButton', ['$compile', '$resource', function ($compile, $resource) {
    return function(scope, element, attrs){
        element.bind("click", function () {
            scope.financeAPI = $resource('http://ift.tt/1qXLaIk', {callback: "JSON_CALLBACK" }, {get: {method: "JSONP"}});
            //scope.financeResult = 
            scope.financeAPI.get({q: decodeURIComponent('select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22' + scope.asxcodeinput + '.AX%22)'),
                format: 'json', env: decodeURIComponent('store%3A%2F%2Fdatatables.org%2Falltableswithkeys')})
            .$promise.then(function (response) {
                scope.quote = response.query.results.quote;
                console.log(scope.quote);
                angular.element(document.getElementById('watchlistItemList')).append($compile("<watchlist-item asx-code=" + scope.quote.Symbol + "></watchlist-item")(scope));
            }, function (error) {
                console.log(error);
            });
        });
    };
}]);

Directive Template

<div class="watchItem">
    <a href="#/{{asxCode}}">
        <div class="watchItemText">
            <p class="asxCodeText"><strong>"{{asxCode}}"</strong></p>
            <p class="asxCodeDesc"><small></small></p>
        </div>
        <div class="watchItemQuote">
            <p class="asxPrice lead"></p>
            <p class="asxChangeUp text-success"></p>
        </div>
    </a>
</div>

HTML

<html lang="en-us" ng-app="financeApp">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta charset="UTF-8">

    <title>ASX Watchlist and Charts</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="http://ift.tt/1K1B2rp">
    <link rel="stylesheet" href="css/styles.css">

    <script src="http://ift.tt/1FBSnCz"></script>
    <script src="http://ift.tt/1NmaLWh"></script>
    <script src="http://ift.tt/1FBSkGR"></script>
    <script src="app/app.js"></script>
</head>
<body>

    <div class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#/">ASX Watchlist and Charts</a>
            </div>
        </div>
    </div>

    <div class="container-fluid" id="mainContainer">
        <div class="row">
            <div class="floatLeft" id="leftDiv" ng-controller="navController">
                <form class="inline-left">
                    <div class="form-group floatLeft">
                        <label class="sr-only" for="asxinput">ASX Code</label>
                        <input type="text" class="form-control" id="asxinput" placeholder="ASX Code" ng-model="asxcodeinput" />
                    </div>
                    <button class="btn btn-default floatRight" my-add-code-button>Add</button>
                </form>
                <div id="watchlistItemList">
                    <!-- Test item -->
                    <div class="watchItem">
                        <a href="#/AFI">
                            <div class="watchItemText">
                                <p class="asxCodeText"><strong>AFI</strong></p>
                                <p class="asxCodeDesc"><small>Australian Foundation Investments Co</small></p>
                            </div>
                            <div class="watchItemQuote">
                                <p class="asxPrice lead">$6.50</p>
                                <p class="asxChangeUp text-success">+ 5%</p>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
            <div class="floatLeft" id="rightDiv" ng-view>

            </div>
        </div>
    </div>

</body>
</html>

The directive "compiles" and is appended to the DOM element as expected, but the asxCode variable is not interpolating within the directive template.

Any suggestions greatly appreciated.



via Chebli Mohamed

Select column header and first column of a cell in datagridview when selected

I need to change the color of the Header Cell and first column called "col_row" when one or more cells are selected with the mouse like this:

enter image description here

I use this code and its working:

    Private Sub gdv_PatioAcopio_CellStateChanged(sender As Object, e As DataGridViewCellStateChangedEventArgs) Handles gdv_PatioAcopio.CellStateChanged
    If e.Cell.ColumnIndex = 0 Then
        e.Cell.Selected = False
    Else

        If e.Cell.Selected = True Then
            Me.gdv_PatioAcopio.Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColor = Color.LightBlue
            Me.gdv_PatioAcopio.Rows(e.Cell.RowIndex).Cells("col_row").Style.BackColor = Color.LightBlue
        ElseIf e.Cell.Selected = False Then
            Me.gdv_PatioAcopio.Columns(e.Cell.ColumnIndex).HeaderCell.Style.BackColor = Color.Navy
            Me.gdv_PatioAcopio.Rows(e.Cell.RowIndex).Cells("col_row").Style.BackColor = Color.Navy
        End If

    End If
End Sub

but when i deselect, for example, the third column, the first column changes its color to Color.Navy.

enter image description here

How can i prevent this?

Thanks!



via Chebli Mohamed

spring-mvc mail not working with the ZK framework

I have a problem replicating the following example on my site created with the ZK-framework: http://ift.tt/1lesONx

When submitting the form, I get:

HTTP ERROR 404

Problem accessing /backend/sendEmail.do. Reason:

Not Found

even though I've specified in my my web.xml to map .do files to the dispatcherservlet.

The relevant entries in web.xml are:

 <servlet>
    <servlet-name>SpringController</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mail.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>SpringController</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

In pom.xml:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-expression</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>3.1.2.RELEASE</version>
  <scope>compile</scope>
</dependency>

In spring-mail.xml:

<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/GAf8ZW">

<bean id="mailSender"      class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="587" />
    <property name="username" value="username" />
    <property name="password" value="password" />

    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/" />
    <property name="suffix" value=".zul" />
</bean>

<bean
    class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.Exception">Error</prop>
        </props>
    </property>
</bean>

The form .zul:

<zk xmlns:h="native">
    <window title="Recupera password">
        <h:form method="post" action="sendEmail.do">
            <grid hflex=" 1">
                <columns>
                    <column align="right" hflex="min" />
                    <column />
                </columns>
                <rows>
                    <row>
                        E-mail :
                        <hlayout>
                            <textbox id="email" cols="24" tabindex="1" />
                        </hlayout>
                    </row>
                    <row>
                        <label />
                        <button id="invia" type="submit" label="Invia" />
                    </row>
                </rows>
            </grid>
        </h:form>
    </window>
</zk>

and finally, the controller:

@Controller
@RequestMapping("/backend/sendEmail.do")
public class RecuperaPasswordController {

    @Autowired
    private JavaMailSender mailSender;

    @RequestMapping(method = RequestMethod.POST)
    public void invia(HttpServletRequest request) throws MessagingException {
    }

}

In theory everything should be in place, as far as I see, but it still gives me this error. Judging from similar posts, the problem might be that the .zul is not in the WEB-INF folder, but as far as I've understood, that folder is inaccessible, and for good reasons, since it might contain configuration files with sensitive information, so I'm kind of lost.

Otherwise, if someone knows a good way to integrate maildispatching with ZK, I'm all ears for other alternative solutions!

EDIT: As requested, the whole web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://ift.tt/qzwahU"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/qzwahU http://ift.tt/16hRdKA">

    <description><![CDATA[MyEfm]]></description>
    <display-name>MyEfm</display-name>

    <!-- //// -->
    <!-- ZK -->
    <listener>
        <description>ZK listener for session cleanup</description>
        <listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
    </listener>
    <servlet>
        <description>ZK loader for ZUML pages</description>
        <servlet-name>zkLoader</servlet-name>
        <servlet-class>org.zkoss.zk.ui.http.DHtmlLayoutServlet</servlet-class>

        <!-- Must. Specifies URI of the update engine (DHtmlUpdateServlet). It 
            must be the same as <url-pattern> for the update engine. -->
        <init-param>
            <param-name>update-uri</param-name>
            <param-value>/zkau</param-value>
        </init-param>
        <!-- Optional. Specifies whether to compress the output of the ZK loader. 
            It speeds up the transmission over slow Internet. However, if you configure 
            a filter to post-processing the output, you might have to disable it. Default: 
            true <init-param> <param-name>compress</param-name> <param-value>true</param-value> 
            </init-param> -->
        <!-- [Optional] Specifies the default log level: OFF, ERROR, WARNING, INFO, 
            DEBUG and FINER. If not specified, the system default is used. <init-param> 
            <param-name>log-level</param-name> <param-value>OFF</param-value> </init-param> -->
        <load-on-startup>1</load-on-startup><!-- Must -->
    </servlet>
    <servlet-mapping>
        <servlet-name>zkLoader</servlet-name>
        <url-pattern>*.zul</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>zkLoader</servlet-name>
        <url-pattern>*.zhtml</url-pattern>
    </servlet-mapping>
    <!-- [Optional] Uncomment it if you want to use richlets. <servlet-mapping> 
        <servlet-name>zkLoader</servlet-name> <url-pattern>/zk/*</url-pattern> </servlet-mapping> -->
    <servlet>
        <description>The asynchronous update engine for ZK</description>
        <servlet-name>auEngine</servlet-name>
        <servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>

        <!-- [Optional] Specifies whether to compress the output of the ZK loader. 
            It speeds up the transmission over slow Internet. However, if your server 
            will do the compression, you might have to disable it. Default: true <init-param> 
            <param-name>compress</param-name> <param-value>true</param-value> </init-param> -->
        <!-- [Optional] Specifies the AU extension for particular prefix. <init-param> 
            <param-name>extension0</param-name> <param-value>/upload=com.my.MyUploader</param-value> 
            </init-param> -->
    </servlet>
    <servlet-mapping>
        <servlet-name>auEngine</servlet-name>
        <url-pattern>/zkau/*</url-pattern>
    </servlet-mapping>

    <!-- [Optional] Uncomment if you want to use the ZK filter to post process 
        the HTML output generated by other technology, such as JSP and velocity. 
        <filter> <filter-name>zkFilter</filter-name> <filter-class>org.zkoss.zk.ui.http.DHtmlLayoutFilter</filter-class> 
        <init-param> <param-name>extension</param-name> <param-value>html</param-value> 
        </init-param> <init-param> <param-name>compress</param-name> <param-value>true</param-value> 
        </init-param> </filter> <filter-mapping> <filter-name>zkFilter</filter-name> 
        <url-pattern>your URI pattern</url-pattern> </filter-mapping> -->
    <!-- //// -->

    <!-- ///////////// -->
    <!-- DSP (optional) Uncomment it if you want to use DSP However, it is turned 
        on since zksandbox uses DSP to generate CSS. -->
    <servlet>
        <servlet-name>dspLoader</servlet-name>
        <servlet-class>org.zkoss.web.servlet.dsp.InterpreterServlet</servlet-class>
        <init-param>
            <param-name>class-resource</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dspLoader</servlet-name>
        <url-pattern>*.dsp</url-pattern>
    </servlet-mapping>

     <servlet>
        <servlet-name>SpringController</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mail.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

<!--     <servlet-mapping> -->
<!--         <servlet-name>SpringController</servlet-name> -->
<!--         <url-pattern>*.zul</url-pattern> -->
<!--     </servlet-mapping> -->

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!-- Less compiler ZK Less Servlet da commentare in produzione / collaudo -->

    <!-- <servlet> -->
    <!-- <servlet-name>zkLess</servlet-name> -->
    <!-- <servlet-class>org.zkoss.less.ZKLessServlet</servlet-class> -->
    <!-- <init-param> -->
    <!-- <param-name>org.zkoss.less.LessResource</param-name> -->
    <!-- specify to the folder that contains *.less -->
    <!-- <param-value>/common/less</param-value> -->
    <!-- </init-param> -->
    <!-- <init-param> -->
    <!-- <param-name>org.zkoss.less.OutputFormat</param-name> -->
    <!-- specify output file suffix, default .css.dsp -->
    <!-- <param-value>.css.dsp</param-value> -->
    <!-- </init-param> -->
    <!-- <init-param> -->
    <!-- <param-name>org.zkoss.less.CompressOutput</param-name> -->
    <!-- compress output, default true -->
    <!-- <param-value>true</param-value> -->
    <!-- </init-param> -->
    <!-- <load-on-startup>1</load-on-startup> -->
    <!-- </servlet> -->
    <!-- <servlet-mapping> -->
    <!-- <servlet-name>zkLess</servlet-name> -->
    <!-- specify to folder that contains *.less -->
    <!-- <url-pattern>/common/less/*</url-pattern> -->
    <!-- </servlet-mapping> -->

    <!-- End Less compiler -->

    <!-- /////////// -->
    <!-- [Optional] Session timeout -->
    <session-config>
        <session-timeout>60</session-timeout>
    </session-config>


    <!-- Spring configuration -->
    <!-- Initialize spring context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        /WEB-INF/applicationContext.xml
        /WEB-INF/applicationContext-security.xml
    </param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>root-pf</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <filter><!-- the filter-name must be preserved, do not change it! -->
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <filter>
        <filter-name>OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>




    <!-- [Optional] MIME mapping -->
    <mime-mapping>
        <extension>doc</extension>
        <mime-type>application/vnd.ms-word</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>gif</extension>
        <mime-type>image/gif</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>jpeg</extension>
        <mime-type>image/jpeg</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>jpg</extension>
        <mime-type>image/jpeg</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>js</extension>
        <mime-type>text/javascript</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>pdf</extension>
        <mime-type>application/pdf</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>png</extension>
        <mime-type>image/png</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>txt</extension>
        <mime-type>text/plain</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>xls</extension>
        <mime-type>application/vnd.ms-excel</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>xml</extension>
        <mime-type>text/xml</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>zhtml</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
    <mime-mapping>
        <extension>zul</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>

    <welcome-file-list>
        <welcome-file>index.zul</welcome-file>
        <welcome-file>index.zhtml</welcome-file>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
    </welcome-file-list>
</web-app>



via Chebli Mohamed

How do you get get absent rows from a SQL table?

I am not sure if I had asked the question correctly in title, but here the proper scenario.

Suppose I have SQL table in which rows are inserted everyday. In these rows there is one column which has one set of values. That means in this column, let's call it Source_system, we receive 20 values each day. Same distinct values everyday. Now is there any way I can get the name of the source system which is not inserted for that day?

EDIT: Sorry for bad English.



via Chebli Mohamed

pagination for a table contents in yii

I'm using Yii application. In that how to give pagination to a table contents( not using cgridview).

In view,

<table data-provides="rowlink" data-page-size="20" data-filter="#mailbox_search" class="table toggle-square default footable-loaded footable" id="mailbox_table">
                                <thead>
                                    <tr>

                                        <th></th>
                                        <th data-hide="phone,tablet">To</th>
                                        <th>Subject</th>
                                        <th data-hide="phone" class="footable-last-column">Date</th>
                                    </tr>
                                </thead>
                                <tbody>

                                    <?php


                                    foreach ($model as $item) {
                                        if ($item->email_status == 1)
                                            echo '<tr id="' . $item->emailid . '" class="unreaded rowlink" style="display: table-row;">';
                                        else
                                            echo '<tr id="' . $item->emailid . '" class="rowlink" style="display: table-row;">';
                                        echo '<td class="nolink footable-first-column">';
                                        echo '<span class="footable-toggle"></span>';

                                        echo '</span></td>';
                                        echo '<td>' . $item->touser->username . '</td>';
                                        echo '<td>' . $item->email_subject . '</td>';
                                        $originalDate = $item->time;
                                        $newDate = date("Y-M-d H:i:s", strtotime($originalDate));


                                        echo '<td class="footable-last-column">' . $newDate . '</td></tr>';
                                    }
                                    ?>
                                </tbody>

                            </table>

In Controller,

   public function actionOutbox() 
   {
       $criteria = new CDbCriteria;
       $criteria->order = 'time DESC';
       $model = Email::model()->findAllByAttributes(array(
              'from_userid' => Yii::app()->user->id
           ), 
           $criteria
       );

       $this->render('outbox', array(
          'model' => $model,
       ));
   }

In this code how to add pagination. I tried following different techniques but found none of them to work. Please help me.



via Chebli Mohamed

UIImagePickerController with cameraOverlayView - misplaced views

I have a UIImagePickerController with a custom cameraOverlayView.

I create the imagePicker like this:

self.overlay = [self.storyboard instantiateViewControllerWithIdentifier:@"OverlayViewController"];
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
self.picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
self.picker.showsCameraControls = NO;

// Insert the overlay
self.picker.cameraOverlayView = self.overlay.view;
self.overlay.pickerReference = self.picker;

self.picker.edgesForExtendedLayout = UIRectEdgeAll;
self.picker.extendedLayoutIncludesOpaqueBars = YES;

self.picker.delegate = self.overlay;


[self presentViewController:self.picker animated:NO completion:^{

}];

For some reason, the OverlayViewController's view is misplaced. It seems as if the constraints haven't been calculated. However, if I explicitly call [self.overlay viewWillAppear:NO]; in the completion block, they layout seems to render correctly.

After some investigation it seems as if viewWillAppear and viewDidAppear is not called for the OverlayViewController.

However, these methods are called if I come back to the imagePicker from a modal 'custom gallery viewcontroller'.

I.e: rootVC-> (No calls) -> imagePicker -> customGalleryVc customGalleryVc (dismiss modal) -> (Calls to willAppear) -> imagePicker

What is this? Am I missing something with the fundamentals of the view-hierarchy?

Thank you!



via Chebli Mohamed

In Pandoc, how do I add a newline between authors through the YAML metablock without modifying the template?

I am trying to add a a couple of authors to a report I am writing. Preferably, the second author would appear on a new line after the first. I know I can modify the template to add a new field or the multiple author example given in the Pandoc readme. However, I wonder if there is any character I can use to insert a new line between authors directly in the metablock. So far I have tried \newline, \\, | with newline and space, <br>, <div></div>, and making the author list a string with newline or double spaces between author names, but nothing has worked. My desired output is pdf.



via Chebli Mohamed

Angular $modal scope - Passing an object to $modal

I am attempting to pass angular's bootstrap modal the url of the image that was clicked in a angular masonry gallery. What I have is very close to the demo in the documentation with only a few changes. I know this is completely an issue with my own understanding of scope.

My modal HTML:

    <div class="modal-header">
        <h3 class="modal-title">I'm a modal!</h3>
    </div>
    <div class="modal-body">
        <ul>
            <li ng-repeat="item in items">
                <a href="#" ng-click="$event.preventDefault(); selected.item = item">{{ item }}</a>
            </li>
        </ul>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
        <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
    </div>

And in my Controller:

angular.module('testApp').controller('GalleryCtrl', function ($scope, $modal, $log) {
  $scope.animationsEnabled = true;
  $scope.items = ['item1', 'item2', 'item3'];
  // Temporary Generation of images to replace with about us images
  function genBrick() {
      var height = ~~(Math.random() * 500) + 100;
      var id = ~~(Math.random() * 10000);
      return {
        src: 'http://placehold.it/' + width + 'x' + height + '?' + id
      };
  };
  this.bricks = [
    genBrick(),
    genBrick(),
    genBrick(),
    genBrick(),
    genBrick(),
    genBrick()
  ];
  this.showImage = function(item){
    alert(item.src); // gives me exactly what im trying to pass to the modal
    var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'views/modal.html',
      scope: $scope,
      controller: 'GalleryCtrl',
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });

  }
});

Lastly for clarity, this is my masonry code

<div masonry>
    <div class="masonry-brick" ng-repeat="brick in gallery.bricks">
        <img ng-src="{{ brick.src }}" alt="A masonry brick" ng-click="gallery.showImage(brick)">
    </div>
</div>

Right now this works fine to return the items objects 3 values in li tags to the modal just like in the original example. What id really like to pass into the model is the (item.src) but no matter what i change it never seems to get passed in so that i can display it.



via Chebli Mohamed

JMeter: Is Windows not capable of handling a hundreds of thousands of users in single system

My linux (i5 Processor, RAM: 16GB) machine is able to handle 100k users easily however same does not happen with Windows 8 (i7 Processor 2600 @ CPU 3.40GHz, RAM: 32GB) and thread creation stops after specific amount of thread is created somewhere around 20k in JMeter.

Is there any reason as why Windows in not able to handle huge number of users?



via Chebli Mohamed

mardi 4 août 2015

Assistance with expanding a Sublime Text Plugin

I have a sublime text plugin that watches for the creation of files beginning with lp_

When a file with lp_ prefix is created the plugin creates a folder of the same name with an images folder within.

I would like to watch different areas of my site and create the relevant folder within the nearest lp folder to the created file.

For example I have the following folder strucure

Root > desktop > Root > desktop > lp

Root > Mobile > Root > Mobile > lp

Root > Tablet > Root > Tablet > lp

When a file with lp_ prefix is created in either 'device' folder I would like folder to be created within the nearest lp folder.

The plugin below is along the right lines but I am unsure as how to set rules for targeting specific folders.

import sublime, sublime_plugin, os

# We extend event listener
class ExampleCommand(sublime_plugin.EventListener):
    # This method is called every time a file is saved (not only the first time is saved)
    def on_post_save_async(self, view):
        variables = view.window().extract_variables()
        fileBaseName = variables['file_base_name'] # File name without extension
        path = '/Users/jameshusband/Dropbox/development/remote/http://ift.tt/1P3thlB' + fileBaseName
        imagepath = path + '/images/'

        if fileBaseName.startswith('lp_') and not os.path.exists(path):
            os.mkdir(path)
            os.mkdir(imagepath)

Could anyone point me in the right direction for this? I am not very experienced with Python so am unsure of the best way to achieve my goal.

Parsing XML with namespaces into a dataframe

I have the following simpplified XML:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xsd="http://ift.tt/tphNwY" xmlns:xsi="http://ift.tt/ra1lAU"
 xmlns:soap="http://ift.tt/18hkEkn"> 
    <soap:Body>
        <ReadResponse xmlns="ABCDEFG.com">
            <ReadResult>
                <Value>
                    <Alias>x1</Alias>
                    <Timestamp>2013-11-11T00:00:00</Timestamp>
                    <Val>113</Val>
                    <Duration>5000</Duration>
                    <Quality>128</Quality>
                </Value>
                <Value>
                    <Alias>x1</Alias>
                    <Timestamp>2014-11-11T00:02:00</Timestamp>
                    <Val>110</Val>
                    <Duration>5000</Duration>
                    <Quality>128</Quality>
                </Value>
                <Value>
                    <Alias>x2</Alias>
                    <Timestamp>2013-11-11T00:00:00</Timestamp>
                    <Val>101</Val>
                    <Duration>5000</Duration>
                    <Quality>128</Quality>
                </Value>
                <Value>
                    <Alias>x2</Alias>
                    <Timestamp>2014-11-11T00:02:00</Timestamp>
                    <Val>122</Val>
                    <Duration>5000</Duration>
                    <Quality>128</Quality>
                </Value>
            </ReadResult>
        </ReadResponse>
    </soap:Body>
</soap:Envelope>

and would like to parse it into a dataframe with the following structure (keeping some of the tags and discarding the rest):

Timestamp                x1    x2
2013-11-11T00:00:00      113  101
2014-11-11T00:02:00      110  122

The problem is since the XML file includes namespaces, I don't know how to proceed. I have gone through several tutorials (e.g., http://ift.tt/1rjd5Ef) and questions (e.g., How to open this XML file to create dataframe in Python? and Parsing XML with namespace in Python via 'ElementTree') but none of them have helped/worked. I appreciate if anyone can help me sorting this out.

Python EOFError after using os.execl to restart the script

I have a script that does the following;

  • Checks if a temp.txt file is present in the working directory.
    • If present the temp.txt file and update.pyd file is removed.
  • Checks whether an update.pyd module is present in the working directory.
    • If present it imports and runs it.
    • The update process creates a temp.txt file in the working directory.
    • After the update the script is restarted using os.execl(sys.executable, sys.executable, *sys.argv)

But I keep getting an error when os.execl(sys.executable, sys.executable, *sys.argv) is called:

Traceback (most recent call last):
  File "<string>", line 73, in execInThread
  File "<string>", line 44, in __call__
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 196, in __call__
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\netref.py", line 71, in syncreq
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 431, in sync_request
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 379, in serve
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\protocol.py", line 337, in _recv
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\channel.py", line 50, in recv
  File "C:\Program Files (x86)\PyScripter\Lib\rpyc.zip\rpyc\core\stream.py", line 166, in read
EOFError: [WinError 10054] An existing connection was forcibly closed by the remote host

I have another process in the same script that does something similar, and restarts using os.execl(sys.executable, sys.executable, *sys.argv), but restarts cleanly.

Could someone tell me why this is happening. What "connection" is the error referring to, and how do I close it before restarting? Thanks

Plot a distance map by apllyind the distance tranform to a list of vlues x and y, in PYTHON

I want to plot a distance map by apllying the distance tranform to a list of vlues x and y, in PYTHON.

I have started to plot the data from a CSV file:

"""PLOTTING DATA FROM A CSV FILE""""" #csv: comma separeted variables file
from matplotlib import pyplot as plt
from matplotlib import style
from pandas import DataFrame

df = DataFrame.from_csv('d:\Users\Raquel\Desktop/test.csv', header=0,sep=';')#unpact values into x and y using pandas to load my csv file

style.use('ggplot')

plt.scatter(df['x'].values,df['y'].values)
plt.title ('Data plot of a Tile')
plt.xlabel('xobj')
plt.ylabel('yobj')

plt.show()

Then I took the coordinates x and y from the file and I applied the distance transform:

 """DISTANCE MAP"""
#distance map: morphology distance transform gives the closeste distance of each pixel to its nearest boundary pixel
   from scipy.ndimage.morphology import distance_transform_edt

# Coordinates
x = df['x'].values
y = df['y'].values

# Distance Transform
dis = distance_transform_edt(x, y) #distance transform applied to x,y
plt.subplot(2,2,1),plt.imshow(dis, origin='lower')
plt.title('Distance Map')

from scipy.ndimage.filters import gaussian_filter #convolution with the gaussian
gf = gaussian_filter(dis, sigma= 2.5)#gaussian filter applied to dis
plt.subplot(2,2,2),plt.imshow(gf, origin='lower')
plt.title('Distance Map with GF')

After that I applied the contour to the Distance Map with the gaussian filter:

"""CONTOUR"""
   import matplotlib.pyplot as plt
   import numpy as np

plt.subplot(2,2,3),plt.contour(gf)
plt.title('Contour')

plt.show()

To finalise I plot the points in the back of the plotting of the contour immage:

"""CONTOUR & HOT SPOTS"""

from matplotlib.pyplot import (colorbar)
plt.subplot(2,2,4),plt.contour(gf) #plotting the  HS in the back of the           image with a transparency = alpha
plt.imshow(dis, origin='lower', alpha=0.19)
plt.title ('Contour & Hot Spots')

plt.show()

When I run my script I have this message and I don't know how to make my script work...

   Traceback (most recent call last):
   File "D:/Users/Raquel/PycharmProjects/BASES/Density Map/v.density map of a tile1.py", line 20, in <module>
   dis = distance_transform_edt(x, y) #distance transform applied to x,y
   File "D:\Users\Raquel\Anaconda\lib\site-packages\scipy\ndimage\morphology.py", line 2111, in distance_transform_edt
sampling = _ni_support._normalize_sequence(sampling, input.ndim)
   File "D:\Users\Raquel\Anaconda\lib\site-packages\scipy\ndimage\_ni_support.py", line 66, in _normalize_sequence
   raise RuntimeError(err)
   RuntimeError: sequence argument must have length equal to input rank

Explain Line of Code

The program returns the largest common subsequence using recursion. However, I need someone to explain me :

return max(lcs_recursive(xlist, ys), lcs_recursive(xs, ylist), key = len)

What exactly, it returns and whether it is the same as just writing:

return max(len(lcs_recursive(xlist,ys), lcs_recursive(xs, ylist))

So basically, I'd like someone to explain me what exactly key = len does.

Code:

s1 = "abc"
s2 = "aebabc"

def lcs_recursive(xlist, ylist):
    if not xlist or not ylist:
        return []
    x, xs, y, ys = xlist[0], xlist[1:], ylist[0], ylist[1:]
    if x==y:
        return [x] + lcs_recursive(xs,ys)
    else:
        return max(lcs_recursive(xlist, ys), lcs_recursive(xs, ylist), key = len)
print lcs_recursive(s1, s2)

django ManyToMany realtionship doesn't work

I'm trying to do this in my models.py:

class Tag(models.Model):
    ''' snip '''
    name = models.CharField(max_length=30)

class Stuff(models.Model):
    kind = models.CharField(max_length=30)
    tag = models.ManyToManyField(Tag)

But when i make qury from Stuff in shell the relationship fields return 'None' like this:

>>> q = Stuff.objects.all()
>>> p = q.tag.name
>>> print q.tag.name
None

I can't use this keys in my template too. Data base backend is mysql.

What is the problem?

Mark interpolated NaN points in Pandas plot

When I use interpolation (or fillna, or any other method of generating some fake data) in Pandas, I would like this to show in my plots. Ideally, I would like to use a different marker for these points in the plot. For regular points I want to use filled circles ('o'), for fake data I want to use crosses ('x').

Of course, I would like to do this with a nice Pythonic oneliner.

One further complication is that I want to use the subplots option in the plot function to plot all my columns at once. I'm hoping manipulating the subplots with Matplotlib voodoo is not necessary, though at this point that's the only option I can think of.

The data I'm using is something like the following (put into file 'meterstanden.ssv'):

datum       tijd   gas[m^3]   electra1[kWh] electra2[kWh]  water[m^3]
2015-03-06  09:00  4000.318   10300         9000           300.0
2015-03-24  20:10  4020.220   -             10003          -
2015-08-02  11:15  4120.388   10500         11000          350.5

And here is the script I'm using to process it:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_table("meterstanden.ssv", delim_whitespace=True,
                   parse_dates=[[0, 1]], index_col=0, na_values=['-'])

df.interpolate(method='time').plot(subplots=True, layout=(2, 2),
                                   figsize=(14, 10), marker='o')
plt.show()

I want the - entries in the table to be plotted with cross-markers.

Can't use makemigrations - TypeError: can't compare offset-naive and offset-aware datetimes

I'm getting TypeError: can't compare offset-naive and offset-aware datetimes error when i run python manage.py runserver command

In the past i had a problem with timezones, i was using USE_TZ = True but changed it to False as suggested in this question. Not sure if they are releated but i have no idea what is the couse and how to fix this problem.

Python & Pandas: Add a link to existing field

In my pandas table, the url is in ['douban_info']['alt'], I want to use it to turn the existing field ['db_rating'] into a link, maybe something like

pd_data['db_rating'] = '<a href=pd_data['douban_info']['alt'] >pd_data['db_rating']</a>'

but this above certainly doesn't work, I can only do something like:

from IPython.display import HTML
pd.set_option('max_colwidth', 500)
# link is in ['douban_info']['alt']
pd_data['link'] = pd_data['douban_info'].apply(lambda x:  x['alt'])
pd_data['a'] = pd_data['link'].apply(lambda x: '<a href="{0}">link</a>'.format(x))
# drop redundent info to make table look better
pd_data = pd_data.drop('douban_info', 1)
pd_data = pd_data.drop('omdb_info', 1)
pd_data = pd_data.drop('link', 1)
HTML(pd_data[0:5].to_html(escape=False))

This can only add a new a field, which produces enter image description here

There're certain thing that's really annoying:

  1. To get data from json, I only know to use pd_data['link'] = pd_data['douban_info'].apply(lambda x: x['alt'])

  2. I only know to use info from one field to another. In the case above, from link to a. I don't know how to use link and incoporate it into db_rating, how can I do it?

Filter a 2D numpy array from an array of values

Let's say I have a numpy array with the following shape :

nonSortedNonFiltered=np.array([[9,8,5,4,6,7,1,2,3],[1,3,2,6,4,5,7,9,8]])

I want to :

- Sort the array according to nonSortedNonFiltered[1] - Filter the array according to nonSortedNonFiltered[0] and an array of values

I currently do the sorting with :

sortedNonFiltered=nonSortedNonFiltered[:,nonSortedNonFiltered[1].argsort()]

Which gives : np.array([[9 5 8 6 7 4 1 3 2],[1 2 3 4 5 6 7 8 9]])

Now I want to filter sortedNonFiltered from an array of values, for example :

sortedNonFiltered=np.array([[9 5 8 6 7 4 1 3 2],[1 2 3 4 5 6 7 8 9]])
listOfValues=np.array([8 6 5 2 1])
...Something here...

> np.array([5 8 6 1 2],[2 3 4 7 9]) #What I want to get in the end

Note : Each value in a column of my 2D array is exclusive.

Django REST Framework: overriding get_queryset() sometimes returns a doubled queryset

I made a little endpoint, adapting DRF ReadOnlyModelViewSet, defined as follows:

class MyApi(viewsets.ReadOnlyModelViewSet):

    queryset = []
    serializer_class = MySerializer

    def get_queryset(self):
        print 'Debug: I am starting...\n\n\n\n'
        # do a lot of things filtering data from Django models by some information on neo4j and saving data in the queryset...
        return self.queryset

When I call MyApi via URL, it returns results without any problems, but sometimes it returns doubled result!! It's very strange...It's not a systematic error but happens only sometimes.

I use the line print 'Debug: I am starting...\n\n\n\n' in Apache log to investigate the problem. When that doubling happens, I read in the log:

Debug: I am starting...




Debug: I am starting...

It seems like get_queryset is called more than one time. It's very strange. I didn't report the detail of the logic inside that method, I think the problem is elsewhere or that is a bug...How can I solve?

How to pass variables to pyjade using simple_convert?

Template looks like:

template = """!!! 5
html
    head
        title Some title
...

and render with simple_convert:

html = pyjade.simple_convert(template)

But i need to use jade's if statements inside string template, and passing with .format(variable=value) doesn't work.

UWSGI log rotation

I am using uwsgi 2.0.10 version.

/etc/init/uwsgi.conf :

exec /home/testuser/virtual_environments/app/bin/uwsgi \
--master \
--processes 4 \
--die-on-term \
--uid testuser \
--home /home/testuser/virtual_environments/app \
--pythonpath /home/testuser/app \
--socket /tmp/uwsgi.sock \
--chmod-socket 660 \
--no-site \
--vhost \
--logto /var/log/uwsgi/uwsgi.log

/etc/logrotate.d/uwsgi:

/var/log/uwsgi/uwsgi.log {
    rotate 10
    daily
    compress
    missingok
    create 640 root root
    postrotate
        initctl restart uwsgi >/dev/null 2>&1
    endscript

But when i restart the server throw the message Unknown instance: so i need log rotation for daily log file. please correct if any modification in uwsgi.conf file. please help me.

Python Grouping Data

I have a set of data:

(1438672131.185164, 377961152)                                                                                                       
(1438672132.264816, 377961421)                                                                                                       
(1438672133.333846, 377961690)                                                                                                       
(1438672134.388937, 377961954)                                                                                                      
(1438672135.449144, 377962220)
(1438672136.540044, 377962483)
(1438672137.172971, 377962763)
(1438672138.24253, 377962915)
(1438672138.652991, 377963185)
(1438672139.069998, 377963285)
(1438672139.44115, 377963388)

What I need to figure out is how to group them. Until now I've used a super-duper simple approach, just by diffing two of the second part of the tuple and if the diff was bigger than a certain pre-defined threshold I'd put them into different groups. But it's yielded only unsatisfactory results.

But theoretically I imagine, that it should be possible to determine wether a value of the second part of the tuple belongs to the same group or not, by fitting them on one or multiple line, because I know about the first part of the tuple that it's strictly monotenous because it's a timestamp (time.time()) and I know that all data sets that result will be close to linear. Let's say the tuple is (y, x). There are only three options:

  • Either all data fits the same equation y = mx + c
  • Or there is only a differing offset c or
  • there is an offset c and a different m

The above set would be one group only. The following group would resolve in three groups:

(1438672131.185164, 377961152)                                                                                                       
(1438672132.264816, 961421)                                                                                                       
(1438672133.333846, 477961690)                                                                                                       
(1438672134.388937, 377961954)                                                                                                      
(1438672135.449144, 962220)
(1438672136.540044, 377962483)
(1438672137.172971, 377962763)
(1438672138.24253, 377962915)
(1438672138.652991, 377963185)
(1438672139.069998, 477963285)
(1438672139.44115, 963388)

group1:

(1438672131.185164, 377961152)                                                                                                       
(1438672134.388937, 377961954)                                                                                                      
(1438672136.540044, 377962483)
(1438672137.172971, 377962763)
(1438672138.24253, 377962915)
(1438672138.652991, 377963185)

group2:

(1438672132.264816, 961421)                                                                                                       
(1438672135.449144, 962220)
(1438672139.44115, 963388)

group3:

(1438672133.333846, 477961690)                                                                                                       
(1438672139.069998, 477963285)

Is there a module or otherwise simple solution that will solve this problem? I've found least-squares in numpy and scipy, but I'm not quite sure how to properly use or apply them. If there is another way besides linear functions I'm happy to hear about them as well!

Arcpy.ValidateFieldName does not validate field name?

I am working on a Python script using Arcpy. It creates a shape file, and then adds fields to it with names coming from user input. From the string the user has entered I need to produce a valid field name. I thought arcpy.ValidateFieldName() would accomplish this. However, I am having problems. Consider the code below:

#Create a new shapefile.
arcpy.CreateFeatureclass_management(r"C:\path\to\file", "shape.shp")

#Validate the fieldname.
name = arcpy.ValidateFieldName("0FIELD", "shape")

#Add the field
arcpy.AddField_management("shape", name, "STRING")

Even though the field name has been validated, it throws an error:

Runtime error Traceback (most recent call last):
File "", line 1, in
File "C:\script.py", line 8, in
arcpy.AddField_management("shape", name, "STRING")
File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3200, in AddField
raise e ExecuteError: ERROR 000310: The Field name must not start with a number

The function corrects other unallowed character (such as replacing spaces with underscores, and capping the string at 10 characters), but it misses to do something about the first character being a number even though that is not allowed in shape file field names.

Is this a bug, or am I using arcpy.ValidateFieldName() wrongly? Is there some other function I should use? Or will I have to write one myself? What should that one look like?

Using Factory boy ImageFiled results in missing attribute _committed error

I'm trying to set up data for a test case that requires an django.db.models.ImageField. I'm trying to use factory.django.ImageField from factory-boy, but get the error AttributeError: 'ImageField' object has no attribute '_committed'

Simplified django object:

class GalleryImage(models.Model):
    image = models.ImageField(upload_to='uploads/products')

Factory class:

class GalleryImageFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.GalleryImage

usage in test:

img = factory.django.ImageField(filename='test.jpg')
GalleryImageFactory.create(image=img)

This will give me the following error pointing to the line creating the GalleryImageFactory.

AttributeError: 'ImageField' object has no attribute '_committed'

I'm running python (2.7.6), factory-boy (2.4.1) and Django (1.6.8)

Full stack trace:

Traceback (most recent call last):
  File "/home/vagrant/sportamore/tests/sportamor_tests/catalog/test_pricefeed_google.py", line 80, in setUp
    image=img)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/factory/base.py", line 585, in create
    return cls._generate(True, attrs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/factory/base.py", line 510, in _generate
    obj = cls._prepare(create, **attrs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/factory/base.py", line 485, in _prepare
    return cls._create(model_class, *args, **kwargs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/factory/django.py", line 153, in _create
    return manager.create(*args, **kwargs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 157, in create
    return self.get_queryset().create(**kwargs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 322, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/vagrant/sportamore/sportamor/catalog/models/__init__.py", line 3960, in save
    super(GalleryImage, self).save(*args, **kwargs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 545, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 573, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 654, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 687, in _do_insert
    using=using, raw=raw)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 232, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 1514, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 902, in execute_sql
    for sql, params in self.as_sql():
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 860, in as_sql
    for obj in self.query.objs
  File "/home/vagrant/sportamore/venv/local/lib/python2.7/site-packages/django/db/models/fields/files.py", line 250, in pre_save
    if file and not file._committed:
AttributeError: 'ImageField' object has no attribute '_committed'

Any help appreciated, including tips of other methods of getting a valid image with the specified filename in place. Thanks in advance!