mardi 22 mars 2016

handling large amounts of data using the google maps api

I'm designing an android application where a user can enter there address and it will fetch a list of bars/clubs/eateries within a 300 miles radius.

The way it currently works is, The user inputs his/her address and the app sends a call to a RESTful service(asp) which then selects every bar/club/eaterie and checks there distance from the users location, puts any within a 300 mile distance into an array and returns the result as json once it's finished.

The problem is this is really slow because it has to select every bar/club/eaterie from the database and calculate the distance(I have roughly 20k rows of data)

The average response time for the entire process (user clicking search to having the information displayed on there phone) is about 6-8 seconds, I would like to get it down to about 1-2 seconds

Is there a better way to go about this ? having to select all of the records and check the distance for each one is what's causing the issue.



handling large amounts of data using the google maps api

Is there a plugin that cycles parameters for a Jenkins Build?

I'm looking to cycle through a set of parameters for my Jenkins build. I have 3 particular permutations of parameters that I'd like the build to cycle through. Is there an easy way to do this? Or is there maybe a plugin that can achieve this for me?

(If you don't quite understand I want Build1 to build using Param A, then the next build that gets triggered will use Param A and Param B. Effectively cycling through the params)

NOTE: I don't want a post-build thing that executes the build again right away, I want it to follow the same timer and polling solution I have set up. I just want the params to change between builds.

Thanks in advance



Is there a plugin that cycles parameters for a Jenkins Build?

C error handling withing an application

The post Error handling in C code describes the error handling in C library, however I'm wondering how to handle errors within your own application.

I'm about to write my first C application, and I'm considering of two error handling styles: returning error code and returning error messages.

// error code style
#define INTERNAL_ERROR 3
int foo(void)
{
   int rc = third_party_lib_func();
   if (rc) {
       return INTERNAL_ERROR;
       // pro: looks nice and clean, everyone talks about error code
       // con: it is hard to debug, what error comes from the third 
       // party function?
   }
   return 0;
}

// error message style
char *foo(void)
{
    int rc = third_party_lib_func();
    if (rc) {
        char *errstr = third_party_lib_strerror(rc);
        return errstr;
        // pro: golang style, easy to check by foo() == NULL,
        //      easy to debug
        // con: maybe it is an rare error handling approach?
    }
    return NULL;
}

What is your opinion? And I'm wondering what is the most common way used in the real world application? Thanks.



C error handling withing an application

KnockoutJS, style binding with a 2D array?

So I am working with a JSON object of CSS attributes/divs, something like:

"#myDiv": {
    "position": "absolute",
    "max-height": "225px"
  },

And I am binding this object to a div using KnockoutJS's style binding:

<!-- ko with: $root.Styles['#myDiv'] -->
     <div data-bind="style:{
         position: position,
         maxHeight: $data['max-height']
       }"></div>
<!-- /ko -->

Position binds fine, and any other properties that do not have to be accessed explicitly are OK as well. Is it possible to bind something like $data['max-height'] within a KnockoutJS style binding?

*I'd also like to note that I can succesfully bind $data['max-height'] to a text field, but it always fails with a syntax error when binding a style.

Thoughts? :)



KnockoutJS, style binding with a 2D array?

Copy files in addition to project primary output using MSBuild project references?

I have a project that is referenced by many dependent projects, and some files in that project that must be in the binary directory of the dependent projects for the dependent projects to run.

Currently, I have several custom AfterBuild targets defined: one in the referenced project to copy the necessary files to a shared location, and then one in each of the dependent projects to reach out and copy the files from the shared location to their bin directories. This works, but it's annoying to maintain and it feels brittle and hacky.

What I would like to achieve is to get my files worked into the primary project outputs for the referenced project (i.e. alongside the .dll and .pdb), such that the files are automatically copied to the dependent projects' output directories at build time via the MSBuild ProjectReference.

Is this possible? If so, what is the mechanism by which primary outputs are discovered and to which itemgroups must I add my files? Is MSBuild "hardcoded" to look only for .dll and .pdb?

For reference, I would consider myself somewhere above an MSBuild novice, but far below an MSBuild expert. I've read Hashimi's "Inside the Microsoft Build Engine," understood it mostly, and I've been able to dig through the MS targets files a couple of times for other tasks, with moderate success. This problem is beyond me so far, though.

Also, I have reviewed this similar-looking question, but it doesn't address project references; only producing additional files with a project.



Copy files in addition to project primary output using MSBuild project references?

Looping a function over columns with different number of rows in VBA

I am dealing with a large dataset where every third column contains values for which I need to perform a function that takes value of 1 if it is positive than 0 and value of -1 if it is negative. Writing the function itself is no problem, but the dimensions of the data matrix are large and the columns are not of equal length. Thus I would need to be able to write a code that loops over the columns, performing the task, and saves the results in another matrix with equal number of colummns and rows of the same length. To be more concrete, an example of the dataset I am dealing with and what I want to achieve:

x1;x2;x3;x4
1;-1;2;4
-5;1;2;-1
1; ;2;1
3; ; ;-4
5; ; ; 
6; ; ;

And transfer this into:

y1;y2;y3;y4
1;-1;1;1
-1;1;1;-1
1; ;1;1
1; ; ;-1
1; ; ;
1; ; ;

x's and y's need to be on the same row.

Thank you in advance!



Looping a function over columns with different number of rows in VBA

mapping elements returns the SQL statement to Java class

I would like to do the mapping elements (graphical user interface), which returns the SQL statement to Java class. I am a beginner in java. Is such a thing is at all feasible? If so, any tips?



mapping elements returns the SQL statement to Java class

Convert pyaudio.paint16 to float

I have data obtained by simple pyAudio recording:

"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""

import pyaudio
import wave

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
            channels=CHANNELS,
            rate=RATE,
            input=True,
            frames_per_buffer=CHUNK)

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
  data = stream.read(CHUNK)
  frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

and I need to process these in numpy (and not to be converted back). So I need to convert from pyaudio.paInt16 (or 24 and so on...) to something more manageable like float or double.

Is there a simple way?



Convert pyaudio.paint16 to float

Rotating header images not working anymore

The rotating banner at the top right of this page: http://ift.tt/1XL3LFu has stopped working in this version: http://ift.tt/1Ry4Sdg And I cannot see why. Any thoughts are appreciated.



Rotating header images not working anymore

row() return null for specific field

Im trying to save specific field from a record into a session, for my user-role. The problem here is i cannot take any other field except nama.

controller/verify_login

public function index(){
    $this->load->model('verify_login_model');
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $result = $this->verify_login_model->verify($username, $password);
    if($result == $username) {



        $name = $this->verify_login_model->getinfo($username);
        $this->session->set_userdata('logged_in', TRUE);
        $this->session->set_userdata('username', $username);
        $this->session->set_userdata('name', $name);

        $this->load->view('home_view');






    } else {
        redirect('login');
    }

model/verify_login_model

function verify($username, $password){
    $this->db->select('username', 'password');
    $this->db->from('tb_user');
    $this->db->where('username', $username);
    $this->db->where('password', MD5($password));
    $this->db->limit(1);

    $query = $this->db->get();
    if($query->num_rows()==1) {
        return $username;
    } else {
        return false;
    }
}

function getinfo($username) {
    $this->db->select('nama', 'username');
    $this->db->from('tb_userInfo');
    $this->db->where('username', $username);
    $this->db->limit(1);

    $query = $this->db->get();
    if($query->num_rows()==1) {

        $result = $query->row();

        return $result->nama;



    } else {
        return false;
    }
}

view

<?php echo $this->session->userdata['name']?>

the var_dump($result) : object(stdClass)#22 (1) { ["nama"]=> string(4) "test" }

if i change the return $result->nama; to $result->username; i get error : Undefined property: stdClass::$username even tho im sure 200% there's username field in the table, and tried the query directly.



row() return null for specific field

MySQL rank across multiple data sets for a scoreboard

I'm trying to build a scoreboard for a multi event competition.

I have a table with data like this:

id competitor  wod score
1  Noah Ohlsen 01  350
2  Noah Ohlsen 02  430
3  Noah Ohlsen 03  140
4  Noah Ohlsen 04  314

I have a SQL query that gets med rank per "wod":

SELECT competitor, FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC ) 
FROM wodcomp.scoring WHERE wod='01' )
) AS wod01,
FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC ) 
FROM wodcomp.scoring WHERE wod='02' )
) AS wod02
,
FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC ) 
FROM wodcomp.scoring WHERE wod='03' )
) AS wod03
,
FIND_IN_SET( score, (
SELECT GROUP_CONCAT( score
ORDER BY score DESC ) 
FROM wodcomp.scoring WHERE wod='04' )
) AS wod04
FROM wodcomp.scoring competitor;

The result is:

Competitor  wod01 wod02 wod03 wod04
Noah Ohlsen 1     0     0     0
Noah Ohlsen 0     1     0     0
Noah Ohlsen 0     0     1     0
Noah Ohlsen 0     0     0     1

I would like it to be one combined row:

Competitor  wod01 wod02 wod03 wod04
Noah Ohlsen 1     1     1     1

Or even with a total across the events based on the combined rank in the different wod, like this:

Competitor  wod01 wod02 wod03 wod04 wodtotal
Noah Ohlsen 1     1     1     1     1



MySQL rank across multiple data sets for a scoreboard

How do I go about creating this table to make a photo collage?

I need some help making a table to put photos of different sizes in as shown below. But when I try to put the images, there is a big white space in a cell and I don't know how to get rid of it. How can you know the exact pixels the image should be by looking at the table, if possible? Any help is appreciated as always. Thanks. :)

What table should look like



How do I go about creating this table to make a photo collage?

Turn text into a string of letters in python?

So I am trying to make a piece if code that can take a string, ignore all plain text in it, and return a list of numbers but I am running into trouble.

basically, I want to turn "I want to eat 2 slices of pizza for dinner, and then 1 scoop of ice cream for desert" into [2,1] (just an example)

    dummy = dummy.split(" ")
                    j = 0
                    for i in dummy:
                        dummy[j]=i.rstrip("\D")
                        j+=1
                        print(dummy[j-1])

is what i have tried but it didn't remove anything. i tried the rstrip("\D") because i thought that was supposed to remove text but does not seem to work for a list.

any ideas where i went wrong or ways to fix this?



Turn text into a string of letters in python?

C# Threading.Timer not always triggering when in a windows Service Task

Folks, I am implementing a routine in a Windows service .NET based, and am using a Threading.Timer task within

protected override void OnStart(string[] args)
{
   base.OnStart(args);
   _startupTask = Task.Factory.StartNew(StartupAction, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}

in my StartupAction i am defning a Threading.Timer as follows:

private void StartupAction()
{ 
    System.Threading.Timer infamousTimer;
    infamousTimer = new System.Threading.Timer(new TimerCallback(runMeEveryHour), null, new TimeSpan(0), new TimeSpan(1, 0, 0));
}

One would think that this is a no brainer, but for some reason it is not always working (works on some PCs but not on others).

Would anyone know what would be the culprit or the environment dependency?

Thanks



C# Threading.Timer not always triggering when in a windows Service Task

Trouble splitting text without using split()

I am trying to do this exercise:

splitText(text) where text is a string and return the list of the words by splitting the string text. See example below:

sampleText = "As Python's creator, I'd like to say a few words about its origins.”

splitText(sampleText)

['As', 'Python', 's', 'creator', 'I', 'd', 'like', 'to', 'say', 'a', 'few', 'words', 'about', 'its', 'origins']

You must NOT use the method split() from the str type, however other methods >from the class are allowed. You must not use python library such as string.py.

This is the code I have got so far:

def split(text):
    final_lst = ""
    length = len(text)
    for x in range(length):
        if text[x].isalpha() == True:
            final_lst = final_lst + text[x]
        else:
            final_lst = final_lst + ", "

    final_len = len(final_lst)
    for a in range(final_len):
        if final_lst[:a] == " " or final_lst[:a] == "":
            final_lst = "'" + final_lst[a]
        if final_lst[a:] == " " or final_lst[a:] == ", ":
            final_lst = final_lst[a] + "'"
        elif final_lst[:a].isalpha() or final_lst[a:].isalpha():
            final_lst[a]


    print(final_lst)

split(sampleText)

But I do not know what to do to finish it off as I have tried so many things but the furthest I can get is this. When I run it I get this:

'A

I've tried lots of things to try and solve this but I have hit a wall. Thanks if you can help me out!



Trouble splitting text without using split()

Wait on COM receive event and console input event in Windows API

I'm an intermediate C++ programmer, but I'm new to using Windows' API functions.

I'm trying to create a console program that will sit/sleep until either

  1. The user inputs something in the console and presses enter
  2. Serial data is received on a COM port that's already been opened

Searching around, it sounds like the way to do this in Windows is with Events, (which sound like they're the same basic idea as interrupts?)

I found documentation on the WaitCommEvent, and I've read about reading console input buffer events. I'm guessing the function to use is WaitForMultipleObjects, but what handles specifically do I send it so it will wait for both a COM RX event or a console standard input event?



Wait on COM receive event and console input event in Windows API

Compare DataOutputStream to String in Java

I have a DataOutputStream I would like to copy into a string. I've found a lot of tutorials on converting DataOutputStreams by setting it to a new ByteArrayOutputStream, but I just want to read the string it sends when it flushes, and my DataOutputStream is already assigned to an output stream though a socket.

output.writeUTF(input.readLine());
output.flush();

If the context is helpful, I'm trying to read the output stream of a server and compare it to a string.



Compare DataOutputStream to String in Java

Can't connect to apple push notify server for production

My push notification script was working until i renewed expired certificates and upload a new apk. I checked everything, my certificates and provisions look correct and push notification service is enabled. Also, it works with development certificate on sandbox.

When i use production certificate, i got error and nothing i found on the internet did not help. Here is the code:

<?php

$deviceToken = '1b66005d6ee0e58eac581a29dce21c34083a3560d3a097b8224ce99412c7a5c5';
$message = 'test!';

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'cafile', 'apple_ca.pem'); // entrust ca certificate
stream_context_set_option($ctx, 'ssl', 'local_cert', 'apn-dist.pem'); // my certificate

// Open a connection to the APNS server
$fp = stream_socket_client(
    'ssl://gateway.push.apple.com:2195', $err,
    $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if(!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL);

echo 'Connected to APNS' . PHP_EOL;
// sending notification ...

Above code dumps this error:

PHP Warning:  stream_socket_client(): Failed to enable crypto in test.php on line 14
PHP Warning:  stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (Unknown error) in test.php on line 14
Failed to connect: 0

When i test my certificate like this:

 openssl s_client -connect gateway.push.apple.com:2195 -cert apn-dist.pem -debug -showcerts -CAfile apple_ca.pem

It is successful:

New, TLSv1/SSLv3, Cipher is AES256-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
    Cipher    : AES256-SHA
    Session-ID:
    Session-ID-ctx:
    Master-Key: 5E9F3C0A551D6A487***********
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1458680158
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

It was working in the past with the previous certificate (also without ca file).



Can't connect to apple push notify server for production

Sinch framework won't import after updating Xcode to support 9.3

I've added the framework in and it won't work when I make the import statement due to a "Module file was created by an older version of the compiler" error. Do I just have to wait for them to recompile it with the new Xcode



Sinch framework won't import after updating Xcode to support 9.3

Data Expansion in Spark (Scala)

I have tab delimited data that I am reading into an RDD that looks roughly like the following. Let's say there are 12 rows for this example (one for each month in 2010).

Data read into myRDD...

1/2010    Red    500    Up
2/2010    Blue   300    Left
3/2010    Red    650    Down
4/2010    Green  200    Left
5/2010    Blue   250    Right
6/2010    Blue   300    Up
...       ...    ...    ...

I am trying to use this data to mock up a larger RDD by doing something like the following, effectively doubling the size.

var biggerRDD = myRDD.union(myRDD)

With the union of the RDD on itself I want to increment the date so it appears to span not only the original 2010 dates, but 2011 as well (essentially incrementing the dates in the second half by one year.

I am unsure of how to do this and have been unsuccessful with my attempts.



Data Expansion in Spark (Scala)

Dropdown changes values according to an upper dropdown

guys. I'm working with cakephp, html and javascript in my work, and I'm having problems with changing the values from a dropdown (select field) according to an upper dropdown, without refreshing the page by the time I select. To explain my situation, I have an array of values from a DB table called "States", connect to another table called "Citys" (I know that it's not correct to write citys, but for a DB it's better just to put an "s" instead of writing "Cities"). A State has many Cities. That's why the table "Citys" has an "idState" to reference the State it's related with. I want the user to select a state from the dropdown list. After that, a dropdown to choose the city appears, but that's not enough, I want just the cities from the state I've choosen to be listed. I know it has to be done with a JavaScript code, but I don't know how to query the database through the js code. I really don't know if I made myself clear. If not, please, ask me for more details about it.



Dropdown changes values according to an upper dropdown

How to use self-compose with sort-step to sort

(define (compose f1 f2)
  (lambda (p2) (f1 (f2 p2))))

(define (self-compose f n)
  (if (= n 1) (compose f f)
      (compose f (self-compose f (- n 1)))))

(define (sort-step l f)
  (cond ((eq? l '()) '())
        ((eq? (cdr l) '()) (list (car l)))
        ((f (car l) (cadr l)) (cons (car l) (sort-step (cdr l) f)))
        (else (cons (cadr l) (sort-step (cons (car l) (cddr l)) f)))))

How to use self-compose with sort-step to sort? Tried:

(define (sort-f l f)
  (self-compose (sort-step l f) (length l)))

test:

(sort-f '(8 4 6 5 3) >)  ===> arity mismatch;
the expected number of arguments does not match the given number
  expected: 1
  given: 0



How to use self-compose with sort-step to sort

Optimizing a Prolog algorithm

I'm trying to learn more advanced Prolog by doing problems I've already solved in Java, and translating parts of the code where possible. I'm currently working on a pebble solitaire problem (http://ift.tt/1XL3LoR), and my code does produce the right answer, for the most part at least... Some inputs take arduous amounts of time to solve, and in some cases, SWI-Prolog runs out of stack (for example start([111,111,111,111,111,45,45,111,45,111,111,111]).

I wonder how I can optimize my program so that it works for all inputs of length 12, and solves them reasonably fast at least.

I tried inserting some cuts where I thought they made sense in the minimizing algorithm, which seemed to have some positive effects. Perhaps there are other things I can do to speed things up that I'm not aware of? Any and all help is greatly appreciated.

% Facts.

empty(45).    % "-"

occupied(111).  % "o"

% Executes a move and updates the board.

executeMove([_, _, _ | R], 0, 1, 2, X, Y, Z, [X, Y, Z | R]).

executeMove([A, B, C | R], I, J, K, X, Y, Z, [A | T]) :- K1 is K - 1,
                                                 J1 is J - 1,
                                                 I1 is I - 1,
                                                 executeMove([B, C | R], I1, J1, K1, X, Y, Z, T).

% Tests if a move to the left can be made,
% i.e. there exists a substring "-oo". 

tryLeft(L, I, J, K) :- I > 1,          
                        nth0(I, L, X),
                        occupied(X),
                        nth0(J, L, Y),
                        occupied(Y),                               
                        nth0(K, L, Z),
                        empty(Z).

% Tests if a move to the right can be made,
% i.e. there exists a substring "oo-".                    

tryRight(L, I, J, K) :- I < 10,        
                      nth0(I, L, X),
                      occupied(X),     
                      nth0(J, L, Y),
                      occupied(Y),                              
                      nth0(K, L, Z),
                      empty(Z).

% Calculates the number of pebbles on the board.

pebbles([], 0).

pebbles([111|T], N) :- pebbles(T, N1),
                 N is N1 + 1, 
                 !.

pebbles([_|T], N) :- pebbles(T, N).

% Algorithm for minimizing the number of pebbles 
% on a board. Currently too inefficient. 

tryMove(L, I) :- (
                 I < 12,               % Iterate over the entire board
                 nth0(I, L, P),        % Get the Ith character
                 (                     % If that character is a pebble
                    occupied(P);       % then we might be able to move
                    I1 is I + 1,       % Otherwise, next iteration
                    !,
                    tryMove(L, I1)
                 ),
                 (
                    J is I + 1,
                    K is J + 1,
                    tryRight(L, I, J, K), % Test if a move can be made
                    !,
                    executeMove(L, I, J, K, 45, 45, 111, Y), % Update the board
                    tryMove(Y, 0), % Test algorithm using the new board
                    calculate(Y);  % Possibly update the minimum 
                    true
                 ),                % Reset to the previous board
                 (
                    J is I - 1,
                    K is J - 1,
                    tryLeft(L, I, J, K), % Test if a move can be made
                    !,
                    executeMove(L, K, J, I, 111, 45, 45, Y), % Update the board
                    tryMove(Y, 0), % Test algorithm using the new board
                    calculate(Y);  % Possibly update the minimum 
                    true
                 ),                % Reset to the previous board
                 I2 is I + 1,
                 tryMove(L, I2);   % Iterate
                 true              % Guarantees true output
               ). 

% Reduces code duplication.

calculate(Y) :- pebbles(Y, F),
          (nb_getval(min, M),
          F < M, 
          nb_setval(min, F),
          !;
          true).

% Game predicate.

start(L) :- pebbles(L, E), 
        nb_setval(min, E), 
        tryMove(L, 0), 
        nb_getval(min, M), 
        write(M), 
        nl.



Optimizing a Prolog algorithm

Typhoon DI framework produces "ambiguous reference" error

I am building an iOS app and using Typhoon framework for dependency injection. I currently have the framework included by source (ie. git submodule), and the Typhoon.framework is linked to my compiled binary. However, when I try to create my first assembly, I get the error Ambiguous reference to member 'withClass' which highlights the TyphoonDefinition class:

assembly function, with highlight shown

Looking at error details, I see these three "candidates" found. I'm lost as to why it thinks there are three different kinds of TyphoonDefinition, if that's indeed what this means:

enter image description here

Any ideas as to how to either (1) resolve the ambiguity, or (2) get more information about the "candidates", the error, or anything else?



Typhoon DI framework produces "ambiguous reference" error

slider carousel - place text under img not on top

I just purchased Master Slider - and I'm trying to place text UNDERNEATH the images of each slide - however the paragraphs keep appearing above the image.

Any ideas?

I've tried floating, clearing, and inspecting all the elements + randomly deactivating them all to try figure out why this order is being reversed.

enter image description here

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

<head>
  <meta charset="utf-8" />

  <title>Master Slider Filters Template</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

  <!-- Base MasterSlider style sheet -->
  <link rel="stylesheet" href="http://ift.tt/1S4rlsH" />

  <!-- Master Slider Skin -->
  <link href="http://ift.tt/1VBHXxn" rel='stylesheet' type='text/css'>

  <!-- jQuery -->
  <script src="http://ift.tt/1S4rlsJ"></script>
  <script src="http://ift.tt/1VBHXxr"></script>

  <!-- Master Slider -->
  <script src="http://ift.tt/1S4rlsL"></script>
  <style>
    <style> .words {
      text-align: center;
    }
  </style>


</head>

<body>
  <!-- template -->
  <div class="ms-filters-template">
    <!-- masterslider -->
    <div class="master-slider ms-skin-default" id="masterslider">
      <div class="ms-slide">


        <img src="http://ift.tt/1VBHZW8" alt="lorem ipsum dolor sit" />
        <p class="words">View All Articles DIY: How to Make a Dreamcatcher There’s something so effortlessly chic about a DIY dreamcatcher! From their flowing feathers to their ethereal origins, dreamcatchers have a free-spirit that encourages us to embrace our dreamy
          inclinations. Want to create your own? Explore your bohemian side with this step-by-step DIY Dreamcatcher guide! More
        </p>


      </div>

      <div class="ms-slide">

        <img src="http://ift.tt/1S4rlsP" alt="lorem ipsum dolor sit" />
      </div>
      <div class="ms-slide">
        <img src="http://ift.tt/1VBHXxt" alt="lorem ipsum dolor sit" />
      </div>
      <div class="ms-slide">
        <img src="http://ift.tt/1S4rnAJ" data-src="img/4.jpg" alt="lorem ipsum dolor sit" />
      </div>
      <div class="ms-slide">
        <img src="http://ift.tt/1S4rnAJ" data-src="img/5.jpg" alt="lorem ipsum dolor sit" />
      </div>
      <div class="ms-slide">
        <img src="http://ift.tt/1S4rnAJ" data-src="img/6.jpg" alt="lorem ipsum dolor sit" />
      </div>
      <div class="ms-slide">
        <img src="http://ift.tt/1S4rnAJ" data-src="img/7.jpg" alt="lorem ipsum dolor sit" />
      </div>
    </div>
    <!-- end of masterslider -->
  </div>
  <!-- end of template -->

</body>

<script type="text/javascript">
  var slider = new MasterSlider();

  slider.control('arrows');
  slider.control('bullets', {
    autohide: false,
    align: 'bottom',
    margin: 10
  });

  slider.setup('masterslider', {
    width: 750,
    height: 430,
    layout: 'partialview',
    space: 5,
    view: 'basic',
    loop: true,
    filters: {
      grayscale: 1,
      contrast: 1.5
    }
  });
</script>

</html>


slider carousel - place text under img not on top

Actionscript Load external MovieClip and replace it's sprite with other movieclip

I have swf files that contain player body and i want load player body and player animation into one movieclip and replace animation sprites with player sprites such as head / hands / weapon. Can anyone help me find way to replace sprites/objects from one movieclip to another?



Actionscript Load external MovieClip and replace it's sprite with other movieclip

uWSGI worker free, but request' handling has significant delay

I would like to run Django app under uWSGI behind nginx. I've launched 2 uwsgi workers, but I noticed next sad circumstance: when one worker is busy, another worker starts handle request only after 10-15 seconds of waiting.

Configuration is pretty simple.

uWSGI: uwsgi --socket 127.0.0.1:3031 --chdir --wsgi-file wsgi.py --master --processes 2 --threads 1

nginx:

server {
    listen 8000;
    server_name example.org;

    location / {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:3031;
    }
}

and /etc/nginx/nginx.conf - default value

test Django view:

def test(request):
    print('Start!!!')
    time.sleep(9999)
    print('End')
    return HttpResponse()

And wsgi.py has default Django value.

So when I launch all this together and send request then I see in console only one "Start!!!" and only after 10-15 seconds apear second "Start!!!".

I have the same strange behaviour without nginx (with uwsgi --http); with multiple threads for each worker; without "--master" uwsgi option.

Additional info: uwsgi version: 2.0.12 nginx version: 1.4.6 host OS: Ubuntu 14.04 Python version: 3.4 Django: 1.9 CPU: intel i7 (4 cores)



uWSGI worker free, but request' handling has significant delay

Increasing Priority Inside Mutexes

I am new to pthreads, and I am trying to understand the output of a C language code, could you please help me with that?

In the program, basically, thread A is executing after being locked, with the command: pthread_mutex_lock(&lock);

Inside this mutex the priority of a second thread (Thread B, which so far had the same priority level of Thread A) is then increased.

How can the program start to execute Thread B if, supposedly it was locked inside the mutex?



Increasing Priority Inside Mutexes

In MySQL how do I iterate over a BLOB?

Let's say there is a BLOB and I would like to replace every occurrence of a particular byte. So I have to iterate over it, right? How do I do that?



In MySQL how do I iterate over a BLOB?

Transfer Database Task

Im trying to use the transfer database task to copy or move a DB from SQL Server 2014 to 2012 and getting the following error message.

[Transfer Database Task] Error: The source connection "{1E07418C-E275-4BC1-8D40-4EE2DD87FD9A}" must specify a SQL Server instance with a version earlier than or the same as the destination connection "{3F849C27-1FE5-4242-8EE8-722E611D453C}".

That seems pretty straight forward but it seems to contradict this post: SQL Server 2014 backup to 2012

What am I doing wrong or is the approved answer in the previous post wrong?



Transfer Database Task

Why is crontab executing on one server but not the other?

I have two servers on linode that have some websites on them. I created a script to see if mysql is running on the server and if it's not running then the script will start mysql. The script is on both servers and in the same file structure.

I have added the script to cron using the "crontab -e" command with both servers. The problem is my dev server will run the script while the prod server will stay down. I have added spaces to the end of the crontab so I know that isn't the problem.

When the script is run manually on the prod server I get this error "(No info could be read for "-p": geteuid()=1000 but you should be root.)". Even though the error shows up the script still restarts mysql but when the script is executing with cron, mysql will not restart. Also note that I have run the script on the dev server and managed to get the same error. Even though the error is there, the script will run on dev and restart mysql when run through cron.

When I run a command under sudo on the dev server it doesn't ask for the pass but when I run it on the prod server I get asked for a password.

I have checked syslog so I know that the cron command is running.

The script uses the netstat command with the parameters -v -u -l -n -t -p.



Why is crontab executing on one server but not the other?

Java, First Item of ArrayList bugs when using String equals method

I have following classes (unnecessary details omitted):

class Person {
    public String name;
    public int id;

    public Person(String name, int id){
        this.name = name;
        this.id = id;
    }

    public void whoAmI(){
        System.out.println("I'm a person!");
    }
}

class Student extends Person {

    public Student(String name, int id){
        super(name, id);
    }

    public void whoAmI(){
        System.out.println("I'm a student!");
    }
}

class Teacher extends Person {

    public Student(String name, int id){
        super(name, id);
    }

    public void whoAmI(){
        System.out.println("I'm a teacher!");
    }

}

Now, I have an ArrayList, which holds all Teachers and Students. For example:

ArrayList<Person> people = new ArrayList<Person>();
Teacher t = new Teacher("John", 1);
people.add(t);
Student s = new Student("Dave", 2);
people.add(s);

At this point, I'm searching the arraylist and try to find out if a person with a specific name is a student or a teacher.

Person p = null;
for(int i=0; i<people.size(); i++){
    p = people.get(i);
    if(p.name.equals("John")){
        break;
    }
}

p.whoAmI();

As you can see, this should print

I'm a Teacher!

But it always prints

I'm a Student!

If I add the student first, or another item, it works correctly. But when the searched item was the first element of the arraylist, equals() method simply not working.

What's happening here?



Java, First Item of ArrayList bugs when using String equals method

Problems with function callbacks in a for loop

I have a function that runs a for loop and then callback the results of the for loop after it is finished. My issue is that in this for loop function I have 2 functions back to back that have callbacks and they take about half a second for them both to finish (maybe less). When I make the call with proper data, my result array is called back after it is finished, however while the usernames are unique, the pictures are Identical which is not what I want. I believe this has something to do with JS trying to be asynchronous but It just is breaking. Here is my code:

function forCallback(rows, callback){
  var done = 0;
  for(i = 0 ;i < rows.length; i++){
    var steamid = rows[i].steamid;
    userinfo.getUserName(steamid, function(name){
        userinfo.getUserPicture(steamid, function(picture){
        results.push({
          name: name,
          picture: picture
        })
        done++;
        console.log("Queried " + done + " username(s)")
        if(done == (rows.length)){
          callback(results);
        }
      });
   });
  }
}

The function takes in sql rows and parses the data that way if you were wondering. Any help is appreciated, THANKS so much!!!



Problems with function callbacks in a for loop

jQuery - all children of a div with class of row

This may have been asked before but I am having troubles. I am trying to do some jquery against all div.row within a div.panel-body.

<div class="panel panel-body">
  <div class=row>
    ...
  </div>
</div>

I have been trying something like this

$(".panel-body").children(".row").mouseover(function(){ $(this).addClass("mover");}).mouseout(function(){ $(this).removeClass("mover");})

If I use just $(".row") it works fine but it affects as you guess all elements with class=row.

What am I missing here?



jQuery - all children of a div with class of row

SQLite3.dll cannot be used in C# application in VS2013 ON WIN 7

I need to access SQLite3.dll for my application (x64) C# in VS2013 on win7.

From SQLite: sqlite3.dll vs System.Data.SQLite.dll?

I see that

 "The sqlite3.dll is unmanaged code containing the databae engine itself and it is embedded as resource inside the managed System.Data.SQLite assembly. "

So, I installed System.Data.SQLite.x64 from package manager:

PM> Install-Package System.Data.SQLite.x64
Attempting to resolve dependency 'System.Data.SQLite.Linq (≥ 1.0.99.0)'.
Attempting to resolve dependency 'System.Data.SQLite.EF6 (≥ 1.0.99.0)'.
Attempting to resolve dependency 'EntityFramework (≥ 6.0.0.0)'.
'System.Data.SQLite.x64 1.0.99.0' already installed.
My_project already has a reference to 'System.Data.SQLite.x64 1.0.99.0'.

I added it as a reference in VS2013. But, I got error:

  An unhandled exception of type 'System.DllNotFoundException' occurred in Devart.Data.SQLite.dll

 Additional information: Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

Then, I downloaded Sqlite3.dll (x64) from http://ift.tt/UeQUv3

I put Sqlite3.dll and Sqlite3.def at bin/Debug and added it as a content file and changed its property of local copy to "copy always" but I got error.

 An unhandled exception of type 'Devart.Data.SQLite.SQLiteException' occurred in Devart.Data.SQLite.dll

 Additional information: Assembly that contains embedded dotConnect for SQLite license cannot be used with this application: my_app.exe

The link does not help either, Could not load file or assembly 'System.Data.SQLite'

Any suggestions ? Thanks.



SQLite3.dll cannot be used in C# application in VS2013 ON WIN 7

PowerShell Version check prior to script execution

I'm just asking the communitty if they have come across a way to have the a script check what version of POSH is running prior to the execution of the script. Currently, my work around is the following code:

    #region Final Checks

    #//Check to make sure that version of PowerShell is at least 3.0 before preceding.

    If($PSVersionTable.PSVersion.Major -le 2) {
        Throw "This script has not been tested with version 2.0 or older of PowerShell.  Please execute this script from a system that has PowerShell 3.0 or newer installed.  Windows 8/Server 2012 and newer has it installed by default.  Windows 7/Server 2008 R2 can be patched to have 3.0 installed."
        }

    #endregion Final Checks

I have this right after defining my parameters. However, for my own crazy sake, I want the script to preform this check automatically prior to getting into the meat and potato of the script. A good comparison is using Validate[X] for a parameter. If an operator tries to provide data that doesn't fit my user, an error is thrown prior to the execution of the script. Any ideas? I know that there is nothing in [CmdletBinding()] that does it. Thanks!



PowerShell Version check prior to script execution

Understanding Swift 2.2 Selector Syntax - #selector()

I am switching over the syntax of my project toward Swift 2.2 (which xCode helps me do automatically); however, I do not understand the new #selector() syntax.

As an example:

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, 
             selector: #selector(MyVC.timerCalled(_:)), //new selector syntax!
             userInfo: nil, repeats: true)

This has the selector #selector(MyVC.timerCalled(_:))

What does the _: signify? Can you add other variables into this selector? Say, #MyVC.timerCalled(_:whateverVar).
General info on what is different in this syntax as opposed to the string based implementation from earlier versions of Swift are greatly appreciated.

Thanks in advance



Understanding Swift 2.2 Selector Syntax - #selector()

Java access to members with type conversion

I have problem with understanding how the methods below work. I have class Calc and method for multiplication, first method use typical getters, second method can access straight to private attribute with type conversion. My question is, how it is possible, that number1 have access to number2's private attribute.

private int number;

public Calc multiplication(Calc z)
 {
        return new Calc(this.number*z.getNumber());
 }

 public Calc multiplication(Calc z)
 {
        return new Calc(this.number*((Calc)z).number);
 }

test()
{
number1 = new Calc(2);
number2 = new Calc(3);
number1.multiplication(number2);
}



Java access to members with type conversion

How to use @Formula in Hibernate/JPA

I am trying to see how @Formula annotation works using a simple piece of code below.

I am able to print out values of description and bidAmount columns but the fields annotated with @Formula i.e. shortDescription and averageBidAmount return null.

Can anyone please help point out what is wrong with the code here?

I am using Hibernate 5.0, postgresql-9.3-1102-jdbc41 and TestNG on a Mac OSX.

    import java.math.BigDecimal;
    import java.util.List;
    import javax.persistence.Entity;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Persistence;
    import javax.transaction.UserTransaction;
    import org.testng.annotations.Test;
    import com.my.hibernate.env.TransactionManagerTest;

    public class DerivedPropertyDemo extends TransactionManagerTest {

      @Test
      public void storeLoadMessage() throws Exception {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");
        try {
          {
            UserTransaction tx = TM.getUserTransaction();
            tx.begin();
            EntityManager em = emf.createEntityManager();

            DerivedProperty derivedProperty1 = new DerivedProperty();
            derivedProperty1.description = "Description is freaking good!!!";
            derivedProperty1.bidAmount = BigDecimal.valueOf(100D);

            DerivedProperty derivedProperty2 = new DerivedProperty();
            derivedProperty2.description = "Description is freaking bad!!!";
            derivedProperty2.bidAmount = BigDecimal.valueOf(200D);

            DerivedProperty derivedProperty3 = new DerivedProperty();
            derivedProperty3.description = "Description is freaking neutral!!!";
            derivedProperty3.bidAmount = BigDecimal.valueOf(300D);

            em.persist(derivedProperty1);
            em.persist(derivedProperty2);
            em.persist(derivedProperty3);

            tx.commit();

            for (DerivedProperty dp : getDerivedProperty(em)) {
              System.out.println("============================");
              System.out.println(dp.description);
              System.out.println(dp.bidAmount);
              System.out.println(dp.getShortDescription());
              System.out.println(dp.getAverageBidAmount());
              System.out.println("#############################");
            }
            em.close();
          }
        } finally {
          TM.rollback();
          emf.close();
        }
      }


     public List<DerivedProperty> getDerivedProperty(EntityManager em) {
      List<DerivedProperty> resultList = em.createQuery("from " + DerivedProperty.class.getSimpleName()).getResultList();
      return resultList;
  }
}

My Entity class is:

@Entity
class DerivedProperty {

  @Id
  @GeneratedValue
  protected Long id;

  protected String description;

  protected BigDecimal bidAmount;

  @org.hibernate.annotations.Formula("substr(description, 1, 12)")
  protected String shortDescription;

  @org.hibernate.annotations.Formula("(select avg(b.bidAmount) from DerivedProperty b where b.bidAmount = 200)")
  protected BigDecimal averageBidAmount;

  public String getShortDescription() {
    return shortDescription;
  }

  public BigDecimal getAverageBidAmount() {
    return averageBidAmount;
  }
}

EDIT

I am following the book Java Persistence with Hibernate 2nd Ed.

enter image description here

Thanks



How to use @Formula in Hibernate/JPA

Issue while printing label

I'm trying to print a sticker and report for a pharmacy since 2 months ago , this pharmacy has 2 printers, i used an interface called Printable I have used it for printing on A4 size and it works fine! , my problem is when I'm trying to print a sticker , it became too huge !, my label size is 5*3
Here is what i did

  1. wrote some words in the pharmacy image using Graphics2D

  2. Pulled the image to java again

3.sent it to Printable after converting it to Graphics.

  public static void sendToPrinter(BufferedImage bufferdImage) {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(new Printable() {
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            if (pageIndex != 0) {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);

            return PAGE_EXISTS;
        }
    });
    try {
        printJob.print();
    } catch (PrinterException e1) {
        e1.printStackTrace();
    }

Can i control the size of this label ? Btw my image has 200 DPI and i know the printable print with 72 DPI, But i have no idea what should i do. The printer name is seewoo lb40 Please i need a solution. Regards.



Issue while printing label

VB.NET / UI Design

Concept UI

Hello,

I'm a beginner at using VB.NET. I have a question about whether I can design a UI similar to the attached image (Concept UI) using Visual Studio/VB.NET. Could this be accomplished with WPF?

Thanks,



VB.NET / UI Design

Why does this script not execute scrollTo(x,y) javascript?

Hello I am trying to create a refresh script to refresh a page on incomming messages,updated posts,ect. Why is x,y not executed useing ex: 1? I have seen a few different methods of reloading a page and keeping scroll position but they seem overkill. I think I would like to use ex: 2, is there any logical way to clear the server side variables using reload() or should I go another route for something like this?

    <script>
    function Refresh()
    {

        var x = window.pageXOffset;
        var y = window.pageYOffset;

        //ex 1:this works but doesnt keep scroll position
        //window.location = window.location.href;

        //ex 2: this works and retains x,y but doesnt refresh $_POST $_GET server side variables
        window.location.reload();

        window.location.scrollTo(x,y);
    }
    //for testing only
    setInterval('Refresh()', 5000);
    </script>



Why does this script not execute scrollTo(x,y) javascript?

numpy UnicodeDecodeError am I using the right approach with genfromtxt

I am stuck. I want to read a simple csv file into a Numpy array and seem to have dug myself into a hole. I am new to Numpy and I am SURE I have messed this up somehow as usually I can read CSV files easily in Python 3.4. I don't want to use Pandas so I thought I would use Numpy to increase my skillset but I really am not getting this at all. If someone could tell me if I am on the right track using genfromtxt OR is there an easier way and give me a nudge in the right direction I would be grateful. I want to read in the CSV file manipulate the datetime column to 8/4/2014 then put it in a numpy array together with the remaining columns. Here is what I have so far and the error which I am having trouble coding around. I can get the date part way there but don't see how to add the date.strftime("%Y-%m-%d") to the datefunc. Also I don't see how to format the string for SYM to get round the error. Any help would be appreciated.

the data

 2015-08-04 02:14:05.249392, AA, 0.0193103612, 0.0193515212, 0.0249713335, 30.6542480634, 30.7195875454, 39.640763021, 0.2131498442 29.0406746589, 13524.5347810182, 89, 57, 99 
 2015-08-04 02:14:05.325113, AAPL, 0.0170506271, 0.0137941891, 0.0105915637, 27.0670313481, 21.8975963326, 16.8135861893, -19.0986405157, -23.2172064279, 21.5647072302, 33, 26, 75 
 2015-08-04 02:14:05.415193, AIG, 0.0080808151, 0.0073296055, 0.0076213535, 12.8278962785, 11.635388035, 12.0985236788, -9.2962105215, 3.980405659, -142.8175077335, 71, 42, 33 
 2015-08-04 02:14:05.486185, AMZN, 0.0235649449, 0.0305828226, 0.0092703502, 37.4081902773, 48.5487257749, 14.7162247572, 29.7810062852, -69.6877219282, -334.0005615016, 2, 92, 10 

the "code" sorry still learning

import numpy as np

from datetime import datetime
from datetime import date,time


datefunc = lambda x: datetime.strptime(x.decode("utf-8"), '%Y-%m-%d %H:%M:%S.%f')
a = np.genfromtxt('/home/dave/Desktop/development/hvanal2016.csv',delimiter = ',',
converters = {0:datefunc},dtype='object,str,float,float,float,float,float,float,float,float,float,float,float,float',
names = ["date","sym","20sd","10sd","5sd","hv20","hv10","hv5","2010hv","105hv","abshv","2010rank","105rank","absrank"])

print(a["date"])
print(a["sym"])
print(a["20sd"])
print(a["hv20"])
print(a["absrank"])

the error

Python 3.4.3+ (default, Oct 14 2015, 16:03:50) 
[GCC 5.2.1 20151010] on linux
Type "copyright", "credits" or "license()" for more information.
>>> 
============================================================================== RESTART: /home/dave/3 9 15 my slope.py ===============================================================================
[datetime.datetime(2015, 8, 4, 2, 14, 5, 249392)
 datetime.datetime(2015, 8, 4, 2, 14, 5, 325113)
 datetime.datetime(2015, 8, 4, 2, 14, 5, 415193) ...,
 datetime.datetime(2016, 3, 18, 1, 0, 25, 925754)
 datetime.datetime(2016, 3, 18, 1, 0, 26, 26400)
 datetime.datetime(2016, 3, 18, 1, 0, 26, 114828)]
 Traceback (most recent call last):
 File "/home/dave/3 9 15 my slope.py", line 19, in <module>
  print(a["sym"])
 File "/usr/lib/python3/dist-packages/numpy/core/numeric.py", line 1615, in array_str
 return array2string(a, max_line_width, precision, suppress_small, ' ', "", str)
File "/usr/lib/python3/dist-packages/numpy/core/arrayprint.py", line 454, in array2string
separator, prefix, formatter=formatter)
File "/usr/lib/python3/dist-packages/numpy/core/arrayprint.py", line 328, in _array2string
_summaryEdgeItems, summary_insert)[:-1]
File "/usr/lib/python3/dist-packages/numpy/core/arrayprint.py", line 490, in _formatArray
word = format_function(a[i]) + separator
UnicodeDecodeError: 'utf-32-le' codec can't decode bytes in position 0-3: code point not in range(0x110000) 



numpy UnicodeDecodeError am I using the right approach with genfromtxt

yhat ggplot facet_wrap type error

I have a pandas dataframe with the following columns:

training = pd.read_csv('training_data.txt') print training.columns.values

['segment' 'cookie_id' 'num_visits' 'num_page_views']

I'm interested in a graph that shows the density of 'num_page_views' by segment, like so:

plot = ggplot(training, aes(x='num_visits')) + geom_density() +xlim(0,20) +facet_wrap( ~ 'segment') print plot

And it gives the following error:

TypeError Traceback (most recent call last) in () 1 ----> 2 plot = ggplot(training, aes(x='num_visits')) + geom_density() +xlim(0,20) +facet_wrap( ~ 'segment') 3 print plot

TypeError: bad operand type for unary ~: 'str'



yhat ggplot facet_wrap type error

sed to Find and Replace chacters between two strings

I have a pipe delimited file where some values/records in one of the columns contain pipes in the value itself making it appear as though there are more columns than there actually are - Notice how "column 8" (bolded) has pipes in the middle. This should actually display as "|col u lm n8|" with spaces in place of the pipes.

column1|column2|column3|column4|column5|column6|column7|**col|u|lm|n8**|2016|column10|column11|column12|column13|column14|

I need to replace these pipe's within column8 with spaces.

Good thing is that the data in column7 and column9 (|2016) is the same across the file so I'm able to do a sed such as this

sed 's/|/ /7g;s/.\(|2016\)/|\1/' 

However that will change all pipes after the 7th pipe to the end of the line. My question is how can I get it to change all pipes to spaces after the 7th pipe but up to the "|2016" column ?

Thank you



sed to Find and Replace chacters between two strings

ByteArrayOutputStream Out of Memory error when send over socket

I am writting a app transfer file based Socket.When I transfer file less than 10 mb ,then no matter what happens.But when I transfer file over 20mb, then I get Out of Memory error and crash my app.

This is my code

RandomAccessFile aFile = new RandomAccessFile(path, "r");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n;
while ((n = inChannel.read(buffer)) > 0) {
        buffer.flip();
        total_length += n;
        baos.write(buffer.array(), 0, n);
        byte[] aaa = baos.toByteArray();
        ObjectStream obstream = new ObjectStream("stream", aaa, session_request, total_length);
        aaa=null;
        outt.writeObject(obstream);
        obstream = null;
        baos.reset();
        buffer.clear(); // do something with the data and clear/compact it.
}
inChannel.close();
aFile.close();

This is error that geted :

FATAL EXCEPTION: Thread-177
java.lang.OutOfMemoryError
at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
at com.jsc.Remote2Droid.Thread.ThreadClientData.run(ThreadClientData.java:705)

out of memory at location:

byte[] aaa = baos.toByteArray();

Please help me fix my code.Thank all.Sorry for my english.



ByteArrayOutputStream Out of Memory error when send over socket

Can't figure out how to have text content shown based on the date automatically

I am looking to have text shown in a paragraph that changes based on the date. This is for a hotel website where the price is based on the seasons and I find it horribly tacky to list out every season's rate in the main price section. Here is my current code that I am having trouble fiddling with to get it to do what I want:

$(function() {
  $(".DateDiv").each(function(index) {
    var sRange = $(this).find(".DateRange").html();
    var arrTemp = sRange.split(" to ");
    var dtFrom = new Date(arrTemp[0]);
    var dtTo = new Date(arrTemp[1]);
    var dtNow = new Date();
    if (dtNow >= dtFrom && dtNow <= dtTo)
      $(this).show();
  });
});
.DateRange,
.DateDiv {
  display: none;
}
<script src="http://ift.tt/1qRgvOJ"></script>
<div class="DateDiv"><span class="DateRange">3/1/2016 to 5/14/2016</span>$89</div>
<div class="DateDiv"><span class="DateRange">5/15/2016 to 9/14/2016</span>$129</div>
<div class="DateDiv"><span class="DateRange">9/15/2016 to 12/1/2016</span>$89</div>
<div class="DateDiv"><span class="DateRange">12/1/2016 to 2/28/2017</span>$49</div>

This works on a basic end of what I want, in that it shows the price of what I need during that rate period though I will have to manually change the code on a yearly basis... if someone knows how to set it up so I don't have to do that, that would be great.



Can't figure out how to have text content shown based on the date automatically

How to place --header-html above margin-top with WKHTMLTOPDF

I have a (in my opinion) common scenario where I want to print a header with a logo on every page. The text on the document can overflow and needs to start on the second page below the header. The logo should start at 10 mm from the top. The text on the second page should start at 40mm from the top of the second page. If I specify top-marin -T 40mm then the header starts at 40mm also. If I specify -T 10mm then the text starts at 10mm also. I have tried to position the header with a CSS style attribute at "position:absolute;top:10mm" from the top and -T 40mm, and I have also tried to position using "margin-top:-30mm" but none of these work. Printing outside the specified margin parameters seems to be impossible. Am I missing something? The --footer-html is placed under the specified bottom-marign -B, why is the header not placed above the top margin?



How to place --header-html above margin-top with WKHTMLTOPDF

How to save a dictionary to a csv where each key has a different row

import time
import csv

def file_reader():
    product_location = {}
    location = 0
    with open('stockfile.csv', mode='r+') as f:
        reader = csv.reader(f)
        #next(reader) Can be included if I have headers to skip it
        products = {rows[0]: (rows[1],rows[2],rows[3],rows[4],rows[5]) for rows in reader}
        global products
    with open('stockfile.csv', mode='r+') as f:
        for line in f:
            lines = line
            print(lines)
            product_location[line.split(',')[0]] = location
            global product_location
        f.close()    

    total=0
    with open('stockfile.csv','r+') as f:
        for line in f:
            product_location[line.split(',')[0]] = location
            location += len(line)
total = 0
while True:
    file_reader()
    GTIN = input("\nPlease input GTIN or press [ENTER] to quit:\n")
    if GTIN == "":
        break
    if(GTIN not in products):
        print("Sorry your code was invalid, try again:")
        continue

    row = products[GTIN]
    description = row[0]
    value = row[1]
    stock = row[2]
    additional_stock = row[3]
    target_stock = row[4]

    print("Updating stock levels back to target level")
    stock = int(stock) + int(additional_stock)

    print('GTIN: ', GTIN)
    print('You have selected: ', description)
    print('The price of this product is: ', value)
    print('Stock: ', stock)

    quantity = input("Please input the quantity required: ")
    new_stock = int(stock) - int(quantity)

    if int(quantity) > int(stock):
        print("Sorry we don't have enough in stock please order again")
        print("Please try a different product or a smaller quantity: ")
        continue
    else:
        new_stock = int(stock) - int(quantity)
    if int(new_stock) < int(target_stock):
        answer = input("The stock is below target, if you would like to top up the product to the target stock level press [ENTER]")
        if answer == "":
            required = int(target_stock) - int(new_stock)
            added_stock = input("This is the target stock: %s, you must enter a minimum of %s" % (target_stock,required))
            stock= int(new_stock)+int(added_stock)
            while int(stock) < int(target_stock):
                print("Sorry input more please:")
                continue
            if int(stock) > int(target_stock):
                additional_stock = 0
                products[GTIN] = row[0],row[1],str(stock),str(additional_stock),row[4]
                print(products[GTIN])
                print(products)
                writer = csv.writer(open('stockfile.csv','w',newline=''))
                for key, row in products.items():
                    writer.writerow([key, value])

    else:
        additional_stock = int(target_stock) - int(new_stock)
        #I need to do the same here and change the dictionary and then send it to the CSV

        product_total = (int(quantity) * int(value))
    total = total + product_total
print('Total of the order is £%s' % total)

I am unable to work out how to send the dictionary back to the csv with this format (this is the format it is in when it has been called upon at the start and I want to send the information back in the same way). This is what the stockfile looks like: This is the format I want the dictionary to be sent back in as well as when it is opened. Please post the code as well which works and thanks in advance.



How to save a dictionary to a csv where each key has a different row

Spring & Security: limit uploads to authenticated users

I'm facing a security problem regarding file uploads. How do I limit file uploads to specific user roles? I'm using @PreAuthorize("hasRole('USER')"), but it is uploading the file first and then checking the role. You can especially see this when file upload size is exceeded. User will get an upload size exceeded exception instead of redirecting to the login-form.

This is how my controller looks like:

@Controller
@PreAuthorize("hasRole('USER')")
@Secured("ROLE_USER") // added this just to see if it makes a difference, it doesn't
@RequestMapping(value = "/self/upload", produces = "application/json")
public class JsonUserSelfUpload {

...

@RequestMapping(value = "", method = RequestMethod.POST, consumes="multipart/form-data")
public ModelAndView fileUpload(
        @RequestParam(value = "file", required = true) MultipartFile inputFile,
        @RequestParam(value = "param1", defaultValue = "") String type,
        HttpServletResponse response
        ) throws Exception {

    ...
    }

}

Anyone know how to secure file uploads to specific roles?

Edit, to be more specific: I want to reject uploads if user is not authenticated. By reject I mean, close connection before the upload actually finishes. Not sure if spring is capable in doing this or I'd need a filter to reject uploads (multipart).



Spring & Security: limit uploads to authenticated users