How to create polygon and calculate area of ocean within a circle on a map

I have a map with a circle drawn around a point. Part of the circle covers land and part of it covers ocean. I want to calculate the area of ocean within the circle, but I don't know how to create that polygon. The code for the map with the circle is

library(dismo)
library(scales)
library(rgeos)

GI <- gmap("Grand Isle,Louisiana", zoom = 7, scale = 2)
d <- data.frame(lat = c(29.2278), lon = c(-90.0122))
coordinates(d) <- ~ lon + lat
projection(d) <- "+init=epsg:4326"
d_mrc <- spTransform(d, CRS = CRS(projection(GI)))
d_mrc_bff <- gBuffer(d_mrc, width = 100000)

plot(GI)
plot(d_mrc_bff, col = alpha("blue", .35), add = TRUE)
points(d_mrc, cex = 2, pch = 20)

I have looked into mask{raster} and landmask{GSIF} functions, but I think in my case it won't work since I only want to mask the land within the circle, not on the entire map. Or I don't really need to mask it, but create the polygon with boundaries being the perimeter of the circle and the coastline.
Thank you for any suggestions!


Which Perl modules can be installed just by copying lib files?

I'm an absolute beginner at Perl, and am trying to use some non-core modules on my shared Linux web host. I have no command line access, only FTP.

Host admins will consider installing modules on request, but the ones I want to use are updated frequently (DateTime::TimeZone for example), and I'd prefer to have control over exactly which version I'm using.

By experimentation, I've found some modules can be installed by copying files from the module's lib directory to a directory on the host, and using

use lib "local_path";

in my script, i.e. no compiling is required to install (DateTime and DateTime::TimeZone again).

How can I tell whether this is the case for a particular module? I realise I'll have to resolve dependencies myself.

Additionally: if I wanted to be able to install any module, including those which require compiling, what would I be looking for in terms of hosting?

I'm guessing at the moment I share a VM with several others and the minimum provision I'd need would be a dedicated VM with shell access?


boostrap menu active page dont show style

So I want the active page to use same settings as the hover settings. No matter how I change the css I cant get it to work... long time since I've worked on this page tho so I might be missing some easy shit...

Style.css before changes

.navbar-default .navbar-brand {
    color: #fff;
    border-left:solid;
    border-right:solid;
    border-top:none;
    border-bottom:none;
    border-color:#202020;
    border-width:0.1pt;
  }
  .navbar-default .navbar-brand:hover,
  .navbar-default .navbar-brand:focus {
    color: #fff;
    border-left:solid;
    border-right:solid;
    border-top:none;
    border-bottom:none;
    border-color:#707070;
    border-width:0.1pt;
    background: -webkit-linear-gradient(top, rgba(112, 112, 112, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(112, 112, 112, 1) 0%, #404040 20%);
  }
  .navbar-default {
    font-size: 14px;
    background-color: rgba(0, 0, 0, 1);
    background: -webkit-linear-gradient(top, rgba(112, 112, 112, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(112, 112, 112, 1) 0%, #202020 20%);
    border-width: 0px;
    border-radius: 0px;
  }
  .navbar-default .navbar-nav>li>a {
    color: #fff;
    background-color: rgba(0, 0, 0, 1);
    background: -webkit-linear-gradient(top, rgba(112, 112, 112, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(112, 112, 112, 1) 0%, #202020 20%);
    border-left:none;
    border-right:solid;
    border-top:none;
    border-bottom:none;
    border-color:#202020;
    border-width:0.1pt;
  }
  .navbar-default .navbar-nav>li>a:hover,
  .navbar-default .navbar-nav>li>a:focus {
    color: #fff;
    background-color: rgba(255, 255, 255, 1);
    background: -webkit-linear-gradient(top, rgba(112, 112, 112, 1) 0%, rgba(0, 0, 0, 1) 100%);
    background: linear-gradient(to bottom, rgba(112, 112, 112, 1) 0%, #404040 20%);
    border-left:solid;
    border-right:solid;
    border-top:none;
    border-bottom:none;
    border-color:#707070;
    border-width:0.1pt;
  }
  .navbar-default .navbar-nav>.active>a,
  .navbar-default .navbar-nav>.active>a:hover,
  .navbar-default .navbar-nav>.active>a:focus {
    color: #fff;
    background-color: rgba(231, 231, 231, 1);
  }
  .navbar-default .navbar-toggle {
    border-color: #ddd;
  }
  .navbar-default .navbar-toggle:hover,
  .navbar-default .navbar-toggle:focus {
    background-color: #ddd;
  }
  .navbar-default .navbar-toggle .icon-bar {
    background-color: #888;
  }
  .navbar-default .navbar-toggle:hover .icon-bar,
  .navbar-default .navbar-toggle:focus .icon-bar {
    background-color: #000000;
  }
.navbar-default .navbar-right>li>a {
  border-left:solid;
border-width:0.1pt;
border-color:#202020;
}

Menu

<div class="navbar navbar-default navbar-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a href="index.php" class="navbar-brand">Per Källström</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="#">Comming soon</a></li>
                <li><a href="#">Comming soon</a></li>
                <li><a href="contact.php" class="active">Contact</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="admin.php">Admin</a></li>
            </ul>
        </div>
    </div>
</div>


INSERT INTO fails if inserting a variable with the value of Null

The SQL INSERT INTO will fail if the variable I am inserting has the value of Null.

The variable costLab is Variant data type. The non-Null value would be Decimal.

db.Execute ("INSERT INTO budget
(wbsid, category, capture_date, budget_date, budget_type, month_value) " & _
"VALUES ('" & wbsid & "', 'Labor', #" & importDate & "#,
#" & monthDate & "#, 'Forecast', " & costLab & ");")

I want to insert Null if the code that sets costLab returns Null. But if a value is returned I want to insert that value. Obviously I could write an If statement that checks for null then insert "Null" directly but I wanted to know if there was a way without the If statement to insert Nulls via a variable.


How do I interpret these crash reports from iOS

Hi I have had an iOS app in review, but it just got rejected... I have been trying to stimulate my ipad with iOS 6.1.3 to make it crash as described by apple:

Your app crashed when we tapped the action or option buttons.

But im failing, can the exact procedure of the crash be read from the report below?
Im suspecting they are doing something really crazy, can you tell me if the crash is network related? or if they have been pushing a certain button? I myself cant find enough information:

Symbolicated:

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x32b0629e __exceptionPreprocess + 158
1   libobjc.A.dylib                 0x3a9aa97a objc_exception_throw + 26
2   CoreFoundation                  0x32b061c0 +[NSException raise:format:] + 100
3   UIKit                           0x34aab56c -[UINib instantiateWithOwner:options:] + 1632
4   UIKit                           0x34aaab96 -[UIViewController _loadViewFromNibNamed:bundle:] + 230
5   UIKit                           0x349a3038 -[UIViewController loadView] + 88
6   UIKit                           0x3492d468 -[UIViewController loadViewIfRequired] + 64
7   CodeFriend                      0x0000fb14 -[ThemesPopOverViewController initWithNibName:bundle:] (ThemesPopOverViewController.m:24)
8   CodeFriend                      0x0000e21a -[AppDelegate settingAct:] (AppDelegate.m:127)
9   UIKit                           0x349f90c0 -[UIApplication sendAction:to:from:forEvent:] + 68
10  UIKit                           0x349f9072 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 26
11  UIKit                           0x349f9050 -[UIControl sendAction:to:forEvent:] + 40
12  UIKit                           0x349f8906 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 498
13  UIKit                           0x349f8dfc -[UIControl touchesEnded:withEvent:] + 484
14  UIKit                           0x349215ec -[UIWindow _sendTouchesForEvent:] + 520
15  UIKit                           0x3490e7fc -[UIApplication sendEvent:] + 376
16  UIKit                           0x3490e116 _UIApplicationHandleEvent + 6150
17  GraphicsServices                0x3660259e _PurpleEventCallback + 586
18  GraphicsServices                0x366021ce PurpleEventCallback + 30
19  CoreFoundation                  0x32adb16e __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 30
20  CoreFoundation                  0x32adb112 __CFRunLoopDoSource1 + 134
21  CoreFoundation                  0x32ad9f94 __CFRunLoopRun + 1380
22  CoreFoundation                  0x32a4ceb8 CFRunLoopRunSpecific + 352
23  CoreFoundation                  0x32a4cd44 0x32a44000 + 36164
24  GraphicsServices                0x366012e6 GSEventRunModal + 70
25  UIKit                           0x349622fc UIApplicationMain + 1116
26  CodeFriend                      0x0000d3b6 main (main.m:16)
27  libdyld.dylib                   0x3ade1b1c start + 0

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x3aea8350 __pthread_kill + 8
1   libsystem_c.dylib               0x3ae1f11e pthread_kill + 54
2   libsystem_c.dylib               0x3ae5b96e abort + 90
3   libc++abi.dylib                 0x3a3f9d4a abort_message + 70
4   libc++abi.dylib                 0x3a3f6ff4 default_terminate() + 20
5   libobjc.A.dylib                 0x3a9aaa74 _objc_terminate() + 144
6   libc++abi.dylib                 0x3a3f7078 safe_handler_caller(void (*)()) + 76
7   libc++abi.dylib                 0x3a3f7110 std::terminate() + 16
8   libc++abi.dylib                 0x3a3f8594 __cxa_rethrow + 84
9   libobjc.A.dylib                 0x3a9aa9cc objc_exception_rethrow + 8
10  CoreFoundation                  0x32a4cf1c CFRunLoopRunSpecific + 452
11  CoreFoundation                  0x32a4cd44 CFRunLoopRunInMode + 100
12  GraphicsServices                0x366012e6 GSEventRunModal + 70
13  UIKit                           0x349622fc UIApplicationMain + 1116
14  CodeFriend                      0x0000d3b6 main (main.m:16)
15  libdyld.dylib                   0x3ade1b1c start + 0

Thread 1:
0   libsystem_kernel.dylib          0x3aea8d98 __workq_kernreturn + 8
1   libsystem_c.dylib               0x3adf6cf6 _pthread_workq_return + 14
2   libsystem_c.dylib               0x3adf6a12 _pthread_wqthread + 362
3   libsystem_c.dylib               0x3adf68a0 start_wqthread + 4

Thread 2 name:  Dispatch queue: com.apple.libdispatch-manager
Thread 2:
0   libsystem_kernel.dylib          0x3ae98648 kevent64 + 24
1   libdispatch.dylib               0x3adc8974 _dispatch_mgr_invoke + 792
2   libdispatch.dylib               0x3adc8654 _dispatch_mgr_thread$VARIANT$mp + 32

Thread 3:
0   libsystem_kernel.dylib          0x3aea8d98 __workq_kernreturn + 8
1   libsystem_c.dylib               0x3adf6cf6 _pthread_workq_return + 14
2   libsystem_c.dylib               0x3adf6a12 _pthread_wqthread + 362
3   libsystem_c.dylib               0x3adf68a0 start_wqthread + 4

Thread 4 name:  WebThread
Thread 4:
0   libsystem_kernel.dylib          0x3ae97eb4 mach_msg_trap + 20
1   libsystem_kernel.dylib          0x3ae98048 mach_msg + 36
2   CoreFoundation                  0x32adb040 __CFRunLoopServiceMachPort + 124
3   CoreFoundation                  0x32ad9d9e __CFRunLoopRun + 878
4   CoreFoundation                  0x32a4ceb8 CFRunLoopRunSpecific + 352
5   CoreFoundation                  0x32a4cd44 CFRunLoopRunInMode + 100
6   WebCore                         0x38a3c500 RunWebThread(void*) + 440
7   libsystem_c.dylib               0x3ae0130e _pthread_start + 306
8   libsystem_c.dylib               0x3ae011d4 thread_start + 4

Thread 0 crashed with ARM Thread State (32-bit):
    r0: 0x00000000    r1: 0x00000000      r2: 0x00000000      r3: 0x3c99e534
    r4: 0x00000006    r5: 0x3c99eb88      r6: 0x1dda5554      r7: 0x2fdf7a14
    r8: 0x1dda5530    r9: 0x00000300     r10: 0x00000000     r11: 0x00000000
    ip: 0x00000148    sp: 0x2fdf7a08      lr: 0x3ae1f123      pc: 0x3aea8350
  cpsr: 0x00000010

So moving on: The code used to initialize the ThemesPopOverViewController is:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {

            self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width - 40, 350)];
            [self.tableView setBackgroundColor:[UIColor clearColor]];
            [self.tableView setDelegate:self];
            [self.tableView setDataSource:self];
            themes = [[NSArray alloc] initWithObjects:kRegexHighlightViewThemeArray];
            [self.view addSubview:self.tableView];
            int item = [themes indexOfObject:theDelegate.codeView.currentTheme];
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
            [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

        }

        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        // Do any additional setup after loading the view from its nib.
    }

I actually seems that even after the popover is removed from the view hierarchy the allocation done by the init method above occupies memory, it is ARC, do i need to set it to nil somewhere above removing the popover? So everytime the popover is pressed the memory allocations increase...


Django admin :: I want to keep last selected value on adding another item

Context

in django administration site

I am adding a new item in a model via add button

when the form is displayed, I have a dropDown  with some options to choose, I choose option B and I fill other fields to complete the form

I click on button save and add another

When the new "add form view" is displayed
I want my dropdown to set on the last choice (B option) I selected before

What is your suggestion to implement that as simple is possible?

Thank you


latex beamer footer alignment

How can I add text line on left side and frame number on right side of footer in latex beamer presentation?

Also, I need to exclude title page from this footer placement.


language switcher not redirecting to proper url in Magento2

we have multi-store site and in two languages 'arabic' and 'english'.
When we are changing language its reloading page with below parameter -

CurrentPageUrl?___from_store=en_sa

i.e right.

But after this when I am again changing language 'arabic' to 'english' then instead of changing parameter of vurrent url its not concatenating parameter to current url like  -

CurrentPageUrl?___from_store=en_sa?___from_store=ar_sa

Can you plz let me know, how to solve this issue?

Thanks


Using C++ struct with iPhone app

As I heard it is possible to use C++ Code within an iPhone (Objective C) project, I want to use an encryption library which is written in C++. However, the library uses a C++ type struct which uses a constructor, that I can't get right.

The Struct looks like this:

struct SBlock
{
 //Constructors
 SBlock(unsigned int l=0, unsigned int r=0) : m_uil(l), m_uir(r) {}
 //Copy Constructor
 SBlock(const SBlock& roBlock) : m_uil(roBlock.m_uil), m_uir(roBlock.m_uir) {}
 SBlock& operator^=(SBlock& b) { m_uil ^= b.m_uil; m_uir ^= b.m_uir; return *this; }
 unsigned int m_uil, m_uir;
};

full source is available here: http://www.codeproject.com/KB/security/blowfish.aspx

what's the easiest way to get around that issue?
I've read the article about using c++ code on apple's developer site, but that didn't help much.


Django retrieve most recent model per day for each item in a list of foreign keys

I'm looking for the most efficient way to do the following:

I have the following model:

class DataEntry(models.Model):
    signal_name = models.CharField(max_length=255)#FK to Signal.name without telling Django (or the database) the relationship (LONG STORY, OUT OF MY HANDS)
    timestamp = models.DateTimeField()
    value = models.FloatField()

I have a list of signal names (strings) and a list of days. I need to retrieve the most recent DataEntry for each signal name in the signal list for each day in the list of days.  Essentially...

for signal in signal_list:
    for day in day_list:
        next_day =  day + timedelta(days=1)
        entry_list.append(DataEntry.objects
            .filter(timestamp__lt=next_day)
            .filter(signal_name=signal)
            .order_by("-timestamp")[0])

This seems like it would generate a TON of database calls. Is there any ORM trickery I can utilize to turn this into as few database calls as possible?


Line-height was larger than paragraph

I set font to 200px and line height to 200px, when i set it I expected font height exactly 200px but it isnt :(, paragraf has height 200px, but font has 223px, can you tell my why?

HTML

<p class="par">
A<span id="why">Áj</span>gxÁj
</p>

CSS

body{font-size: 200px;font-family: Arial;line-height: 200px;}
.par{background-color: rgba(0, 255, 0, 0.5);}
#why{background-color: rgba(255, 0, 0, 0.5);}

Fiddle link


Strip trailing decimal points from floats in pandas

All columns in my dataset seem to be floats.
Some contain values like like '20. ' or '11. '

How can I selectively and quickly remove the dot and space, without affecting the other values in the column, like '24.4' or '12.5'?

I have tried several solutions but none of them worked.

My goal is to change, for example, '12. ' to '12', for each value in each cell where '. ' appears.


Accessing raw request string from Flask app

Is it possible to access the raw, unparsed request data from within a Flask app?


Tomcat connector architecture, thread pools and async servlets

I would like to understand Tomcat's thread model for BIO and NIO connectors. I am referencing the official Tomcat 7  documentaion for connectors which can be found here. Based on it, this is what I have in doubt:

acceptorThread(s) : This is a single or at the most 2 threads (as mentioned in the doc) which is responsible only for accepting in-coming connections. This can be configured using acceptorThreadCount, and it's suggested that more than two can be used for a multi-cpu machine -

why is this ?

Does this imply that the number of simultaneous open connections scales with the number of cpus versus the number of open file descriptors allowed on the server system ?

maxConnections(s) :

What is the relation between this setting and acceptCount and the number of open file descriptors on the system.

Why is the default value for this so much higher for the NIO connector ( 10000 ) than for the BIO ( = maxThreads ) ?

acceptCount : This is the queue for requests when all request processing threads are busy.

When requests are put into this queue, is a file descriptor assigned to it as well ? Or is it only when a request is being actively processed, does it consume a file descriptor ?

request processing threads : The number of threads in this pool is configured by the maxThreads and minSpareThreads attributes.

What is the relation between this thread pool and the acceptorThreads ? Does the acceptor thread(s) spawn the threads in this pool ?

As I understand, the NIO model is more efficient with the request processing threads than the BIO model. How does it achieve this efficiency ?

As I've read in various sources, threads in the NIO model follow the thread per request paradigm vs the thread per connection paradigm of the BIO model. Also, in the NIO connector model, the actual request processing is delegated to a different,  application monitored thread while the server's request processing thread is returned to the thread pool- free to accept more connections. So, does this imply that the benefit of the NIO model will only be apparent if the connections to the server are of the HTTP Keep-Alive nature or if the application is using Servlet 3.0's asynchronous processing feature ?

Servlet 3.0 :

When using Servlet 3.0, what should be the size of the application servlet thread pool ( relative to the connector thread pool size ) to achieve optimum efficiency ?

When using the BIO model and this together, will there be any difference as to how requests are processed ( given that the connector threads will still be using the thread per connection model ) ?

Please note: All discussion with respect to tomcat 7.


NullPointerException VideoView and MediaController on Fragment in android

I am developing Galaxy Tab 10.1 app by using honeycomb 3.1 and i have a videoview and mediacontroller in fragment on the right side. I defined VideoView and MediaController in Layout xml file and instantiate and manipulate them in the related java file.

As you guys konw, in the java file, i set VideoView's controller to MediaController and set MediaController's media player to VideoView, i defined.

Below is fragment layout xml file

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <MediaController
        android:id="@+id/controller"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

and java code file is below

public class ContentFragment extends Fragment {
    private VideoView mVideo;
    private MediaController mController;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content, null);
        mVideo = (VideoView)view.findViewById(R.id.video);
        mController = (MediaController)view.findViewById(R.id.controller);
        mVideo.setMediaController(mController);
        mController.setMediaPlayer(mVideo);

        return view;
    }

    public void playVideo(String path) {
        mVideo.setVideoPath(path);
        mVideo.requestFocus();
    }
}

But while running this app, there occurs

NullPointerException with
  android.widget.MediaController.show(MediaController.java:305)

I tried to solve this error a whole day but i can't get the reason why. actullay there isn't enought information for this.
Dose any body know what i did wrong? or have solutions?
Please let me know.

Thanks.


Angular ng-style on body tag for different page backgrounds?

I am new to angular and ngroute and am trying to use ng-style to have a different image background for each page of a website.  Currently it sets the background of all the site's pages, even when I have different controller scope image urls.

My html is like this:

<body ng-controller="mainController" ng-style="bodyStyles">
...
   <div id="main">
      <div ng-view></div>
</body>

My script:
 var angVenture = angular.module('angVenture', ['ngRoute']);

// configure routes
angVenture.config(function($routeProvider, $locationProvider) {
    $routeProvider

        // route for the index page
        .when('/home', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

 ... more routes.....

// create the controller
angVenture.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'home page';
    $scope.bodyStyles ={
        "background": "url(../images/someimage.jpg) no-repeat center center fixed",
        "-webkit-background-size": "cover",
        "-moz-background-size": "cover",
        "-o-background-size": "cover",
        "background-size": "cover"
    }
});

angVenture.controller('aboutController', function($scope) {
    $scope.message = 'another page.';
});

....more controllers for different pages...

Would I be better off going about doing this with ui-router?


The number of processes a user is running using bash

I would like to know how I could get the number of processes for each user that is currently logged in.


elastic search aggregate doesn't return data

It possible that aggregate function returns data instead of count?

Right now I get:

array (size=3)
'doc_count_error_upper_bound' => int 0
'sum_other_doc_count' => int 0
'buckets' =>
array (size=2)
  0 =>
    array (size=2)
      'key' => int 15
      'doc_count' => int 2
  1 =>
    array (size=2)
      'key' => int 14
      'doc_count' => int 1

But this is useless cause I need the actual data that represents this doc_count of 2 and doc_count of 1

I'm using elastica.io


Facebook Graph API Upgrade

I'm working on website that has an old facebook API implementation with Facebook SKD for PHP. I'm not able to update SDK to newer version since it requires PHP 5.4, this project works under 5.3 so I'm forced to use old one.
I have access to API upgrade tool and it shows me a lot of methods that I should fix, for example GET /posts
Assume I want upgrade to v2.4 and I use link to find out what changed in that request. What I found:

Deprecated Fields

As of April 18, 2017, the following parameters are no longer supported
  by Graph API versions 2.9 and higher. For versions 2.8 and lower, the
  parameters will continue working until July 17, 2017.

The link field is still supported, but its sub-fields have been
  deprecated.

I feel myself so stupid but I can't realize what should I use instead of link field after it will be deprecated on 17th July?


quartz threw an unhandled Exception: : java.lang.NullPointerException with JSF+EJB

I am using JSF and EJB in my project.

I have one functionality where i need to send the sms to some people for every 1 hour.

For that i am getting the information(some persons) from the database to whom i need to send.

While retrieving from the database it is throwing the following exceptions.

09:51:29,640 ERROR [org.quartz.core.JobRunShell] (DefaultQuartzScheduler_Worker-2) Job group1.job1 threw an unhandled Exception: : java.lang.NullPointerException
at hms.general.SendSMSJob.execute(SendSMSJob.java:43) [classes:]
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-all-2.1.7.jar:]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557) [quartz-all-2.1.7.jar:]

09:51:29,640 ERROR [org.quartz.core.ErrorLogger] (DefaultQuartzScheduler_Worker-2) Job (group1.job1 threw an exception.: org.quartz.SchedulerException: Job threw an unhandled exception. [See nested exception: java.lang.NullPointerException]
at org.quartz.core.JobRunShell.run(JobRunShell.java:224) [quartz-all-2.1.7.jar:]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557) [quartz-all-2.1.7.jar:]
Caused by: java.lang.NullPointerException
at hms.general.SendSMSJob.execute(SendSMSJob.java:43) [classes:]
at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-all-2.1.7.jar:]
... 1 more

The following code is for scheduler
    package hms.general;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

@ManagedBean(eager=true)
@ApplicationScoped
public class ScheduleBean {
public ScheduleBean() {
    try{
        Scheduler scheduler =  StdSchedulerFactory.getDefaultScheduler();
        scheduler.start();

        JobDetail job = org.quartz.JobBuilder.newJob(SendSMSJob.class).withIdentity("job1","group1").build();
        Trigger trigger = org.quartz.TriggerBuilder.newTrigger().withIdentity("trigger1","group1").startNow().withSchedule(org.quartz.SimpleScheduleBuilder.simpleSchedule().withIntervalInHours(1).repeatForever()).build();
        scheduler.scheduleJob(job,trigger);

    }
    catch(SchedulerException se){
        se.getMessage();
    }
}
}

Code for JobScheduler
    import hms.db.PatientRegEMRemote;
    import hms.db.Prescription;
    import hms.db.PrescriptionEMRemote;

import java.util.List;

import javax.ejb.EJB;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class SendSMSJob implements Job {

@EJB(mappedName = "java:global/Hms-Main/PatientRegEM!hms.db.PatientRegEMRemote")
public PatientRegEMRemote patreg_r;

@EJB(mappedName = "java:global/Hms-Main/PrescriptionEM!hms.db.PrescriptionEMRemote")
private PrescriptionEMRemote prescription_r;

public static void main(String ar[]){
    SendSMSJob hj = new SendSMSJob();
    try {
        hj.execute(null);
    } catch (JobExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
    System.out.println(arg0.getJobDetail());
    System.out.println("I am in execute method....");
    // TODO Auto-generated method stub
    System.out.println("Im inside execute method");
    String s="select p from prescription p where p.smsflag=1";
    System.out.println(s);
    List<Prescription> pre=prescription_r.retrieveAll(s);
    System.out.println(".........");
    for (Prescription p : pre) {
        System.out.println(p.getAppointno());
    }
}
}


Instantiating a generic extension of an abstract class

Trying to write some generalised code for Genetic Algorithms and I have an abstract class Genotype as follows:

public abstract class Genotype {
private ArrayList<Gene> genotype = new ArrayList<Gene>();

//...

public Genotype(ArrayList<Gene> genotype) {
    setGenotype(genotype);
    setGenotypeLength(genotype.size());
}

public abstract Phenotype<Gene> getPhenotype();

public abstract void mutate();

//...
}

This class is intended to be extended and the subclass obviously provides the implementation of getPhenotype() and mutate(). However, I also have a second class that takes two Genotype objects as parameters and returns an ArrayList containing Genotype objects. Since I don't know the type of the extended Genotype objects at this point I need to use a generic parameter as follows:

public class Reproducer {

//...

    private <G extends Genotype> ArrayList<Genotype> crossover(G parent1, G parent2) {
        ArrayList<Genotype> children = new ArrayList<Genotype>();

        ArrayList<Gene> genotypeOne = ArrayListCloner.cloneArrayList(parent1.getGenotype());
        ArrayList<Gene> genotypeTwo = ArrayListCloner.cloneArrayList(parent2.getGenotype());

        //one point crossover
        int p = gen.nextInt(genotypeOne.size());

        for (int i = 0; i < p; i++) {
            genotypeOne.set(i, genotypeOne.get(i));
            genotypeTwo.set(i, genotypeTwo.get(i));
        }
        for (int i = p; i < 10; i++) {
            genotypeOne.set(i, genotypeTwo.get(i));
            genotypeTwo.set(i, genotypeOne.get(i));
        }

        children.add(new G(genotypeOne)); //THROWS ERROR: Cannot instantiate the type G
        children.add(new G(genotypeTwo)); //THROWS ERROR: Cannot instantiate the type G

        return children;
    }
}

However, since I need to return two objects of type G in an ArrayList I clearly have a problem where I can't instantiate the new Genotype objects because they're 1. generic types and presumably 2. abstract.

This might be a bad way of going about things all together but if anyone has a solution that would be great. Thank you.


Mule Http basic authentication - set username in variable

I have implemented HTTP Basic Authentication for my mule flow application.

It listens on HTTP and the URI is http://localhost:8082/login.

<flow name="wsGetReport">
    <http:listener config-ref="HTTP_Listener_Configuration" path="${wsPath}" doc:name="HTTP"/>
    <logger level="INFO" message="## received" doc:name="Logger"/>
    <http:basic-security-filter realm="mule-realm"/>
    <flow-ref name="doSubFlow" doc:name="doSubFlow"/>
    <logger level="INFO" message="## passed security" doc:name="Logger"/>
    <http:static-resource-handler resourceBase="${app.home}/classes" doc:name="HTTP Static Resource Handler" defaultFile="index.html"/>
</flow>

I would retrieve the username typed in the login by the user, and show it in the http Static resource (an html page).

How can I store the username used in authentication?

Thanks.


How to send -f parameter equivalent from swiftmail?

I am trying to migrate from PHP mail to SendGrid using swift mail. I am not able to understand -f email additional parameter.

mail($Email,$sub,$cont,$headers,'-f noreply@mydomain.com')

I am not sure what type of header is this. Should i send this as path_header?

I could not undersrtand the explanation of this here.


Slf4j compatibility issues between solr and hadoop

I am using behemoth solr on hadoop, and I am getting a conflict in the slf4j versions. Solr 3.6.2 uses slf4j-api-1.6.1 and hadoop 1.0.4 has libraries for slf4j-api-1.4.3. Due to this, I am unable to run the behemoth solr jar file on hadoop. What is the best way to resolve this conflict? One option is replacing slf4j libraries in hadoop, but I am not willing to do that. Any solution will be greatly appreciated.


Unable to upload file (size greater than 50KB) using Jquery hosted on apache httpd server

Scenarios:

I am able to upload files successfully which are less then 50 kb.

Anything greater then 50 kb the request does not reach the server itself(My  observation).

All GET  requests are working fine.

Any help would be appreciated.

Thanks in advance.

angular.module('myApp', []).directive('ngFiles', ['$parse', function($parse) {
  function fn_link(scope, element, attrs) {
    var onChange = $parse(attrs.ngFiles);
    element.on('change', function(event) {
      onChange(scope, {
        $files: event.target.files
      });
    });
  };

  return {
    link: fn_link
  }
}]).controller('myController', function($scope, $http) {
  var formdata = new FormData();
  $scope.getTheFiles = function($files) {
    angular.forEach($files, function(value, key) {
      formdata.append(key, value);
    });
  };

  // NOW UPLOAD THE FILES.
  $scope.uploadFiles = function() {
    var request = {
      method: 'POST',
      url: '/api/fileupload/',
      data: formdata,
      headers: {
        'Content-Type': undefined
      }
    };

    // SEND THE FILES.
    $http(request).success(function(d) {
      // Some Logic
    }).catch(function(Object) {
      // Some Logic
    });
  }
});


Hashing functions with special characters?

My application requires database to store username and password. To hash password I am looking for SHA 1 algorithm. Basically I need few special characters such as . , ! @ # $ % ^ & * ( ) along with A-Z , a-z, 0-9 etc in my hash.

Any way to get them?

looking for php or javascript implementation.


how to deploy python webservice on apache

I'm a green hand in Python.I have got a simple webservice with python as following:

enter code here

import soaplib
from soaplib.core.service import rpc, DefinitionBase
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array
from soaplib.core.service import soap

class HelloWorldService(DefinitionBase):

    @soap(String,Integer,_returns=Array(String))
    def say_hello(self,name,times):
        results = []
        for i in range(0,times):
            results.append('Hello, %s'%name)
        return results
if __name__=='__main__':

    try:

        from wsgiref.simple_server import make_server
        soap_application = soaplib.core.Application([HelloWorldService], 'tns')
        wsgi_application = wsgi.Application(soap_application)
        server = make_server('10.44.138.231', 9999, wsgi_application)
        server.serve_forever()

    except ImportError:

        print "Error: example server code requires Python >= 2.5"

it's very fast when I access the service in localhost,but it will become very slow from the another host in local area network.

so I want to deploy this program in apache,but it seems hard,I search this in google for a long time and it makes me very tired now. who can give me a help,Thank you


A relational query, not sure how to build it with EXISTS

carts
id user_id

cart_proucts
id cart_id product_id price

products
much details about the product...

So this is some easier form of my table structure currently. I have a list of product Id, that I need to check against a User if he has them  or not, I know that by looking at cart_products which a cart belongs to a user, as the relationship described above. If he has  I should retrieve that "User" and information he contains. But I also need to check if the price range of the product, i.e. the product must not be lower than 500 for i.e. The price column in the cart_products...

How can I easiest build this sql? I am thinking of JOINS and some use of EXISTS or IN perhaps?


Stop armv7s support in app update

Previously, our iOS app supported armv6, armv7 and armv7s architectures. In the new version that is not submitted yet we added some third-party libraries that support armv6 and armv7 only. So the whole project was forced to support only these two architectures. I understand that armv7s is a superset of armv7 and compatibility won't be affected but is it ok to submit the update that doesn't support armv7s anymore to the App Store? Maybe someone had the same experience?
Thanks in advance.


open javafx window with it's relative path

I need to open a fxml window from a javafx controler

Stage graphStage = new Stage();
    FXMLLoader loader = new FXMLLoader();
    fenetre = new File("../graph/graph.fxml");
    if (!fenetre.exists()) {
        System.out.println("fichier inexistant");
    } else {
        Pane rootGraph = loader.load(getClass().getResource(fenetre.getPath()).openStream());
        GraphController controller = (GraphController) loader.getController();
        controller.getSystemChoice(id);
        Scene sceneGraph = new Scene(rootGraph);
        sceneGraph.getStylesheets().add(getClass().getResource("myStyle.css").toExternalForm());

        graphStage.setTitle("Graphe");
        graphStage.setScene(sceneGraph);
        graphStage.show();
    }

the code doesn't fincd the file, how to reach this file ?

controler is on: cloud/composant/controler.java
my fxml is on:   cloud/graph/graph.fxml


How to pass Excel Array Formula to VBA UDF?

I have already looked at a similar solution here but somehow I still could not make my code work.

I want to pass an output of an Array Formula as Input to UDF, process it and return a single value from it. Say just add all items in an array and return the value as an example. My main question is how to pass an output of an Array Formula to UDF and process it inside the UDF.

'Public Function Test1(ParamArray Parm1() As Variant) As Integer
'Dim i, j
'i = 0
'For j = LBound(Parm1) To UBound(Parm1)
'
'    i = i + Parm1(j)
'
'Next j
'Test1 = i
'End Function

Public Function Test1(Parm1 As Variant) As Integer
Dim i, j
Dim tmparray() As Variant
tmparray = Parm1
For j = LBound(tmparray, 1) To UBound(tmparray, 2)
   i = i + tmparray(j)
Next j
Test1 = i
End Function

Above commented code did not work. I tried to modify it by referring the mentioned solution as pasted just below it, but still I could not make it work.

In Excel Spreadsheet I am passing {=Test1(ROW(C1:C4))} as an Array Formula to this but it returns #VALUE!

In above code (The commented one) if I test and debug thru below sub it works fine but when called from an Excel Array Formula like {=Test1(ROW(C1:C4))}it returns #VALUE!

Sub check()

j = Test1(1, 2)

End Sub

Could someone help me further please?


Scaling ImageButton basing on screen size

In my application i can scaling an ImageView using this class

`public class resizeAvatar extends View {

private final Drawable sfondoAvatar;

public resizeAvatar(Context context) {
    super(context);

    sfondoAvatar = context.getResources().getDrawable(R.drawable.main_voice);
    setBackgroundDrawable(sfondoAvatar);

}

public resizeAvatar(Context context, AttributeSet attrs) {
    super(context, attrs);

    sfondoAvatar = context.getResources().getDrawable(R.drawable.main_voice);
    setBackgroundDrawable(sfondoAvatar);
}

public resizeAvatar(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    sfondoAvatar = context.getResources().getDrawable(R.drawable.main_voice);
    setBackgroundDrawable(sfondoAvatar);
}

@Override
protected void onMeasure(int widthMeasureSpec,
                                   int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = width * sfondoAvatar.getIntrinsicHeight() / sfondoAvatar.getIntrinsicWidth();
    setMeasuredDimension(width, height);
}

}
`

And writing in the layout:

<com.myapp.app.resizeAvatar
        android:id="@+id/mainvoice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_centerVertical="true"/>

But in this way i can't have the onClick event.. i need do the same but using an ImageButton.. Is there a way?


Android - Cannot get priority of IntentFilter

In my program I search for packages that match a specific intent.

From the list of ResolveInfo I get, I then try and order the packages according to the priority of their IntentFilter. But when I use the intentFilter.getPriority() method, it always returns 0, even though different priority values are used in the manifest of the targeted packages.

Here is an example of a Manifest:

<intent-filter
          priority='100'>
        <action
            name='com.gsma.services.nfc.action.TRANSACTION_EVENT'>
        </action>
        <category
            name='android.intent.category.DEFAULT'>
        </category>
        <data
            scheme='nfc'
            host='secure'
            pathPattern='/SIM.*/a0000005595000000000000052414431'>
        </data>
      </intent-filter>

And here is the code in which I retrieve the ResolveInfo and the priority:

Intent gsmaIntent = new Intent();
gsmaIntent.setAction("com.gsma.services.nfc.action.TRANSACTION_EVENT");
gsmaIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
gsmaIntent.setData(Uri.parse("nfc://secure:0/"+ seName+"/"+ strAid));

PackageManager pm = mContext.getPackageManager();
List<ResolveInfo> resInfo = pm.queryIntentActivities(gsmaIntent,
PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER);

    ...

if ((resInfo != null) && (resInfo.size() != 0))
{
    for (ResolveInfo res : resInfo)
    {
        intentFilter = res.filter;

        if (intentFilter != null)
        {
            priority = intentFilter.getPriority();
    ...

EDIT: Could it be that info is missing for the queryIntentActivities() call?

On my first trial I did not used the PackageManager.GET_RESOLVED_FILTER flag and hence did not get the IntentFilter data. Is there another flag to retrieve the priority value?

EDIT 2: If the above code cannot work, does anyone know another way to get the   the priority value from an IntentFIlter?


Can you make a user-based search with Facebook API?

On Facebook when you write something in the search box in the top.

Like 'Eric'

You first get the results with your friends named Eric and further down you get people you might know with X mutual friends and some random people in the vicinity you might know.

Is it possible to make a similar search with the Facebook API?

I've tried:

https://graph.facebook.com/search?q=eric&type=user&fields=id,name&access_token= (my token)

And thought if I added my access_token I would get a search like the one on Facebook. But I just get some random Eric's from all over the world.

I'm writing a simple web application and getting this search to work would be great! Thanks!


ask user name and check if length is between 3 and 256 characters

I'm new in coding and I'm trying to have the user input his name and if the user's name is not between 3 and 256, he have to re enter his name!
Here's my code so far...

public static void main(String[] args) {
    String userName = "";
    do {
        System.out.print("Enter your name (between 3 and 256 characters) :");
        Scanner name = new Scanner(System.in);
        userName = name.nextLine();

        if ((userName.length() < 3) && (userName.length() > 256));
            System.out.println("the length is not good");

    } while ((userName.length() < 3) && (userName.length() > 256));

}


Android testing of the floating view

I add a floating view to the WindowManager, and make it movable around the screen, and i can perform click event when i click this view, everything works fine.

However, I don't know how to access this view in espresso or UIAutomator.

Add view to WindowManager

final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    type,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                    PixelFormat.TRANSLUCENT
            );

            ImageView floatingView = new ImageView(mContext);
            floatingView.setContentDescription("bugtags_fab_des_normal");
            mWindowManager.addView(floatingView, layoutParams);

The Floating View

the white-blue icon in rect is the floating view i am talking about.

Question

The floating view response a click event, and perform some task, now i want to do this in AndroidJunit test.

Espresso

I try Espresso, using onView method, but the test case:

onView(withContentDescription("bugtags_fab_des_normal")).perform(click());

Get:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with content description: is "bugtags_fab_des_normal"

UIAutomator

I try UIAutomator Viewer, but i can't find the floatingView in view hierarchy.

How

How can i access this view in espresso or uiautomator and perform click to it?

Appendix

Test Case

@Test
public void testInvoke() {
    onView(withContentDescription("bugtags_fab_des_normal")).perform(click());
}

Output log

output-log-gist

Bugtags.com

Actually, i am using a sdk called bugtags.com, it's a simple tool for app bug reporting and crash analysis.


How to add zoom effect to an activity?

Hello i want to add zoom option to this activity. I tried few things but failed is anyone can help me please?
I followed this tutoril and made this activity.
Here is tutorial : tutorial

Here is my activity.java

public class activity extends AppCompatActivity {
private SliderLayout mDemoSlider;

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

    mDemoSlider = (SliderLayout) findViewById(slider);

    HashMap<String, Integer> file_maps = new HashMap<String, Integer>();
    file_maps.put("img1", R.drawable.img1);
    file_maps.put("img12", R.drawable.img2);

    for (String name : file_maps.keySet()) {
        TextSliderView textSliderView = new TextSliderView(this);
        // initialize a SliderLayout
        textSliderView
                .description(name)
                .image(file_maps.get(name))
                .setScaleType(BaseSliderView.ScaleType.Fit);

        mDemoSlider.addSlider(textSliderView);
    }
    mDemoSlider.setPresetTransformer(SliderLayout.Transformer.ZoomOutSlide);
    mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
    mDemoSlider.setCustomAnimation(new DescriptionAnimation());
    mDemoSlider.setDuration(4000);
}

}

and here is my activity.xml

  <com.daimajia.slider.library.SliderLayout
    android:id="@+id/slider"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusable="true"
    android:onClick="onClickk"/>

<com.daimajia.slider.library.Indicators.PagerIndicator
    android:id="@+id/custom_indicator"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    />

Noone knows?


Interface can never instantiate in java,But What happened,when Interface is used return type

We know,interface can never instantiate in java. We can, however, refer to an object that implements an interface by the type of the interface

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)
{
    A test = new B();  //upcating
    //A test = new A(); // wont compile
}

But I have become confused when interface is used return type,such as

Method of DriverManager class which return Connection object

  public static Connection getConnection(String url);

Connection con=DriverManager.getConnection(String url);

Same problem

Method of Connection interface which return Statement object

  public Statement createStatement();

Statement stat=con.createStatement();

I cannot understand,what happened when interface is used return type.
Please help me by explain.

Thanks


Liquibase transaction demarcation

I have 2 examples of Liquibase changesets where the second statements are failing(trying to insert a record with existing primary key), but the first ones are successful:

Failing/no record in databasechangelog:

--changeset yura:2
insert into test2 values (4, 'test4');
insert into test2 values (2, 'test2');

Partially written, no record in databasechangelogg:

--changeset yura:2
insert into test2 values (4, 'test4');
ALTER TABLE test2 ADD name varchar(50);

When I try to run those statements on MySql directly, the behaviour is consistent for both because MySql(InnoDB) will wrap every statement in a separate transaction.
Why is Liquibase not consistent?


CSS Problems - 960.gs

I've decided to let tables out of my Web UIs but I'm suddenly having lots of trouble with CSS.

I've hacked a little bit into 960.gs and I've made my own grid with only 8 columns, here it is:

.grid {
    margin-left: auto;
    margin-right: auto;
    width: 960px;
}
.grid ._01,
.grid ._02,
.grid ._03,
.grid ._04,
.grid ._05,
.grid ._06,
.grid ._07,
.grid ._08 {
    display: inline;
    float: left;
    margin: 10px;
    position: relative;
}
.grid ._01 {
    width: 100px;
}
.grid ._02 {
    width: 220px;
}
.grid ._03 {
    width: 340px;
}
.grid ._04 {
    width: 460px;
}
.grid ._05 {
    width: 580px;
}
.grid ._06 {
    width: 700px;
}
.grid ._07 {
    width: 820px;
}
.grid ._08 {
    width: 940px;
}
.grid .clear {
    clear: both;
    display: block;
    height: 0px;
    overflow: hidden;
    visibility: hidden;
    width: 0px;
}

And here is the HTML:

<div class="grid">
    <div class="_05">
        <img src="../logo.png" alt="" width="450" height="60" vspace="50" />
    </div>
    <div class="_03" align="center">
      <form id="form1" name="form1" method="post" action="">
        <p>
          <label>Email
            <input type="text" name="textfield" id="textfield" style="margin-right: 0;" />
          </label>
        </p>
        <p>
          <label>Password
            <input type="text" name="textfield2" id="textfield2" />
          </label>
        </p>
      </form>
    </div>
    <div class="clear"></div>
    <div class="_05">
        <div class="box">
            <h2>grid, _05, box, h2</h2>
            <div class="content">grid, _05, box, content</div>
        </div>
    </div>
    <div class="_03">
        <div class="box green">
        <h2>grid, _03, box, h2</h2>
            <div class="content">
              <p>grid</p>
              <p>_03</p>
              <p>box</p>
              <p>content</p>
            </div>
        </div>
    </div>
    <div class="clear"></div>
    <div class="_05">
        <div class="box yellow">
            <h2>grid, _05, box, h2</h2>
            <div class="content">grid, _05, box, content</div>
        </div>
    </div>
    <div class="_03">
        <div class="box red">
            <h2>grid, _03, box, h2</h2>
            <div class="content">
              <p>grid</p>
              <p>_03</p>
              <p>box</p>
              <p>content</p>
            </div>
        </div>
    </div>
    <div class="clear"></div>
</div>

How can I make this...

bogus UI http://i33.tinypic.com/148md76.png

Look more like this? Specially, how can I change the position of the yellow box and the login form in the top?

mockup UI http://i36.tinypic.com/2upptua.png

Thanks in advance for all your input!


how to allow only one active session per user

I want to implement a code that enables only one session per user.
I use asp.net with forms authentication .

I read this post:
Limit only one session per user in ASP.NET

but I want to do the opposite, to disconnect all previous sessions.

here is my code:

void Application_Start(object sender, EventArgs e)
{
    Application["UsersLoggedIn"] = new System.Collections.Generic.Dictionary<string, string>(); }

when user logs in, I insert a record : username, sessionID.
if the username exists, I just update the sessionID

    void Application_BeginRequest(object sender, EventArgs e)
    {
        System.Collections.Generic.Dictionary<string, string> d = HttpContext.Current.Application["UsersLoggedIn"] as System.Collections.Generic.Dictionary<string, string>;
        if (d != null)
        {
            if (d.Count > 0)
            {
                    string userName = HttpContext.Current.User.Identity.Name;
                    if (!string.IsNullOrEmpty(userName))
                    {
                        if (d.ContainsKey(userName))
                        {
                            if (d[userName] != HttpContext.Current.Session.SessionID)
                            {
                                FormsAuthentication.SignOut();
                                Session.Abandon();
                            }
                        }
                    }
}
}

but I get empty HttpContext.Current.User.
I tried also "AuthenticatedRequest", but then I get null Session.

any idea please?


Cannot enable viewstate?

I have a web apllication with wizard control with 4 step index. Each having a dynamically editable grid which need to put only valid data & goto next.

In one step which have 2 columns which are not require to be editable because it has set its value from previous field by calculation, done with javascript.

But problem is that when we decalre these field as a enable false or read only mode then it works but can not able maintain state means its value goes off when we change the step index changed. (If that field are editable then it works ok.)

Also I tried it by use of label field but the same thing happen when the step changes label can not maintan its state (its value clears when step changes).

Please give me idea how to resolve this problem. Also each step has a dynamically created editable grid.

Thanks & Regards,
     Girish


Displaying error messages in WebSeal

I have an application in webseal. The problem is that when an error (403 or 404) comes, the error pages of webseal are not being displayed.


json schema validator throwing exception when empty array is present in response

I am getting following exception if I place dummy array. eg, in Security/RelatedSecurities/RelatedSecurities. I tried to build a json schema from the response where it is empty. But if I use json validator it gives sytax error "array must have atleast one element". So I used the dummy array elements. After that I do not get syntax error but the validation fails with following error. Actual not matching with expected.
I will be happy to share the response and json schema if anyone is willing to help.

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 org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:80)
at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:74)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:60)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:235)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247)
at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:598)
at com.jayway.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at com.jayway.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:760)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
at com.jayway.restassured.internal.ResponseSpecificationImpl.content(ResponseSpecificationImpl.groovy:92)
at com.jayway.restassured.specification.ResponseSpecification$content$0.callCurrent(Unknown Source)


GT06 GPS Module TCP server in Python

I am using python socketserver module to develop the GT06 server. Which will respond to the GPS GT06 module.

I am getting the Login Message 78 78 0d 01 03 58 73 50 70 57 91 97 00 11 ab 0d 0d 0a in HEX.

Upon receiving the value I am using encode('hex') so that I can parse the input and respond with appropriate Login Response:

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(1024)
        cur_thread = threading.current_thread()
        time_rec = time.strftime("%b %d %Y %H:%M:%S", time.gmtime(time.time()))
        print "received data from client socket %s :%s" % (time_rec, data.encode("hex"))

When I am sending the response first I generate the login response as 78 78 05 01 00 11 c9 5d 0d 0a and then convert it to HEX values using decode('hex') and then send those value to GT06 terminal back:

login = LoginMessagePacket(gps_input=data.encode('hex'))
resp = login.response()
print "Sent to client: %s" % login.response()
self.request.sendall(resp)

LoginMessagePacket is the class which handles and parsing and validation of Login Message by terminal.

My problem is even I am sending the response as per the protocol I am not getting the GPS data and terminal keep sending the login request packet.

P.S. I tested the AWS server if server is responding to the TCP request properly and I am sure server is sending the response.

Any help is much appreciated.

Thanks in advance.


How to eliminate the use of this class variable

Ruby 2.0.0, Rails 4.0.3, Windows 8.1 Update, PostgreSQL 9.3.3

I have built an XLog class that allows me to write records to PostgreSQL from within any controller in my application.  However, it's built around the use of a class variable.  I am wondering whether I can convert this to an instance variable.

In the ApplicationController, I instantiate the class variable and write the first record:

  @@xaction = XLog.new
  @@xaction.info(
      controller: self.class.name,
      action:     "start",
      status:     "success"
  )

At any point in the application, I can reference @@xaction.info with a hash to log the success or failure of any transaction.  It works...

XLog is:

class XLog < ActiveRecord::Base
  def info hash
    logger.info "XLog " << hash.collect { |key, value| "#{key}: #{value}; "}.join  # map?
    XLog.create(
        controller: hash[:controller],
        associate:  hash[:associate],
        proxy:      hash[:proxy],
        object:     hash[:object],
        value:      hash[:value],
        action:     hash[:action],
        status:     hash[:status],
        message:    hash[:message]
    )
  end
end


How to keep the DropDown list opened after PostBack in ASP

I have a DropDown like below:-

<telerik:RadComboBox ID="RadComboBox" runat="server"  EmptyMessage="Select"  DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="id" ShowMoreResultsBox="true" EnableVirtualScrolling="true" HighlightTemplatedItems="true" ItemsPerRequest="10" >
                <HeaderTemplate>
                    <table style="width: 500px">
                        <tr>
                            <td style="font-weight: bold; width: 400px"><asp:LinkButton ID="LinkButton1" runat="server" ReadOnly="true" Font-Bold="true" Text="Name" OnClick="LB_Click" ></asp:LinkButton></td>
                            <td style="font-weight: bold; width: 100px">ID</td>
                        </tr>
                    </table>
                </HeaderTemplate>
                <ItemTemplate>
                    <table style="width: 500px">
                        <tr>
                            <td style="width: 400px"><%#DataBinder.Eval(Container.DataItem, "name")%></td>
                            <td style="width: 100px"><%#DataBinder.Eval(Container.DataItem, "id")%></td>
                        </tr>
                    </table>
                </ItemTemplate>
            </telerik:RadComboBox>
            <asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:SqlConnectionString %>" ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM table1 order by name asc" />

When I run the application and click on the RadComboBox, then the DropDown List opens and shows the items in the  DropDown list.

Now when I click LinkButton1 (i.e Name) there is a PostBack of the page, then the opened DropDown list closes automatically and again I have to click on my RadComboBox to open the DropDown list,

Is there a way  to keep the DropDown list opened, after the postback of the page ?

Could anyone please help .  ThankYou.


Retrieve Boolean value of 'isAVideo' Key in Parse

Users of my app can upload images or videos. If the user uploads a video, a still image representation is also uploaded to the @"images" column in parse. Those files populate a Table View of still images.
I created a third column to manage a boolean value indicating if the object isAVideo (True or False).

In my Table View feedcell.m file I have a method to set the feed Item like so

- (void)setFeedItem:(PFObject *)feedItem
{
NSLog(@"setting feed item");
_feedItem = feedItem;

PFUser *user = [feedItem objectForKey:@"user"];
[_usernameButton setTitle:user.username
                 forState:UIControlStateNormal];

PFQuery *query = [PFQuery queryWithClassName:@"tfeed"];

[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
    if (!object) {
        // Found nothing
    } else {
        BOOL isVideo = [[object objectForKey:@"isAVideo"]boolValue];
        if (isVideo == true) {
            NSLog(@"Object is a VIDEO");
            _pictureView.image = self.feedImage;
        // Create play button
        UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [playButton addTarget:self
                       action:@selector(playVideo:)
             forControlEvents:UIControlEventTouchUpInside];
        // Set the play image
        UIImage *playImage = [UIImage imageNamed:@"playButtonImage.pgn"];
        [playButton setImage:playImage forState:UIControlStateNormal];
        playButton.frame = CGRectMake(0, 0, 375, 375);
        [_pictureView addSubview:playButton];
        [_pictureView bringSubviewToFront:playButton];

        } else {
            NSLog(@"Object is not a video");
            _pictureView.image = self.feedImage;
        }
    }
}];
}

My goal is to add a play button when the object is a video, but the button is added to all objects regardless of it Bool value.

I think my query and/or conditional statement must be wrong.

EDIT: removed line:

[query whereKey:@"isAVideo" equalTo:[NSNumber numberWithBool:YES]];


Setting near mode for depth cam in Kinect using OpenNI

I have been unable to find out how i can set the Kinect depth mode to near (40-300mm) using OpenNi. I am programming in C++ and would like to keep using the OpenNi libraries for retreiving the depth data, however i cannot find any property of setting that i should use for changing modes.


How to add arguments without key, to add only value to the body of ConnectionRequest

I want to add a Json object to ConnectionRequest as value without key. I know that if use standard addArgument(key,value) -

addArgument("json","{JsonObject}")

in the body of request will be

json={JsonObject}

But I need to add only JsonObject without key and "=" symbol.

{JsonObject}

Is there any standard solution?
One more question Is there any class in Lwuit to create JsonObject similar to json.org.me
Thanks


Sorting in ServiceNow - First by priority and then by updated Timestamp

In a list view of the incident table in service now, I can easily sort by any given column. If I Filter my Incidents by priority and show only the "high" and "very high" open incidents I can sort that by priority. But unfortunately I didn't find a way to sort first by priority and then by updated. Meaning first I get the very high incidents ordered by the updated timestamp and then the high incidents by priority.

Is that possible to do? I would like to have this ordering in a report which I send out as .pdf.


App crashes when I try to switch from fragment to activity

I have 3 fragments in Main Activity and one of them has a button which I want to start Activity 2. I created interface in the third fragment and extended the Main Activity with it, but I cannot figure out why my app still crashes. I lost 2 days on that issue and its driving me nuts. My Activity 2 is declared in the Manifest file. Please help!!!

Profile.Fragment:

public class ProfileFragment extends Fragment implements View.OnClickListener {

    private TextView tv_name,tv_email,tv_message;
    private SharedPreferences pref;
    private AppCompatButton btn_change_password,btn_logout, btn_ok;
    private EditText et_old_password,et_new_password;
    private AlertDialog dialog;
    private ProgressBar progress;

    public interface OnProfileListener{
        void onProfileButtonOkClicked();
    }

    private OnProfileListener mCallBack;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_profile,container,false);
        initViews(view);
        return view;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        pref = getActivity().getPreferences(0);
        tv_name.setText("Здравей, "+pref.getString(Constants.NAME,"")+"!");
        tv_email.setText(pref.getString(Constants.EMAIL,""));
        btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallBack.onProfileButtonOkClicked();
            }
        });

    }

//I have API16 and I cannot run my app with
//onAttach(Context context) because it is supported by API>=23,
//but Android deprecated  API16, so that is why I  use both Activity and Context

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (activity instanceof OnProfileListener){
             mCallBack = (OnProfileListener) activity;
        } else {
            throw new RuntimeException(activity.toString()
                    + " must implement OnProfileListener");
        }
    }}
    @TargetApi(23)
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnProfileListener) {
            mCallBack = (OnProfileListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnProfileListener");
        }
    }

...
    private void initViews(View view){

        tv_name = (TextView)view.findViewById(R.id.tv_name);
        tv_email = (TextView)view.findViewById(R.id.tv_email);
        btn_change_password = (AppCompatButton)view.findViewById(R.id.btn_chg_password);
        btn_logout = (AppCompatButton)view.findViewById(R.id.btn_logout);
        btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
        btn_change_password.setOnClickListener(this);
        btn_logout.setOnClickListener(this);

    }

   //Here I go to other fragment in Main Activity flawlessly, wish I could manage to go Activity2 with the same ease

    private void goToLogin(){

        Fragment login = new LoginFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame,login);
        ft.commit();
    }
}

MainActivity.java:

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;

public class MainActivity extends FragmentActivity implements
        ProfileFragment.OnProfileListener{

    private SharedPreferences pref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getPreferences(0);
        initFragment();
        onProfileButtonOkClicked();
    }
    @Override
    public void onProfileButtonOkClicked() {

        Intent intent=new Intent(this, Activity2.class);
        startActivity(intent);
    }

    private void initFragment(){
        Fragment fragment;
        if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){
            fragment = new ProfileFragment();

        }else {
            fragment = new LoginFragment();
        }
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame,fragment);
        ft.commit();
    }


How to make rounded percentages add up to 100%

Consider the four percentages below, represented as float numbers:

    13.626332%
    47.989636%
     9.596008%
    28.788024%
   -----------
   100.000000%

I need to represent these percentages as whole numbers. If I simply use Math.round(), I end up with a total of 101%.

14 + 48 + 10 + 29 = 101

If I use parseInt(), I end up with a total of 97%.

13 + 47 + 9 + 28 = 97

What's a good algorithm to represent any number of  percentages as whole numbers while still maintaining a total of 100%?

Edit: After reading some of the comments and answers, there are clearly many ways to go about solving this.

In my mind, to remain true to the numbers, the "right" result is the one that minimizes the overall error, defined by how much error rounding would introduce relative to the actual value:

        value  rounded     error               decision
   ----------------------------------------------------
    13.626332       14      2.7%          round up (14)
    47.989636       48      0.0%          round up (48)
     9.596008       10      4.0%    don't round up  (9)
    28.788024       29      2.7%          round up (29)

In case of a tie (3.33, 3.33, 3.33) an arbitrary decision can be made (e.g. 3, 4, 3).


javascript: changing "multiple" attribute of the "select" element does not work

Windows 7 64 bit, Chrome version 61.0.3163.100

I have a html page with a listbox:

<select id='lst' multiple>...</select>

I need to disable multiple items selection for this listbox.
I have a javascript function with this code:

lst = document.getElementById('lst');
lst.multipe = false;

I have checked in the debugger - the value changed to "false".
But in another function called "onclick", it is "true" again.
And multiple items could be selected with [shift] or [ctrl] pressed.


Send command in Fiscal Epson tmT81 C#

I trying to print in a fiscal printer EPSON TMT81 i have example code in VB and i need to do the same in C#, im using EpsonFPHostControl. OCX 1.9

The basic to work is sendcommand to the printer by COM port, i connect to the port with no problem but i cant send command by the port.

To send commnad in VB the code is:

        '*** PROBAR CONEXION CON IMPRESOR FISCAL ***
        '*** CHEQUEA  ESTADO  DE IMPRESOR FISCAL ***
        EpsonFPHostControl1.AddDataField (Chr$(&H0) & Chr$(&H1))
        EpsonFPHostControl1.AddDataField (Chr$(&H0) & Chr$(&H0))

        '*** ENVIA COMANDO FISCAL ***
        EpsonFPHostControl1.SendCommand

Im trying to do the same in C#:

        //*** PROBAR CONEXION CON IMPRESOR FISCAL ***
        //*** CHEQUEA  ESTADO  DE IMPRESOR FISCAL ***
        EpsonFPHostControl1.AddDataField("H0H1");
        EpsonFPHostControl1.AddDataField("H0H0");

        //*** ENVIA COMANDO FISCAL ***
        EpsonFPHostControl1.SendCommand()

But it doesnt Work well :/, the fiscal printer receibe the command but return code 513 invalid frame of comand (frame de comando invalido)

i apreciate some help.


How do I convert config file to dict in Python?

server 192.168.10.10 443 {
    protocol TCP

    _server 192.168.10.1 443 {
        weight 1
        SSL_GET {
            url {
                path /
            }
            connect_timeout 3
        }
    }
}


Prevent user to go back, but filter is not working

I have a payment form. When user submit the form the payment process runs successfully, but clicking the back button brings user to same form. I want to expire the form after successful submission, to prevent user from multiple payment (in case user goes back and submit form).
Following Prevent user from going back tutorial, I added the filter but it's not working for me. What am I doing wrong? Here is what I added for filtering.

<filter>
    <filter-name>paymentFilter</filter-name>
    <filter-class>path to PaymentFilter class</filter-class>
</filter>
<filter-mapping>
    <filter-name>paymentFilter</filter-name>
    <url-pattern>/order/*/payment</url-pattern>
</filter-mapping>

and my filter class is

public class PaymentFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        httpServletResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        httpServletResponse.setDateHeader("Expires", 0); // Proxies.
        System.out.println("In filter");
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

}

I have added a System.out.println("In filter") but I can't see its output ("In filter") on console after running the page.

When I use the URL pattern as /* the System.out prints on console,

<url-pattern>/*</url-pattern> (it works as expected)

but when I change the URL pattern to /order/*/payment (* is order id what changes for each order). then System.out does not print anything on console.

<url-pattern>/order/*/payment</url-pattern> (it doesn't work)

I am using spring mvc, apache, tomcat7.0


How to access Server side validation errors on Client side and change css class

I am workig on a MVC project which is using Jquery for client side validation, like below

jQuery.validator.defaults.highlight = function (element, errorClass, validClass) {
            if ($(element).attr('readonly')) {
                return;
            }
            element = this.findByName(element.name);
            element.parent()
                .addClass('invalid')
                .removeClass('valid');
        };
        jQuery.validator.defaults.unhighlight = function (element, errorClass, validClass) {

            element = this.findByName(element.name);
            element.parent()
                .removeClass('invalid')
                .addClass('valid');
            element.nextAll('.error').hide();
        };

With this way of validation we are showing error message which looks like this

But i have a model with a few fields which needs to be validated on the server side, so when i Post the Form i need to get the list of fields which failed validation on the server side and when i load the view again i need to change the css of the failed fields and show the error to the user, How can i do this?


Upload image does not work in Android app but working in Postman Plugin in Codeigniter

I face the problem like as follow:

I develop API in codeigniter for upload image into specific folder of server. When i check in postman that works fine. But, when i check with android app that does not work fine.

Please give me suggestion.

Thanks in advance.

My code as below:

public function updateimage_post() {
    if(!$this->post('UserID')) {
        $status = [
            ['status' => 400 ,  'message' => 'UserID is required.'],
        ];
        $this->response($status, REST_Controller::HTTP_BAD_REQUEST);
    } else {
        $this->db->where(array('ID' => $this->post('UserID')));
        $db_result = $this->db->get('userregistration');

        if ($db_result && $db_result->num_rows() > 0) {
            if(isset($_FILES['ProfilePicture']['name'])) {
                $info = pathinfo($_FILES['ProfilePicture']['name']);
                $ext = $info['extension'];
                if (($ext == "GIF" || $ext == "PNG" || $ext == "JPG" || $ext == "jpg" || $ext == 'gif' || $ext == 'png' || $ext == 'jpeg') && ($_FILES["ProfilePicture"]["type"] == "image/PNG" || $_FILES["ProfilePicture"]["type"] == "image/GIF" || $_FILES["ProfilePicture"]["type"] == "image/JPG" || $_FILES["ProfilePicture"]["type"] == "image/jpg" ||$_FILES["ProfilePicture"]["type"] == "image/jpeg" || $_FILES["ProfilePicture"]["type"] == 'image/gif' || $_FILES["ProfilePicture"]["type"] == 'image/png') && ($_FILES["ProfilePicture"]["size"] < 30485760)) {
                    $file = $info['filename'];
                    $filename = 'frontuser' . '_' . uniqid() . '.' . $ext;
                    $target = './uploads/frontusers/' . $filename;
                    $file = $_FILES['ProfilePicture']['tmp_name'];
                    if (move_uploaded_file($file, $target)) {
                        $data = array(
                            'ProfilePicture' => $filename,
                            'ModifiedOn' => date('Y-m-d H:m:s'),
                        );
                        $result = $this->db->update('userregistration', $data, array('ID' => $this->post('UserID')));
                    } else {
                        $status = ['status' => 201 ,  'message' => 'Image not uploaded.'];
                        $this->response($status, REST_Controller::HTTP_OK);
                    }
                } else {
                    $status = ['status' => 201 ,  'message' => 'File is invalid.'];
                    $this->response($status, REST_Controller::HTTP_OK);
                }
            } else {
                $status = ['status' => 201 ,  'message' => 'Please Select image.'];
                $this->response($status, REST_Controller::HTTP_OK);
            }

            if($result) {
                $status = [
                    'status' => 200,
                    'message' => 'Profile Picture Update Successfully',
                    ];
            } else {
                $status = [
                    'status' => 201,
                    'message' => 'Something went wrong !!',
                    ];
            }
            $this->set_response($status, REST_Controller::HTTP_OK);
        } else {
            $status = [
                    'status' => 201,
                    'message' => 'UserID does not exist !!',
                    ];
            $this->set_response($status, REST_Controller::HTTP_OK);
        }
    }
}


Auto create VPN account on CENTOS VPS server, with successful purchase of VPN subscription

I was wondering if anyone knows if this would be the correct approach for going about this process.

I am making a VPN service as a project to further my computer programming background and portfolio.

I was wondering, after a successful verification purchase for a VPN subscription on www.example.com, would the correct route to auto create the subscribers VPN account be to:

Fire off a .sh (shell script) hosted on the server with PHP variables passed to the script for the $username & $password. Which in return will run on the server and create the subscribers access account.


Using Semantic merge as diff tool in Perforce

I'm trying to set up SemanticMerge as my diff tool for C# in Perforce.

I've configured perforce with the exe and with the arguments -s=%1 -d=%2 -l=csharp

But when I try to diff a C# file I receive the error:

Could not find file c:\Program Files Perforce\%1

The selected file is not in that location (nor is its filename %1)...

I am no doubt being slow and am trying to RTFM but am also hoping someone here can see what I'm missing


How to export configuration of maas (Metal as a service)

Since few days, i make some test of automatic tool deployement of Canonical: Maas. I think it's very prometise. But if I need to save my configuration, how I can make it ? And how I can import it ? By example, to make a migration from a maas1.9 to maas 2.0. I have see nothing on the internet, and the maas cli command "maas user maas get-config" doesn't help.

Thanks.

Regards.

jmc


Stored Proc and WCF Data Services

I've got a WCF Data Service setup and can access the table data through the browser url.

Have created a simple Stored Proc which takes in a parameter and then returns some columns from various tables via Joins - how can I consume this?


Why Should I provide an alternative style for 21 api knowing that AppCompat is made for compatibility

Some material design  are only supported starting from android 21 API  , so for this purpose we need to provide alternative styles that will work on devices running earlier version  . (like they say in documentation ) .

for example  :

res/values/styles.xml
res/values-v21/styles.xml

They also have mentioned V7 support library that includes Material design styles .

From here I am little bit confused !
Suppose that my default theme extends from Theme.AppCompat .

Why Should I provide an alternative style for 21 api knowing that  Theme.AppCompat is made for compatibility ?


len of varbinary

would someone please explain why select len(0x0a000b) returns 3? does len count bytes? and why select left(0x0a000b, 1) returns nothing? i expected 0x0a (if len counts bytes)...

i am using mssql 2005

thanks
konstantin


how can ı add more button on my android application which already includes a scrollview?

l have a android  application that includes a  xml file that includes a scrolview and  ı added some buttons ın this layout and ı want to add more buttons (when ı add on graphical layout content get defaced )  but ı can t add more here is also my xml file

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DualarMainActivity" >

 <RelativeLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@drawable/dualarbackround"
     android:orientation="vertical" >

<Button
    android:id="@+id/button6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button5"
    android:layout_alignRight="@+id/button2"
    android:layout_below="@+id/button5"
    android:layout_marginTop="20dp"
    android:text="Button" />

<Button
    android:id="@+id/button3"
    android:layout_width="248dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:text="Button" />

<Button
    android:id="@+id/button2"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button3"
    android:layout_below="@+id/button1"
    android:layout_marginTop="20dp"
    android:text="Button" />

<Button
    android:id="@+id/button1"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/button3"
    android:layout_marginTop="240dp"
    android:text="Button" />

<Button
    android:id="@+id/button4"
    android:layout_width="256dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button3"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="20dp"
    android:text="Button" />

<Button
    android:id="@+id/button5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button3"
    android:layout_alignRight="@+id/button4"
    android:layout_below="@+id/button4"
    android:layout_marginTop="20dp"
    android:text="Button" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/bismillah" android:contentDescription="TODO"/>

<Button
    android:id="@+id/button7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_alignRight="@+id/button1"
    android:layout_below="@+id/imageView1"
    android:layout_marginTop="50dp"
    android:text="Button" />

<Button
    android:id="@+id/button8"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/button7"
    android:layout_alignLeft="@+id/button4"
    android:layout_alignRight="@+id/button7"
    android:layout_marginBottom="65dp"
    android:text="Button" />

      </RelativeLayout>
  </ScrollView>


How can I define a composite key in serverless.yml for DynamoDB?

I am trying to define a dynamodb table that has a 3 column composite key. Is this possible?

I've seen examples and tutorials that have code like this:

resources:
  Resources:
    TodosDynamoDbTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

But that only has a single column and a single key. My table looks like this:

  Properties:
    AttributeDefinitions:
      - AttributeName: id
        AttributeType: N
      - AttributeName: server
        AttributeType: S
      - AttributeName: room
        AttributeType: S
      - AttributeName: friendlyName
        AttributeType: S

I want a key on id, server and room. A user can be in multiple rooms on the same server and in multiple rooms on multiple servers. But, across the three keys, it will always be unique.

I don't know how to define the KeySchema part. Any help?


Bash equivalent to Python's string literal for utf string conversion

I'm writing a bash script that needs to parse html that includes special characters such as @!'ó. Currently I have the entire script running and it ignores or trips on these queries because they're returned from the server as decimal unicode like this: &#39;. I've figured out how to parse and convert to hexadecimal and load these into python to convert them back to their symbols and I am wondering if bash can do this final conversion natively. Simple example in python:

print ur"\u0032" ur"\u0033" ur"\u0040"

prints out

23@

Can I achieve the same result in Bash? I've looked into iconv but I don't think it can do what I want, or more probably I just don't know how.

Here's some relevant information:

Python String Literals

Hex to UTF conversion in Python

And here are some examples of expected input-output.

Ludwig van Beethoven - 5th Symphony and 6th Symphony &#39;&#39;Pastoral&#39;&#39; - Boston Symphony Orchestra - Charles Munch

Ludwig van Beethoven - 5th Symphony and 6th Symphony ''Pastoral'' - Boston Symphony Orchestra - Charles Munch

&#1040;&#1083;&#1080;&#1089;&#1040; (Alisa) - &#1052;&#1099; &#1074;&#1084;&#1077;&#1089;&#1090;&#1077;. &#1061;&#1061; &#1083;&#1077;&#1090; (My vmeste XX let)

АлисА (Alisa) - Мы вместе. ХХ лет (My vmeste XX let)


edGet the value of element inside ng-repeat dynamically

I am generating 10 elements using ng-repeat.

Please help me to get the value of each span tag dynamically so that I can write conditions accordingly.

Below is my html code.

I tried

 $('span').attr('value');

<span ng-repeat="n in [].constructor(7) track by $index" class="dot" value="{{$index+1}}">{{$index+1}}</span>


texture2d rectangle XNA wont initialize

I have a rather basic Texture2D name rect and I am just trying to initialize it. It tells me that a field initializer cannot reference the non-static field, method or property "graphics"

     public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    //my variables and stuff I delcare

    //texture we can render
    Texture2D myTexture;

    //set coords to draw the spirte
    Vector2 spritePos = new Vector2(300.0f, 330.0f);

    //some info about motion
    Vector2 spriteSpeed = new Vector2(0f, 0f);

    KeyboardState oldState;
    double boost = 15;

    //boost level rectange this is the issue below+
    Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }


ToList slow performance vs foreach slow performance

I am building program that use DataBase with 3 tables(Worker, Task, TaskStep)
and i have a method that get date and build report for specific worker
of the task and there steps for the specific day.

The data base structure is as follow:

MySQL 5.2

Worker table columns:

workerID(VARCHAR(45)),
name(VARCHAR(45)),
age(int),
...

Tasks table columns:

TaskID(VARCHAR(45)),
description(VARCHAR(45)),
date(DATE),
...

TaskSteps table columns:

TaskStepID(VARCHAR(45)),
description(VARCHAR(45)),
date(DATE),
...

No indexing on any table

The problem is thats it is very very slow!! (~ 20 seconds)

Here is the code:

using WorkerDailyReport = Dictionary<task, IEnumerable<taskStep>>;

private void Buildreport(DateTime date)
{
    var report = new WorkerDailyReport();

    // Load from DB
    var sw = new Stopwatch();
    sw.Start();

    var startOfDay  = date.Date;
    var endOfDay    = startOfDay.AddDays(1);
    var db          = new WorkEntities();

    const string    workerID   = "80900855";

    IEnumerable<task> _tasks = db.task
                    .Where(ta =>    ta.date     >= startOfDay   &&
                                    ta.date     <  endOfDay     &&
                                    ta.workerID == workerID)
                    .ToList();

    sw.Stop();
    Console.WriteLine("Load From DB time - " + sw.Elapsed +
                      ", Count - "           + _tasks.Count());

    // Build the report
    sw.Restart();

    foreach (var t in _tasks)
    {
        var ts = db.taskStep.Where(s => s.taskID == task.taskID);

        report.Add(t, ts);
    }

    sw.Stop();
    Console.WriteLine("Build report time - " + sw.Elapsed);

    // Do somthing with the report
    foreach (var t in report)
    {
        sw.Restart();

        foreach (var subNode in t.Value)
        {
            // Do somthing..
        }

        Console.WriteLine("Do somthing time - " + sw.Elapsed +
                          ", Count - " + t.Value.Count());
    }
}

As u can see i put StopWatch in each part to check what take so long
and this is the results:

1)

If i run the code as above:

Console:

Load From DB time - 00:00:00.0013774, Count - 577

Build report time - 00:00:03.6305722

Do somthing time - 00:00:07.7573754, Count - 21

Do somthing time - 00:00:08.2811928, Count - 11

Do somthing time - 00:00:07.8715531, Count - 14

Do somthing time - 00:00:08.0430597, Count - 0

Do somthing time - 00:00:07.7867790, Count - 9

Do somthing time - 00:00:07.3485209, Count - 39

.........

the inner foreach run takes about 7-9!! Sec to run over no more then
40 record.

2)

If i change only one thing, Add .ToList() after the first query
when i load the worker tasks from the Data Base it changes
everithing.

Console:

Load From DB time - 00:00:04.3568445, Count - 577

Build report time - 00:00:00.0018535

Do somthing time - 00:00:00.0191099, Count - 21

Do somthing time - 00:00:00.0144895, Count - 11

Do somthing time - 00:00:00.0150208, Count - 14

Do somthing time - 00:00:00.0179021, Count - 0

Do somthing time - 00:00:00.0151372, Count - 9

Do somthing time - 00:00:00.0155703, Count - 39

.........

Now the load from DataBase takes lot more time, 4+ sec.
But the Built report time is about ~1ms
And each inner foreach takes ~10ms

The first way is imposible(577 * ~8 seconds) and the seconde option
is also very slow and i cant see y.

Any idea what happening here?

1) Why the ToList() so slow ?

2) Why without the ToList(), The inner foreach and the Build report is slowing?

How can i make it faster?

thnx.


What does this statement mean in C#?

What does if ((a & b) == b) mean in the following code block?

if ((e.Modifiers & Keys.Shift) == Keys.Shift)
{
    lbl.Text += "\n" + "Shift was held down.";
}

Why is it not like this?

if (e.Modifiers == Keys.Shift)
{
    lbl.Text += "\n" + "Shift was held down.";
}


Convert log message timestamp to UTC before sroring it in Elasticsearch

I am collecting and parsing Tomcat access-log messages using Logstash, and am storing the parsed messages in Elasticsearch.
I am using Kibana to display the log messges in Elasticsearch.
Currently I am using Elasticsearch 2.0.0, Logstash 2.0.0, and Kibana 4.2.1.

An access-log line looks something like the following:

02-08-2016 19:49:30.669 ip=11.22.333.444  status=200  tenant=908663983 user=0a4ac75477ed42cfb37dbc4e3f51b4d2 correlationId=RID-54082b02-4955-4ce9-866a-a92058297d81  request="GET /pwa/rest/908663983/rms/SampleDataDeployment HTTP/1.1" userType=Apache-HttpClient requestInfo=- duration=4 bytes=2548 thread=http-nio-8080-exec-5 service=rms itemType=SampleDataDeployment itemOperation=READ dataLayer=MongoDB incomingItemCnt=0 outgoingItemCnt=7

The time displayed in the log file (ex. 02-08-2016 19:49:30.669) is in local time (not UTC!)

Here is how I parse the message line:

filter {

        grok {
            match => { "message" => "%{DATESTAMP:logTimestamp}\s+" }
        }

        kv {}

        mutate {
            convert => { "duration" => "integer" }
            convert => { "bytes" => "integer" }
            convert => { "status" => "integer" }
            convert => { "incomingItemCnt" => "integer" }
            convert => { "outgoingItemCnt" => "integer" }

            gsub => [ "message", "\r", "" ]
        }

        grok {
            match => { "request" => [ "(?:%{WORD:method} %{NOTSPACE:request}(?: HTTP/%{NUMBER:httpVersion})?)" ] }
            overwrite => [ "request" ]
        }

}

I would like Logstash to convert the time read from the log message ('logTimestamp' field) into UTC before storing it in Elasticsearch.

Can someone assist me with that please?

--

I have added the date filter to my processing, but I had to add a timezone.

    filter {
            grok {
                match => { "message" => "%{DATESTAMP:logTimestamp}\s+" }
            }

            date {
               match => [ "logTimestamp" , "mm-dd-yyyy HH:mm:ss.SSS" ]
               timezone => "Asia/Jerusalem"
               target => "logTimestamp"
            }

            ...
   }

Is there a way to convert the date to UTC without supplying the local timezone, such that Logstash takes the timezone of the machine it is running on?

The motivation behind this question is I would like to use the same configuration file in all my deployments, in various timezones.