PostgreSql: cannot use aggregate function in UPDATE

I have an Oracle query that I ported to PostgreSql:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29"
SET "SECT_ORDER" = MAX("SECTIONS"."SECT_ORDER")+1 FROM "SPD_PG"."SECTIONS"
INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)

This give me: ERROR: cannot use aggregate function in UPDATE, seems PostgreSql doesn't support MAX in Update statements.

However if I rewrite the query as follows:

UPDATE "SPD_PG"."TT_SPLDR_11A2F324_29"
SET "SECT_ORDER" = "MAX_VALUE" FROM (
  SELECT MAX("SECTIONS"."SECT_ORDER")+1 AS "MAX_VALUE" FROM "SPD_PG"."SECTIONS"
  INNER JOIN "SPD_PG"."META_SECTIONS" ON ("SECTIONS"."META_SECT_ID"="META_SECTIONS"."META_SECT_ID")
  WHERE ("META_SECTIONS"."META_SECT_ORDER"="TT_SPLDR_11A2F324_29"."META_SECT_ORDER"-1)
  AND ("SECTIONS"."DOC_ID"="TT_SPLDR_11A2F324_29"."DOC_ID")
  AND ("TT_SPLDR_11A2F324_29"."META_SECT_ORDER">0)
) "TBL_ALIAS"

it says ERROR: subquery in FROM cannot refer to other relations of same query level.

So I can't figure out how to write this query.


Kendo Grid edit popup complex model submitting

I’m trying to use complex models with Kendo grid edit popup. When submitting ALResults object properties are always null. It works fine when I’m not using Kendo. Is there a problem with kendo complex model submitting?

public class InitialApplicantLevel2Model
    {
        public InitialApplicantLevel2Model()
        {

            alResultsModel = new ALResults();
        }

        public int InitialApplicantLevel2ID { get; set; }
        public string ApplicantName { get; set; }
        public string ContactNumber { get; set; }
        public string School { get; set; }

        [Required(ErrorMessage="Ref No. required.")]
        public int? EnquiryID { get; set; }

        public ALResults alResultsModel { get; set; }

    }

public class ALResults
    {
        public int ResultsID { get; set; }
        public int InitialApplicantLevel2ID { get; set; }
        public string Stream { get; set; }
        public string Grading { get; set; }
        public string IndexNo { get; set; }
        public int? Year { get; set; }
        public int? Attempt { get; set; }
        public double? ZScore { get; set; }
        public string Medium { get; set; }
    }

@model SIMS.Models.StudentIntake.InitialApplicantLevel2Model
<tr>
        <td>Year: </td>
        <td>@Html.TextBoxFor(o=>o.alResultsModel.Year)</td>
        <td>Index No: </td>
        <td>@Html.TextBoxFor(o=>o.alResultsModel.IndexNo)</td>
        <td>Medium: </td>
        <td>@Html.TextBoxFor(o=>o.alResultsModel.Medium)</td>
    </tr>
    <tr>
        <td>Stream: </td>
        <td>@Html.TextBoxFor(o=>o.alResultsModel.Stream)</td>
        <td>Attempt: </td>
        <td>@Html.TextBoxFor(o=>o.alResultsModel.Attempt)</td>
        <td>Zscore: </td>
        <td>
      @Html.TextBoxFor(o=>o.alResultsModel.ZScore)

        </td>
    </tr>


access wcf self service host using js

I created a wcf self service host
I can access it , and see it's wsdl
but when trying to add the /js extension to the path I get 405 error.
I cannot understand why, while doing the same with a asp.net web applicaton it worked ok.

wcf class :

namespace A
{

    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Hello : IHello
    {

         public string SayHi()
        {
             return "Hiush !";
        }

    }

}

wcf interface:

namespace A
{

    [ServiceContract]
    public interface IHello

    {
        [OperationContract]
         string SayHi();
    }

}

wcf svc file:

<%@ ServiceHost Language="C#" Debug="true"  Service="A.Hello"   %>

the self service host:

namespace SelfServiceHost
{

    class Program
    {

         static void Main(string[] args)
        {
             using (ServiceHost helloHost =  new ServiceHost(typeof(A.Hello)))
            {
                helloHost.Open();
                Console.WriteLine("HelloHost started @ " + DateTime.Now);
                Console.ReadKey();
            }
        }

    }

}

self service host app.config:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
  </system.web>

  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="" closeTimeout="00:01:00"
             openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
             allowCookies="false" bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
             maxBufferSize="524288" maxBufferPoolSize="524288" maxReceivedMessageSize="524288"
             messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
             useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="524288" maxArrayLength="16384"
               maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <!--<security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>-->
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="A.Hello">
        <endpoint address="PINCalc" behaviorConfiguration="AAA"
                  binding="webHttpBinding" contract="A.IHello">
          <!--<identity>
            <dns value="localhost"/>
          </identity>-->
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:3020/Hello.svc"/>
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="AAA">
          <enableWebScript/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>


How can i get a hash into an array, state and acronym?

Array = [{:acronym => "AC", :fullname => "Acre"}, {:acronym => "AL", :fullname => "Alagoas"}, {:acronym => "AP", :fullname => "Amapá"}, {:acronym => "AM", :fullname => "Amazonas"}, {:acronym => "BA", :fullname => "Bahia"}, {:acronym => "CE", :fullname => "Ceará"}, {:acronym => "DF", :fullname => "Distrito Federal"}, {:acronym => "opensearch", :fullname => "Espírito Santo"}, {:acronym => "GO", :fullname => "Goiás"}, {:acronym => "MA", :fullname => "Maranhão"}, {:acronym => "MT", :fullname => "Mato Grosso"}, {:acronym => "MS", :fullname => "Mato Grosso do Sul"}, {:acronym => "MG", :fullname => "Minas Gerais"}, {:acronym => "PA", :fullname => "Pará"}, {:acronym => "PB", :fullname => "Paraíba"}, {:acronym => "PR", :fullname => "Paraná"}, {:acronym => "PE", :fullname => "Pernambuco"}, {:acronym => "PI", :fullname => "Piauí"}, {:acronym => "RR", :fullname => "Roraima"}, {:acronym => "RO", :fullname => "Rondônia"}, {:acronym => "RJ", :fullname => "Rio de Janeiro"}, {:acronym => "RN", :fullname => "Rio Grande do Norte"}, {:acronym => "RS", :fullname => "Rio Grande do Sul"}, {:acronym => "SC", :fullname => "Santa Catarina"}, {:acronym => "SP", :fullname => "São Paulo"}, {:acronym => "SE", :fullname => "Sergipe"}, {:acronym => "TO", :fullname => "Tocantins"}]

How can I compare a variable with :acronym and return the :fullname in other variable?
I'm trying to do this using a Rails helper.


How to get all folders in a SPList, then checking permission "Contribute" for current user

I have a sharepoint list like that:

List
---------Folder 1
-----------------Item 1
-----------------Item 2
---------Folder 2
-----------------Item 1
-----------------Item 2
---------Folder 3
-----------------Item 1
-----------------Item 2

How can I get all Folders in List?

After that checking if current user has Contribute permission on Folder 1, Folder 2, Folder 3?


Display dates between two dates in asp.net

I have two calendars in my aspx and I want to display records between selected dates of these calendars. My 'TeklifTarih' database attribute is a date type attribute.
Here is my aspx:

<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar><br />
<asp:Calendar ID="Calendar2" runat="server"></asp:Calendar><br/>
<asp:Button ID="btnClendar" runat="server" Text="İstatistikleri Filtrele" OnClick="btnClendar_Click"/>

And my onclick method:

protected void btnClendar_Click(object sender, EventArgs e)
    {
        string baslangicTarihi = Calendar1.SelectedDate.ToString();
        string bitisTarihi = Calendar2.SelectedDate.ToString();
        EntityDataSourcePersonel.CommandText =
            "SELECT COUNT(TeklifTable.TeklifHazirlayan) AS Basari, EmployeeTable.Name, EmployeeTable.Surname, SUM(TeklifTable.TeklifTutar) AS ToplamSatis FROM EmployeeTable JOIN TeklifTable ON TeklifTable.TeklifHazirlayan = EmployeeTable.EmployeeId WHERE TeklifTable.TeklifTarih >= " + baslangicTarihi + " AND TeklifTable.TeklifTarih <= " + bitisTarihi + " GROUP BY EmployeeTable.Name,EmployeeTable.Surname";
    }

I need to display datas with this commandtext and it works when I remove where command of query but I need to filter with these two dates.


Ajax alert on validation error

I have made this ajax call:

$.ajax({
    type: myMethod,
    url: myRoute,
    headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
    data: form.serializeArray(),
    dataType: 'json',
    success: function(data){
        console.log('validated!');
    },
    error: function(data) {
        var errors = data.responseJSON;
        for (error in errors) {
            alert(error);
        }
        console.log(errors);
    }
});

I get this response in the console:

And my alerts are those field names:

event_end_date
event_start_date

And what i want is to print those messages:

Endzeitpunkt muss ausgefüllt sein.
Startzeitpunkt muss ausgefüllt sein.

How to get them in alert?


Generate link to PDF asset in MODX with PHP

My SimpleSearch is configured to return both Resource hits and PDF hits from my assets/pdfs folder (using Solr). The results are more-or-less working properly, but I'm unable to generate links to PDF hits as SimpleSearch uses makeUrl() for Resource links, but it only take an integer and doesn't like the file path that is sent for a PDF hit. Here's the section of SimpleSearch snippet I'm working on:

if ($extract) {
    $resourceArray['link'] = $modx->makeUrl($resourceArray['id'],'$ctx',$args);

} else {
    $resourceArray['link'] = 'http://google.ca';
}

I'm using if ($extract) as PDF hits don't have an extract generated... And it's working! When I look at the html of a search result, all the PDF hits get 'http://google.ca' while Resource hits have their link generated properly by makeUrl().

So how do I generate links to the PDF hits?


There is already an open DataReader associated with this Command which must be closed first - WCF

I have functions that is being called within a WCF service function and I get the exception stated above at the subcategoriesGenerator function on the excute reader line
isn't it supposed for the cmd created in the second function to a completely different instance than the other one
please I'm confused and I need help ant suggestions?

public static List<Category> categoryGenerator(ref SqlConnection con)
    {
        Category category = null;
        List<Category> list = null;
        List<SubCategory> subcategoryList = null;
        string categoryName = null;
        string categoryLink = null;
        SqlCommand cmd = new SqlCommand("sp_categoriesgenerator", con);
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        while(reader.Read())
        {
            categoryName = reader["CategoryName"].ToString();
            categoryLink = reader["CategorySEO"].ToString() + "/";
            subcategoryList = subcategoriesGenerator(ref con, Convert.ToInt32(reader["CategoryId"].ToString()));

            category.categoryName = categoryName;
            category.categoryLink = categoryLink;
            category.subcategories = subcategoryList;

            list.Add(category);

            category = null;
        }
        reader.Close();
        return list;
    }//end CategoryGenerator

  public static List<SubCategory> subcategoriesGenerator(ref SqlConnection con, int categoryId)
    {
        SubCategory subcategory = null;
        List<SubCategory> list = null;
        string SubCategoryName = null;
        string SubCategoryLink = null;
        SqlCommand cmd = new SqlCommand("sp_subcategoriesgenerator", con);
        cmd.Parameters.AddWithValue("@categoryID", categoryId);
        SqlDataReader reader = cmd.ExecuteReader();

        while(reader.Read())
        {
            SubCategoryName = reader["SubcategoryName"].ToString();
            SubCategoryLink = reader["CategorySEO"].ToString() + "/" + reader["SubcategorySEO"] + "/";
            subcategory.subcategoryName = SubCategoryName;
            subcategory.subcategoryLink = SubCategoryLink;
            list.Add(subcategory);
            subcategory = null;
        }
        reader.Close();

        return list;
    }// end subcategoriesGenerator


Flash - Managing a large project

We are prototyping using Autodesk Scaleform and building our game UI using Flash. We will need to be able to run a large project with a team of 3-4 artists and 10+ programmers. We use Perforce source control system for storage of all code and assets. We need to be able to manage a project with multiple shared resources and multiple people (artists & programmers) working on screens and controls.

Our problem is as follows:

We want to be able to create skinned graphical custom components, such as buttons, sliders, checkboxes as well as more complex controls such as tables and game specific elements.
We want to be able to share graphics assets in a single location and allow multiple artists and coders to work on shared components simultaneously. We need all of this to be stored in a Perforce source control repository.

For AS3 code this is all fairly straight forward. It works like any other codebase and we have set up FlashBuilder and FlashDevelop projects.

Now, the options seem to be as follows:

Create a flash project or projects. The problem here is that all of the assets are copied into AuthortimeSharedAssts.fla. This means that, because FLA is a binary format, our source control cannot allow more than one person to edit any shared resource at the same time.

Set up manual authortime sharing. This will allow work on multiple shared components because individuals can update a small discrete FLA file and this will automatically update a larger shared librar. The problem is that this does not allow sharing of graphics assets, which means that, if an artist updates a graphic, this does not filter down to individual flash files.

Use the XFL format. This would allow us to merge files when checking in to source control as they are plain text and it saves out individual assets as separate files, which looks perfect. The problem is that I can't see how to make a project, which entirely uses XFL files (i.e. makes something like AuthortimeSharedAssets.xfl).

At the moment I can't see any obvious, sensible way of running a large project  in Flash. We cannot be the first to do this sort of thing though.

Can anyone help or explain how we should do it?


Can i write file in root direcotry android?

i have a question that i can write a file in root directory by this code?
when i test on emulator then it can write at path: /data/data/com.example.test/files/g.gc
but i donot know that i can write file on device, because i donot have any device to check it.

public static void saveFile(Context context, String content) {
    try {

        FileOutputStream fw = context.openFileOutput("g.gc", Context.MODE_PRIVATE);

        fw.write( content);

        fw.close();

    } catch (IOException e) {}
}


kill my previous file on local host

I connected my file "smap" to localhost:3000 couple month ago when I was learning the npm.

Right now, I cannot remove it from localhost:3000

It keeps showing me old file:

smap@1.0.0 start /Users/Han
  cross-env NODE_ENV=development ./node_modules/.bin/hjs-dev-server
  Listening at http://localhost:3000
  webpack built 2f3c2c9a3eec810b8e79 in 2453ms

Does anyone know how can I remove it from my local host? I tried

Find: lsof -i :3000
Kill: kill -9 <PID>

but it did not work.

Since I get a new file, want to connect it with localhost.


Codeigniter form serialize not working

i'm triying to pass data from form to controller in codeigniter...but when I want to print a table with the results...i'm getting null on every row of the table. Here is my code:

FORM

<form class="col s12" id="update_form" name="update_form" method="post" >
      <div class="row">
        <div class="input-field col s6">
          <input id="update_name" type="text" name="name" class="validate">
          <label for="first_name">Nombre</label>
        </div>
        <div class="input-field col s6">
          <input id="update_last_name" name="lastname" type="text" class="validate">
          <label for="last_name">Apellido</label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s6">
          <input id="update_side" type="text" name="side" class="validate">
          <label for="partido">Partido</label>
        </div>
        <div class="input-field col s6">
          <input id="update_charge" type="text" name="charge" class="validate">
          <label for="cargo">Cargo</label>
        </div>
      </div>
        <div class="row">
            <div class="input-field col s6">
               <div class="file-field input-field no-margin-top">
                  <div class="btn light-blue darken-4">
                    <span>Animación</span>
                    <input type="file">
                  </div>
                  <div class="file-path-wrapper">
                    <input class="file-path validate" name="animation" type="text">
                  </div>
                </div>
            </div>

            <div class="input-field col s6">
            <select id="update_section" name="section" autocomplete="off">
              <option value="" disabled selected>Seleccione una opción</option>
              <option value="1">Presidencia</option>
              <option value="2">Senadores</option>
              <option value="3">Diputados</option>
            </select>
            <label>Sección</label>
          </div>
        </div>
        <input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
    </form>

Jquery

$("#update_politic_btn").click(function(event) {
    /* Act on the event */

    var chango = $("#update_form").serialize();
    alert(chango);
    $.post(baseurl + 'admin/update_politic', {
            data: chango
        },
        function(data) {
            console.log(data);
            list_politic();
        });
    event.preventDefault();
});

Controller

public function update_politic(){

  if ($this->input->is_ajax_request()) {

  $params["name"] = $this->input->post("name");
  $params["lastname"] = $this->input->post("lastname");
  $params["side"] = $this->input->post("side");
  $params["charge"] = $this->input->post("charge");
  $params["animation"] = $this->input->post("animation");
  $params["section"] = $this->input->post("section");
  $params["id"] = $this->input->post("update_politic_hide");

  if ($params["section"]=="Presidencia") {
      $params["section"]=1;
  }

  if ($params["section"]=="Senadores") {
      $params["section"]=2;
  }

  if ($params["section"]=="Diputados") {
      $params["section"]=3;
  }

  $this->load->model("politic");
  $this->politic->update($params);
}
}

MODEL

public function update($param){

  $id = $param["id"];
    $values = array(

                    "POLITIC_NAME" => $param["name"],
                    "POLITIC_LASTNAME" => $param["lastname"],
                    "POLITIC_SIDE" => $param["side"],
                    "POLITIC_CHARGE" => $param["charge"],
                    //"animation" => $param["animation"],
                    "SECTION_ID" => $param["section"],
                    );

    $this->db->update("politics",$values);
  $this->db->where("POLITIC_ID",$id);
}

HELP!!! I  don't understan why i'm getting null values once I want print results!!


GroupBox: Adjust size according to text length

Is there an easy way to have a GroupBox auto resize its width depending on the length of the string in the Text property?

Say I fit the width by hand (in Design Mode) when the Text = "Text1" then, when the program is running, I update it to Text = "This is the new text!" I would like the width to auto expand instead of wrapping over to the next line.

Thanks!


Is it possible to serialize two forms in one ajax function?

I need to serialize two forms in the same ajax function with one call. I have tried the following but it just serialize the last one.

                function sssssss2(page){
            var form1 = document.myform1;
            var form2 = document.myform2;
                            var dataString1 = $(form1).serialize() + '&page=' + page;
            var dataString2 = $(form2).serialize() + '&page=' + page;
                $.ajax
                ({
                    type: "GET",
                    url: "load_data.php",
                    data: {dataString1, dataString2}
                    success: function(ccc)
                    {
                     $("#container").html(ccc);
                    }
                });
            }

It doesn't work. How may I serialize both of them within the same function?


Adding a Equinox OSGI hook throwing ClassNotFoundException

I'm trying to add a BundleWatcher hook in my OSGi container so that I can monitor bundles as they are loaded. I have made the following changes in config.ini,

Added a reference to my jar in the osgi.bundles property like so,
osgi.bundles = , reference\:file\:../lib/my.jar@2:start

Set the property osgi.framework.extensions = mybundle

Add MyBundleWatcher as a hook in osgi.hook.configurators.include

Also my jar file is in the same directory as the OSGi bundle.

When I run my app I get a ClassNotFoundException for my BundleWatcher.

I can confirm however that my bundle (which contains the BundleWatcher) is indeed started as the start method of the Activator in my bundle is called.

What am I doing wrong?

As a background here are a couple of articles I followed,

http://wiki.eclipse.org/index.php/Adaptor_Hooks

http://eclipsesource.com/blogs/2013/01/23/how-to-track-lifecycle-changes-of-osgi-bundles/


QTreeView and QTabWidget to display only selected items of QTableViews

Given two SQLite tables addresses and messages, what is the best way to map them to a QTreeView and QTabWidget in such a way, that if I select one row in a QTableView (which is either mapped to addresses or messages), the selected item is

opened as a new tab to display its contents, and

inserted as an item in the QTreeView to represent an "opened" item.

I've managed to open new tabs by creating two custom QWidgets, one for addresses and one for messages. On selecting a row in the QTableView, the correct (either addresses or messages) QWidget is created and fed with the SQL model and the index. The widget then creates a QDataWidgetMapper and displays the given index. AddressWidget example:

AddressWidget::AddressWidget(QSqlRelationalTableModel *model, QModelIndex &index, QWidget *parent) :
    QWidget(parent)
{
    // ...

    // set up widget mapper
    mapper = new QDataWidgetMapper(this);
    mapper->setModel(this->model);
    mapper->addMapping(streetEdit, this->model->fieldIndex("street"));
    mapper->addMapping(houseNumberEdit, this->model->fieldIndex("houseNumber"));
    mapper->addMapping(zipEdit, this->model->fieldIndex("zip"));
    mapper->addMapping(cityEdit, this->model->fieldIndex("city"));
    mapper->setCurrentModelIndex(index);
}

How can I extend this to the QTreeView, so that the tree displays opened items? Each tab in the QTabWidget should have a corresponding item in the QTreeView.

If there is a right way of doing this, please add it or replace my scenario entirely.


I want to know how i can return Json in my cakephp when i perform a Get request?

I'm new to cakephp and json. I've recently build a rest service with cakephp. Everything seems to be working. When i query a link using this code beneath that is stored in a separate file:

<?php

$request =  'http://localhost/tut_blog/posts/';
$response = file_get_contents($request);
echo $response;
?>

I get the return in html because i programmed my view file that way. Her is my view file: index.ctp

<h2>View all posts</h2>

  <table>
    <tr>
    <th>Title</th>
    <th>Body</th>
     </tr>

<?php foreach($posts as $post):?> // met de functie foreach wordt er hier geloopt door de variable $posts die we eerder in de controller hadden aangemaakt en die alle waarden bezit van de query die we eerder hadden opgesteld.

<tr>
    <td><?php echo $post['Post']['title'];?></td> // de $posts array bevat 2 sleutels nr 1 = naam van de model, nr 2 = de naam van de veld in je tabel.
    <td><?php echo $post['Post']['body'];?></td>
</tr>

<?php endforeach; ?>
 </table>

I want to know how i can get this same data but then in JSON output.
Here's my controller file as well:

 <?php

class PostsController extends AppController{

var $name = 'Posts';

var $components = array('RequestHandler');

    function hello_world(){

    }

    function index(){

    $this->set('posts',$this->Post->find('all'));

    }

    function view($id = NULL){

    $this->set('post',$this->Post->read(NULL, $id));

    }

}

?>


css - how to get floated divs to stack when you zoom in

In this responsive design I am trying for, I have three divs floating side-by-side, which get narrower and narrower when you zoom in on them. I would like them to keep their size and stack instead. How do I do this? I am beginning jquery, but for this would prefer to stick to css if possible.

Here is the relevant styling I have for the divs and their parent container div:

#container {
margin-left:auto;
margin-right:auto;
width:110%}

.floating-div {
width:27%;
min-width:27%;
height:420px;
float:left;}

Thanks for reading~


Is it possible to set an element to display only when the <img> element is removed?

For printing purposes, I removed the IMG element, but I wanted an H1 element to be displayed on another portion of the site when the IMG element is removed.

Is this possible?


rails 4 justifiedGallery script only load the latest post with images

When i create a new post with images it works, but when i create a new post with images, justifiedGallery doesnt apply the jquery script to the previous post, why?

jQuery -> //when dom is ready
  $("#userindex").justifiedGallery(
    lastRow : 'justify',
    captions: false,
    randomize: false,
    rowHeight: 80,
  )

View to render post with image

<div id="userindex">
   <% img.each do |link| %>
      <div>
          <%= image_tag(link) %>
      </div>
   <% end %>
</div>


cmake failed building project on mac

I'm trying to build a project on my new macbook which was previously built normally on linux computers.

at first when i run cmake, i get a the following:

-- The C compiler identification is Clang 5.1.0
-- The CXX compiler identification is Clang 5.1.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Performing Test HAVE_CLOCK_GETTIME
-- Performing Test HAVE_CLOCK_GETTIME - Failed
-- Boost version: 1.55.0
-- Found the following Boost libraries:
--   graph
-- Could NOT find Doxygen (missing:  DOXYGEN_EXECUTABLE)
-- -> doxygen not found -> api-doc will not be created
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/folder

and then when i run make, it works till around 30% and then it stop with this error:

/path/to/project/lib/helpers.cpp:555:2: error: use of undeclared identifier 'gettimeofday'
        gettimeofday(&tv, NULL);
        ^
1 error generated.
make[2]: *** [lib/CMakeFiles/genom.dir/helpers.cpp.o] Error 1
make[1]: *** [lib/CMakeFiles/genom.dir/all] Error 2
make: *** [all] Error 2

I looked online, there was some suggestions for changing clock_gettime(CLOCK_REALTIME, &t); to clock_get_time(CLOCK_REALTIME, &t);

but they didnt work.


iOS 8 :MFMailComposeViewController automatic called cancel button

iOS 7 email send work perfectly but iOS 8 view automatic disappear and send button also not enable.

error is :timed out waiting for fence barrier from com.apple.MailCompositionService


Rails: Many to Many relationship setup (ActiveRecord and ActiveAdmin)

I added a has_and_belongs_to_many between Product and Brand tables/models

This is how the models look like:

class Brand < ActiveRecord::Base
  has_and_belongs_to_many :products

  default_scope { order('name asc')}
end

class Product < ActiveRecord::Base
  has_and_belongs_to_many :brands
end

These are the existing columns in the table:

[13] pry(main)> Brand
=> Brand(id: integer, name: string, created_at: datetime, updated_at: datetime, product_id: integer)

[11] pry(main)> Product
=> Product(id: integer, name: string, created_at: datetime, updated_at: datetime)

Join table db migration:

class CreateJoinTableProductsBrands < ActiveRecord::Migration
  def change
    create_join_table :products, :brands do |t|
      t.integer :product_id
      t.integer :brand_id
      t.index [:product_id, :brand_id]
      t.index [:brand_id, :product_id]
    end
  end
end

Questions:

As you will notice, the Brand table already had the product_id column. Should I change it to an array product_ids column? (I am using postgres)

Should I add brand_ids column to Product

Should I add ProductBrand model. I tried it but seems like Rails console didnt recognize it

class ProductBrand < ActiveRecord::Base

end

In ActiveAdmin what's the correct way of creating a new entry for Product or Brand such that a new record correctly links Product, Brand and ProductBrand entry?


How to escape a systemd Specifier to pass to the command in ExecStart

I've written the following systemd service tcpdumpd.service to kick off a persistent tcpdump recording.

[Unit]
Description=TCPDumpd
After=multi-user.target network.target

[Service]
Type=simple
ExecStart=/usr/sbin/tcpdump -pni eth0 -s65535 -G 3600 -w '/var/log/tcpdump/trace_%Y-%m-%d_%H:%M:%S.pcap' -z gzip
Restart=on-abort

[Install]
WantedBy=multi-user.target

tcpdump allows strftime-placeholders like %H for hour, %M for minute and so on to allow you to create time stamped files.

However, systemd has special specifiers than can be used in it, like (%n, %N, %p, %i, %U, %u, %m, %H, %b, %v)  So any of the specifiers that overlap, like %m and %H pass through the information from systemd and don't allow the placeholder to be passed through to tcpdump to make the time stamp.

Does anyone know if there is a way to escape the specifiers in systemd so I can pass the %m and %H through to tcpdump?


What's the best approach in auditing a big java/j2ee web application

I have to audit a large web Java/J2ee application that has evolved over several
years. It's been written by some other company, not the one I'm working for. In
it's current state it has become hard to evolve and maintain, new
functionalities are hard to add and often lead to bugs that sometime show up in
production. There seem to be some copy/pasted code which resulted in code duplication.
The current app is some kind of online shopping with some cms-like content here and there.
It's mostly Struts and some Spring in newer parts of the code, maybe some ejbs thrown in for
good measure. There are some unit tests available, but not a lot of them.
These are things I've been told, I haven't seen yet the actual code.

My company will make a proposition to rewrite parts of this app in order to reduce
complexity, improve quality and modularity, and make it possible to add easier
new functionalities without regressions.
Before making any commitement, they would like to have some kind of appreciation
of the quality of the existing code and to asses how much of it can be reused, in order
to have more than a guess in what there will have to be done - full rewrite or partial
rewrite.

The catch is that I'll have to do this in a very short period ( a couple of days ) so I'm
trying to work out a plan for what can be done in such a short time. What I'm thiking is :

check out "basic" things - exceptions treatment, logging

check out the level of layering ( views, controllers, dao layer )

measure the actual coverage of the unit tests

maybe run some Checkstyle, Findbugs and PMD over the projects

...

So the actual question is what other things should I take into account/check/measure/etc ?

I'm not sure what kind of numbers I could get out of this and if it would really mean
something, I have the feeling that what the management is asking is kind of the wrong
approach, so the second question would be : does anyone has a better idea ?

I'll appreciate any idea, suggestion, comment on this.

Edit: I'll be adding two dead code detectors to the mix : UCD and DCD


Android Timer Example

I'm developing a game via Andengine for Android. There is a player on my game scene. When the player pass finish line(800,0), the game will end. So I wanna show every passed seconds to user on scene. And finally I wanna show how much time passed till the finish.
How can I do that?

I tried this but doen'T work:

TimerHandler timerHandler = new TimerHandler(0.1f, true, new ITimerCallback(){

           @Override
           public void onTimePassed(TimerHandler pTimerHandler) {
              time.setText(""+pTimerHandler.getTimerSeconds());
           }
       });
registerUpdateHandler(timerHandler);


R plot: How to use mtext to get top-aligned vertical label with las=1

I'm trying to get a label on my vertical axis using mtext that is read horizontally (las=1) and is at the top of the axis.

My attempt is to use las=1, adj=1. I can get the desired placement when I don't specify las=1, but as soon as I add the las=1 argument the adj=1 placement goes away. Here's a picture with code. The left plot shows correct placement, but without las=1. The right plot shows both arguments present.

par(mfrow=c(1,2), mar=c(2,3,2,1))

plot(1, 1, ann=F)
mtext(col="blue", "y", side=2, line=2, adj=1)
mtext(side=3, "col=blue, side=2, adj=1")

plot(1, 1, ann=F)
mtext(col="red", "y", side=2, line=2, adj=1, las=1)
mtext(side=3, "col=red, side=2, adj=1, las=1")

I've tried fussing around with padj, but that only moves the label up & down a little. Also, I know that the at argument can, but that feels a bit too manual.


Hadoop, "Browse the filesystem" broken link on ec2

I am newbie to setting hadoop on EC2. I am trying to set-up single node hadoop setup. I have successfully installed and ran Hadoop 1.1.2 on one of the Amazon EC2 instance. All nodes, namenode, datanode, jobtracker, mapred node are on the same machine.

My core-site cofiguration is

<property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:9000</value>
</property>

When I start the Hadoop, and go to web ui, namenode UI opens without any problem.

http://<namenode>:50070/dfshealth.jsp

But when clicked on the "Browse the filesystem", it redirects to

http://localhost:50075

which is incorrect. It should be something

http://<namenode>:50075.

But in this case it failes.

Please help me to figure out the problem.


Parse XML partially

i have a problem parsing following (shortened) XML-file:

<?xml version="1.0" encoding="UTF-8"?>
<!-- DOCTYPE nitf PUBLIC "-//IPTC-NAA//DTD NITF-XML 3.0//EN" "nitf.dtd" -->
<nitf>
  <head>
    <title>EU-Regierungschefs streiten über Waffen für Syrien</title>
  </head>
  <body>
    <body.head>
      <hedline>
        <hl1>EU-Regierungschefs streiten über Waffen für Syrien</hl1>
      </hedline>
    </body.head>
    <body.content>
      <p> [...] </p>

      <block style="EXTERNAL-LINKS">
        <p>
          <a href="http://dpaq.de/CyyZL">EU und Syrien</a>
        </p>
        <p>
          <a href="http://dpaq.de/WzLWU">EU und Russland</a>
        </p>
      </block>
      <media media-type="image">
        <media-reference alternate-text="Merkel und Barroso" height="600" mime-type="image/jpeg" name="large_4_3" source="../dpa-bzv_myline-images/large/jpeg-1484DE008774AFFD-20130315-img_41077628.original.large-4-3-800-252-0-2976-2041.jpg" width="800"/>
        <media-caption>
          <p> [...] </p>
        </media-caption>
      </media>
    </body.content>
    <body.end/>
  </body>
</nitf>

The PHP-part looks like this:

if (file_exists($path)) {
    $xml = simplexml_load_file($path);
    var_dump($xml->body->{'body.content'});
}

As expected, the XML-content is parsed correctly. This is, where my problem begins. <body.content> contains HTML-tags, which are parsed, too, but i would like the content to be treated as a string, to output it directly to display the HTML as it is.

What would be the best way to solve this?


Can I call a 64bit DLL from a 32bit version of Excel VBA?

I'm in the unusual situation of having a 32bit install of Excel and some libraries I call have been compiled as 64bit libraries but when I try to call the functions I get an error "Cannot find xyz.dll".

I know you can't call 32bit processes (easily) from 64bit ones, but what about vice versa?


Simulate application on an iPad mini w/ Flashbuilder

I'm almost ready to launch my app on the store. But i found some issues with the display of components on an iPad Mini. It all works on a regular ipad and a ipad retina.

Simple question, is there any way to simulate the app on an iPad Mini (or more devices from Apple) with FlashBuilder?

Info app:
- Flex mobile project
- made in FlashBuilder


php object oriented overloading

I came across the following code and could not figure out why the output of the script came out in a non-intuitive sequence using php's get and set magic methods.

class Magic
{
    public $a = "A";
    protected $b = array("a" => "A", "b" => "B", "c" => "C");
    protected $c = array(1,2,3);

    public function __get($v)
    {
        echo "$v";
        return $this->b[$v];
    }
    public function __set($var, $val)
    {
        echo "$var: $val";
        $this->$var = $val;
    }
}
$m = new Magic();
echo $m->a . "," . $m->b . "," . $m->c . ",";
$m->c = "CC";
echo $m->a . "," . $m->b . "," . $m->c;

Out put was:

bcA,B,C,c
CCbcA,B,C

First of all why is it no outputting A as the first thing? The sequence of output doesn't make sense.


how to output the incremented list of years/current pop?

I'm doing an assignment for class where I need to output my program to look something like this. Right now I'm stuck on how to output the years like that.

I've added a counter for years and asked for current year as an input?

Can someone lend me a hand?

             Town A             Town B
               8.5%               0.3%
Year          5000                8000
-------------------------------------------
2016          5425                8024
2017          5886                8048
2018          6386                8072
2019          6929                8096
2020          7518                8121
2021          8157                8145

    cout << "What year is it? ";
    cin >> curYear;
    cout << "Enter the population of town A: ";
    cin >> townA;
    cout << "Enter the growth rate of town A: ";
    cin >> growthA;
    cout << "Enter the population of town B: ";
    cin >> townB;
    cout << "Enter the growth rate of town B: ";
    cin >> growthB;

    while ((townA <= 0) && (growthA <=0) && (townB > townA) && (growthB < growthA) && (growthB > 0))
    {
        cout << "Error: Values must be positive, please try again." << endl;
        cout << "Enter the population of town A: ";
        cin >> townA;
        cout << "Enter the growth rate of town A: ";
        cin >> growthA;
        cout << "Enter the population of town B: ";
        cin >> townB;
        cout << "Enter the growth rate of town B: ";
        cin >> growthB;
        cout << endl;
    }

    years = 0;
    while (townA <= townB)
    {
        finalA = ((growthA / 100) * (townA)) + townA;
        finalB = ((growthB / 100) * (townB)) + townB;
        cout << "Town A " << finalA << endl;
        cout << "Town B " << finalB << endl;
        years++;
        curYear++;
        townA = finalA;
        townB = finalB;
    }

    cout << "\n\n" << endl;
    cout << setw(3) << "Town A" << setw(15) << "Town B" << endl;
    cout << setw(3) << growthA << "%" << setw(14) << growthB << "%" << endl;
    cout << setw(4) << townA << setw(16) << townB << endl;
    cout << "Year" << endl;
    cout << curYear << endl;
    cout << "--------------------------------------------" << endl;
    cout << endl;
    cout << "It took Town A " << years << " years to exceed the population of Town B." << endl;

    return 0;
}


How to update widget every minute

can anyone tell me the best way to update widget every minute.

Now i'm using thread inside the AppWidget, but sometimes i get error  FAILED BINDER TRANSACTION !!! After that error, i always got a lot of error like that all the time and i can't change the view in my widget again.

Thanks


AND a mask to address (lower bits needed) C#

So I know I can bit shift a mask of 0xFFFFFFFF by say 8 for example to get 0xFFFFFF00 & it with an address and get everything but the last 8 bits, but I would like to go the other way so I can grab the bottom end of an address with a mask like 0x000000FF, however bit shifting right wont work obviously. Any ideas?

Here is the code for the first type bit shift I mentioned.

public int Block_tag(int address, int block_size, int max_address)
    {
        int bit_shift = (int)Math.Log(block_size, 2);
        int bit_mask = max_address << bit_shift;
        return (address & bit_mask);
    }

I could do it by hand with about 12 "If" statements but that isn't very clean.

Thanks!


Task 'default' is not in your gulpfile after npm link gulp

I´m using gulp and defined my gulp task in the gulpfile.js
Because i don´t want to install gulp every time i used the

npm install gulp -g
npm link gulp

( the link command in my directory where i want to execute gulp )
after that the command "gulp" is available on my working directory, but it outputs:

Task 'default' is not in your gulpfile
  Blockquote

If I put a console log in the beginning of my gulpfile.js, I can see that he outputs the log and can find the gulpfile.js

Can anyone tell me where my problem is ?

I found this article but it did not helped me
How to fix "Task is not in your gulpfile" error when using npm link?

Thanks so much


Can Moqui implement a form with dynamic fields

I have two list listRowKey and listColKey and a nested map map<Row, Map<Col, String>>, I want to create a table to input content into map, the rows and cols of table is generated from two list. I don't known how to use a nested loop to add fields into form.


Android Calendar Provider: How can I delete my own local calendars?

I am just learning how to work with the Android Calendars. So far, I am able to display the info about existing calendars. I can also create my own local calendars -- the test code like:

private void createCalendarTest()
{
    Uri.Builder builder = Calendars.CONTENT_URI.buildUpon();
    builder.appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true")
           .appendQueryParameter(Calendars.ACCOUNT_NAME, "private")
           .appendQueryParameter(Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);

    Uri uri = builder.build();

    ContentValues values = new ContentValues();
    values.put(Calendars.NAME, "TEST");
    values.put(Calendars.CALENDAR_DISPLAY_NAME, "Calendar named TEST");
    values.put(Calendars.SYNC_EVENTS, false);
    values.put(Calendars.VISIBLE, true);

    getContentResolver().insert(uri, values);
}

Actually, I can create many calendars that differ only in _ID. I have read elsewhere that I can create a calendar only when using the sync adapter. Now, how can I delete the calendar? I expect the URI must also contain the sync adapter info, and the _ID of the deleted calendar. I tried the following code, but I was unsuccessful:

private void deleteCalendarTest()
{
    Uri.Builder builder = Calendars.CONTENT_URI.buildUpon();
    builder.appendPath("6")   // here for testing; I know the calender has this ID
           .appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER, "true")
           .appendQueryParameter(Calendars.ACCOUNT_NAME, "private")
           .appendQueryParameter(Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);

    Uri uri = builder.build();

    getContentResolver().delete(uri, null, null);
    Toast.makeText(this, "??? deleteCalendarTest() not working", Toast.LENGTH_SHORT).show();
}

How can I fix it?


Compile Matplotlib for Python on Snow Leopard

I've killed half a day trying to compile matplotlib for python on Snow Leopard.  I've used the googles and found this helpful page (http://blog.hyperjeff.net/?p=160) but I still can't get it to compile.  I see comments from other users on that page, so I know I'm not alone.

I already installed zlib, libpng and freetype independently.

I edited the make.osx file to contain this at the top:

PREFIX=/usr/local

PYVERSION=2.6
PYTHON=python${PYVERSION}
ZLIBVERSION=1.2.3
PNGVERSION=1.2.33
FREETYPEVERSION=2.3.5
MACOSX_DEPLOYMENT_TARGET=10.6

## You shouldn't need to configure past this point

PKG_CONFIG_PATH="${PREFIX}/lib/pkgconfig"
CFLAGS="-Os -arch x86_64 -arch i386 -I${PREFIX}/include"
LDFLAGS="-arch x86_64 -arch i386 -L${PREFIX}/lib"
CFLAGS_DEPS="-arch i386 -arch x86_64 -I${PREFIX}/include -I${PREFIX}/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.6.sdk"
LDFLAGS_DEPS="-arch i386 -arch x86_64 -L${PREFIX}/lib -syslibroot,/Developer/SDKs/MacOSX10.6.sdk"

I then run:

sudo make -f make.osx mpl_build

which gives me:

export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig" &&\
    export MACOSX_DEPLOYMENT_TARGET=10.6 &&\
    export CFLAGS="-Os -arch x86_64 -arch i386 -I/usr/local/include" &&\
    export LDFLAGS="-arch x86_64 -arch i386 -L/usr/local/lib" &&\
    python2.6 setup.py build

... snip ...

gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -Os -arch x86_64 -arch i386 -I/usr/local/include -pipe -DPY_ARRAYAUNIQUE_SYMBOL=MPL_ARRAY_API -I/Library/Python/2.6/site-packages/numpy/core/include -I. -I/Library/Python/2.6/site-packages/numpy/core/include/freetype2 -I./freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6-universal-2.6/src/ft2font.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++
In file included from src/ft2font.h:13,
                 from src/ft2font.cpp:1:
/usr/local/include/ft2build.h:56:38: error: freetype/config/ftheader.h: No such file or directory

... snip ...

src/ft2font.cpp:98: error: ‘FT_Int’ was not declared in this scope
/Library/Python/2.6/site-packages/numpy/core/include/numpy/__multiarray_api.h:1174: warning: ‘int _import_array()’ defined but not used
lipo: can't open input file: /var/tmp//ccDOGx37.out (No such file or directory)
error: command 'gcc-4.2' failed with exit status 1
make: *** [mpl_build] Error 1

I'm just lost.


Does an HttpHandler require an aspnet_isapi.dll mapping

If I configure (via web.config) an httphandler to handle all .gif requests for a specific folder, is it absolutely essential for me to map .gif requests to aspnet_isapi.dll in IIS?

Is there any other way of ensuring that the .gif http request will be handled by aspnet_isapi.dll?

I have a server configured where the virtual dir that contained the .gif->aspnet_isapi.dll mapping has been deleted, but the .gif requests are still being passed to the handler.  Anyone know how this might be being done, and where the setting might be lurking?

Thanks


Handle Twitter / Facebook Authentication in App

I want users of my app to be able to authenticate with Twitter and Facebook. This way I know they are a real user. Once they've authenticated once I don't want to have to worry about them logging out or re-authenticating unless they explicitly do so.

I'm storing/displaying the users avatar image. How might I handle if the user were to update this on their given platform? My stored image URL will now be out of date correct? User would essentially have to logoff and re-authenticate in order to have their data updated which isn't ideal...


Extracting a region from an image using slicing in Python, OpenCV

I have an image and I want to extract a region from it. I have coordinates of left upper corner and right lower corner of this region. In gray scale I do it like this:

I = cv2.imread("lena.png")
I = cv2.cvtColor(I, cv2.COLOR_RGB2GRAY)
region = I[248:280,245:288]
tools.show_1_image_pylab(region)

I can't figure it out how to do it in color. I thought of extracting each channel R, G, B; slicing this region from each of the channels and to merge them back together but there is gotta be a shorter way.


Wordpress URL - Sessions, Cookies or GET using different Custom Post Types

Projetct of Advertisement System

Custom Post Types:

States/Cities - localhost/category/state/city

Coupons - localhost/site/coupons/post-name

Ads - localhost/site/ads/post-name

Enterprises - localhost/site/enterprises/post-name

Users use a select to choose state and city (it's required).

So, they are redirected to a page url like: http://localhost/sp/jundiai/

This page is a subcategory. City(Jundiaí) is children of State (SP).

Coupons, Ads and Enterprises can be from any city.
But, when I access an enterprise for example, I got this URL: http://localhost/site/enterprises/post-name. Ok but. The Loop of this page, should know that the user is at the city he choose before in the select.

I thought to use JS/HTML5 LocalStorage to set two values, then return them into PHP. But seems not possible.

localStorage.setItem('state','value');
localStorage.setItem('city','value');

So in the loop of Coupons / Ads / Enterprise, I could use these values to make de wp-query.

What I need is:

A way using sessions, cookies, localstorage or anything to "record" the state/city values and pass them to the queries.
And if user changes city, theses values also changes.

Any ideas?
Thanks!


Python 3: creating a dictionary/ adding values to a nested dictionary

thanks for help in advance!

I try to simplify my problem:
I have a nested dict looking like:
after that I wrote a for loop to calculate a ratio of the nested dict values

d={'a' :{ '1990': 10, '1991':20, '1992':30},'b':{ '1990':15, '1991':40, '1992':50}}
for key in d:
    rate = d[key]['1990']/d[key]['1992']
    print(rate)

now I would like to create a new key value pair for each nested dict, so that in the end it looks like:

d = {'a' :{ '1990': 10, '1991':20, '1992':30, 'rate':0.33333},'b':{ '1990':15, '1991':40, '1992':50, 'rate':0.3}}

or creating a new dict looking like:

d2 = {'a':{'rate':0.3333}, 'b':{'rate':0.3}}

please help with the solution easiest for you, I think adding to the existing dict would be better?

thank you!


Alternative to using LinkedQueue?

I was wondering which is the best alternative to using EDU.oswego.cs.dl.util.concurrent.LinkedQueue.

In the following situation:

public class testQueue extends LinkedQueue implements TestInterface {

public void putTestObject (TestObject to) {
    put(to);
}

Should I be using LinkedBlockingQueue or LinkedTransferQueue?

I am only using the put(), take(), and isEmpty() methods


Android, Xamarin, Rest - how to pass object in the request

I have a simple server rest endpoint running Spring -

@RestController
@RequestMapping("/services")
@Transactional
public class CustomerSignInService {

    @Autowired
    private CustomerDAO customerDao;

    @RequestMapping("/customer/signin")
    public Customer customerSignIn(@RequestParam(value = "customer") Customer customer) {
        //Some Code Here...
        return customer;
    }
}

I'm trying to pass a Customer object from my Xamarin Android App using this method -

public JsonValue send(String url, SmartJsonSerializer obj)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.ContentType = "application/json";
    request.Method = "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(obj.toJsonString());
    }

    using (WebResponse response = request.GetResponse())
    {
        using (Stream stream = response.GetResponseStream())
        {
            return JsonObject.Load(stream);
        }
    }
}

But i keep getting Bad Request Exception (Http Error 400) and obviously my code at the server side is not triggered.

SmartJsonSerializer uses JSON.NET to serialize the Customer object to string -

using System;
using Newtonsoft.Json;

namespace Shared
{
    public class SmartJsonSerializer
    {
        public string toJson()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
}

Any help appreciated,
thnx!


Delphi android java path error

I have a problem which is this:

It's different from this. Delphi was working fine but then I removed the jdk 1.8.0 and I have installed the jdk 1.9.0 because I have to work with IntelliJ IDEA (Java).

Delphi (android) is not working anymore because I've removed ( = uninstalled) the 1.8.0 jdk. How do I fix the problem? How can I tell Delphi to use the new 1.9.0 JDK?

I am using Delphi Tokyo. I have edited the windows PATH variable adding the path to the jdk (C:\Program Files\Java\jdk-9.0.1) but it's not working.


No nodes connecting to host in docker swarm

I just followed this tutorial step by step for setting up a docker swarm in EC2 -- https://docs.docker.com/swarm/install-manual/

I created 4 Amazon Servers using the Amazon Linux AMI.

manager  + consul

manager

node1

node2

I followed the instructions to start the swarm and everything seems to go ok regarding making the docker instances.

Server 1

Running docker ps gives:

The Consul logs show this

2016/07/05 20:18:47 [INFO] serf: EventMemberJoin: 729a440e5d0d 172.17.0.2
2016/07/05 20:18:47 [INFO] serf: EventMemberJoin: 729a440e5d0d.dc1 172.17.0.2
2016/07/05 20:18:48 [INFO] raft: Node at 172.17.0.2:8300 [Follower] entering Follower state
2016/07/05 20:18:48 [INFO] consul: adding server 729a440e5d0d (Addr: 172.17.0.2:8300) (DC: dc1)
2016/07/05 20:18:48 [INFO] consul: adding server 729a440e5d0d.dc1 (Addr: 172.17.0.2:8300) (DC: dc1)
2016/07/05 20:18:48 [ERR] agent: failed to sync remote state: No cluster leader
2016/07/05 20:18:49 [WARN] raft: Heartbeat timeout reached, starting election
2016/07/05 20:18:49 [INFO] raft: Node at 172.17.0.2:8300 [Candidate] entering Candidate state
2016/07/05 20:18:49 [INFO] raft: Election won. Tally: 1
2016/07/05 20:18:49 [INFO] raft: Node at 172.17.0.2:8300 [Leader] entering Leader state
2016/07/05 20:18:49 [INFO] consul: cluster leadership acquired
2016/07/05 20:18:49 [INFO] consul: New leader elected: 729a440e5d0d
2016/07/05 20:18:49 [INFO] raft: Disabling EnableSingleNode (bootstrap)
2016/07/05 20:18:49 [INFO] consul: member '729a440e5d0d' joined, marking health alive
2016/07/05 20:18:50 [INFO] agent: Synced service 'consul'

I registered each node using the following command with appropriate IP's

docker run -d swarm join --advertise=x-x-x-x:2375 consul://x-x-x-x:8500

Each of those created a docker instance

Node1

Running docker ps gives:

With logs that suggest there's a problem:

time="2016-07-05T21:33:50Z" level=info msg="Registering on the discovery service every 1m0s..." addr="172.31.17.35:2375" discovery="consul://172.31.3.233:8500"
time="2016-07-05T21:36:20Z" level=error msg="cannot set or renew session for ttl, unable to operate on sessions"
time="2016-07-05T21:37:20Z" level=info msg="Registering on the discovery service every 1m0s..." addr="172.31.17.35:2375" discovery="consul://172.31.3.233:8500"
time="2016-07-05T21:39:50Z" level=error msg="cannot set or renew session for ttl, unable to operate on sessions"
time="2016-07-05T21:40:50Z" level=info msg="Registering on the discovery service every 1m0s..." addr="172.31.17.35:2375" discovery="consul://172.31.3.233:8500"
...

And lastly when I get to the last step of trying to get host information like so on my Consul machine,

docker -H :4000 info

I see no nodes. Lastly when I try the step of running an app, I get the obvious error:

[ec2-user@ip-172-31-3-233 ~]$ docker -H :4000 run hello-world
docker: Error response from daemon: No healthy node available in the cluster.
See 'docker run --help'.
[ec2-user@ip-172-31-3-233 ~]$

Thanks for any insight on this. I'm still pretty confused by much of the swarm model and not sure where to go from here to diagnose.


JavaCPP problems compiling the example Callback function

I just wanted to test Callback function example from the webpage.

https://github.com/bytedeco/javacpp#creating-callback-functions

In file foo.cpp

#include <iostream>
#include "jniFoo.h"

int main() {
    JavaCPP_init(0, NULL);
    try {
        foo(6, 7);
    } catch (std::exception &e) {
        std::cout << e.what() << std::endl;
    }
    JavaCPP_uninit();
}

Foo.java where function foo performs

import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;

@Platform(include="<algorithm>")
@Namespace("std")
public class Foo {
    static { Loader.load(); }

    public static class Callback extends FunctionPointer {
        // Loader.load() and allocate() are required only when explicitly creating an instance
        static { Loader.load(); }
        protected Callback() { allocate(); }
        private native void allocate();

        public @Name("foo") boolean call(int a, int b) throws Exception {
            throw new Exception("bar " + a * b);
        }
    }

    // We can also pass (or get) a FunctionPointer as argument to (or return value from) other functions
    public static native void stable_sort(IntPointer first, IntPointer last, Callback compare);

    // And to pass (or get) it as a C++ function object, annotate with @ByVal or @ByRef
    public static native void sort(IntPointer first, IntPointer last, @ByVal Callback compare);
}

Building and running this sample code with these commands under Linux x86_64:

javac -cp javacpp.jar Foo.java
java -jar javacpp.jar Foo -header
g++ -I/usr/lib/jvm/java-8-oracle/include/ -I/usr/lib/jvm/java-8-oracle/include/linux/ linux-x86_64/libjniFoo.so foo.cpp -o Foo

In the third command, I got error:

/tmp/ccvrmILI.o: In function `main':
foo.cpp:(.text+0x14): undefined reference to `JavaCPP_init'
foo.cpp:(.text+0x1e): undefined reference to `onAddTwoInteger'
foo.cpp:(.text+0x23): undefined reference to `JavaCPP_uninit'
collect2: error: ld returned 1 exit status

Why do I get it?


Close JDialog from JavaFx Button

I need to close my JDialog from JavaFx Button defined in my FXML file.
I post code of my class called by Main Application:

ExampleWindow.java

public class ExampleWindow extends JDialog
{
@FXML
Button closeButton;

public ExampleWindow()
{
}

public void initAndShowGUI()
{
    final JFXPanel fxPanel = new JFXPanel();
    add(fxPanel);

    Platform.runLater(new Runnable()
    {
        @Override
        public void run()
        {
            AnchorPane parent = null;
            FXMLLoader fxmlLoader = new FXMLLoader();

            fxmlLoader.setRoot(this);
            try {
                parent = fxmlLoader.load(getClass().getResource("WindowControlPanel.fxml"));
            }
            catch (IOException e) {
                e.printStackTrace();
            }

            scene = new Scene(parent);
            fxPanel.setScene(scene);
        }
    });
}

public void onAction(ActionEvent ac)
{
this.dispose();
}

}

Method onAction is called by JavaFx Button (on FXML file)

WindowControlPanel.fxml

<AnchorPane id="AnchorPane" fx:id="windowPanel" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="50.0" prefWidth="1024.0" style="-fx-border-color: white, grey; -fx-border-width: 2, 1; -fx-border-insets: 0, 0 1 1 0" xmlns:fx="http://javafx.com/fxml" fx:controller="ExampleWindow">
<children>
<FlowPane alignment="CENTER_RIGHT" columnHalignment="CENTER" prefHeight="50.0" prefWidth="1024.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
  <children>
    <Button fx:id="closeButton" mnemonicParsing="false" onAction="#onAction" prefHeight="35.0" prefWidth="100.0" text="Close">
      <FlowPane.margin>
        <Insets bottom="5.0" left="20.0" right="20.0" top="5.0" />
      </FlowPane.margin>
    </Button>
  </children>
</FlowPane>
</children>
</AnchorPane>

When I pressed closeButton, method onAction is correctly called, but my JDialog doesn't close. Any ideas? Where am I wrong?


Insert "-" in the name of all files in a folder at position 4 and 6

I got a bunch of PDFs in a folder which must be renamed. They are all built like this: YYYYMMDD_Text.pdf. The system is Windows 7.

I want to insert a - between the dates, so the documents look like:
YYYY-MM-DD_Text.pdf.

This is what I got, but it's not working and I searched a dozen threads but could not find the solution:

    Ordner = "C:\xte Stelle\Test Doku"

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Fld = fso.GetFolder(Ordner)

    For i = 0 To UBound(Arr)
        WScript.Echo i & vbTab & Arr(i)
    Next

    For Each File In Folder.Files
        File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 6) & "-" & Mid(File.Name, 8)
End Sub

Edit:

This is what I got now. I can run it and it does not crash, but does not function either. It simply does nothing. Any idea on that?

Ordner = "C:\xte Stelle\Test Doku"

Set fso = CreateObject("Scripting.FileSystemObject")
Set Fld = fso.GetFolder(Ordner)

Sub test
    For Each File In Fld.Files
        File.Name = Left(File.Name, 4) & "-" & Mid(File.Name, 5, 2) & "-" & Mid(File.Name, 7)
    Next
End Sub


Differences between Sphinx local and readthedocs.org

I have created a set of documentation for my Django app using Sphinx. I use readthedocs.org to create a public version of that documentation. This works well but for one oddity. On readthedocs.org some of my documentation generates differently from a local build. For example for my models.py I created models.rst, which looks like this:

Models
======

.. automodule:: my_app.models

Agents
------

Agent
`````
.. autoclass:: Agent
   :members:

etc...

For a local build this creates a document with model names as titles, their docstring and their members with docstrings where a #: comment... was added.

However on readthedocs.org only a title entry for each model is generated and nothing more.

It appears as if readthedocs.org ignores the automodule and autoclass directives.

Initially I thought this was caused by the difference in theme (I use the bootstrap theme locally and the readthedocs theme on readthedocs.org), but after setting up a virtualenv on readthedocs.org and using the bootstrap theme there as well, nothing changed. The build completes, but documentation for my models remains absent.

Locally I use Sphinx 1.2.2. I'm not sure which version is used on readthedocs.org but I presume a 1.2.x release.

Any ideas on what might cause this?


Cloud performance vs Desktop

I have developed an app to analyze videos using OpenCV and Visual Studio 2013.  I was planning to run this app in the Azure assuming that it will run faster in cloud.  However, to my surprise, the app ran slower than my desktop, taking about twice the time when I configured the Azure instance with 8 cores.  It is a 64-bit app, compiled with appropriate compiler optimization.  Can someone help me understand why am I losing time in the cloud, and is there a way to improve the timing there?

The app takes as input a video (locally in each case) and outputs a flat file with the analysis data.

I am not sure why people are voting to close this question.  This is very much about programming and if possible, please help me in pinpointing the problem.


Create Trac ticket from Google Form GAS script?

This is a followup question to my original question here.  The decision between Bugzilla & Trac seems to have been made for us, and Trac it is.  Here are the options I've found so far:

Leverage our current Google Form based bug report by modifying the GAS script that is doing our email notification.  So far I've been unable to find an example, but it would appear that you can modify the email portion of the GAS script to send email to the Trac server to open a ticket automatically.  This is my preferred option, but I'd like to see an example if possible.

Create something using TracCmdScript, but the site hasn't been updated in three years, and it appears to use python, a language I'm not proficient at (although I'd like to be) and the XmlRpcPlugin, which seems to be under current development.

There's also an email option website cited on this SO page to use email2trac, but the cited site appears to be dead.  Edit: here's the new site:  email2trac which still hasn't been touched in a couple of years, but seems to be functional.

I'm open to any other suggestions the SO folks might have.


Bringing up the iPad keyboard which is predominantly symbols

Apologies in advance if this is answered but I genuinely couldn't find it.  I'm trying to bring up the keyboard type on iPad which appears when pressing the "#+=" button.  I've tried going through all the types on the docs and I'm sure that this wasn't successful.  Am I missing something or does the user have to click this button every time?

Edit: this question was closed as "off-topic" because it didn't include code or ideas or what I've tried already...  Therefore for a bit of extra detail, I used EVERY keyboard type that is available on the docs e.g.

theTextField.keyboardType = UIKeyboardTypeNumberPad;

This did not yield the results that I require, which is the keyboard plane that appears when you press the #+= button because I wanted users to go straight to that one.


How to create an image pattern for a path with Snap.svg?

Failing to create an image pattern for a path element through Snap.svg library. Is it possible?

Creating a Paper.image() and then trying to call Element.pattern() on it doesn't seem to be an option or a working solution.

So i wonder whether it's possible to do so using Snap.svg lib. or Should i generate the needed ,  elements myself and then append them to the needed svg 'by hands'?

Thanks in advance!


Error with Ruby Exception

I have an array defined like this,

result = ["true","false","false","false"]

In my code I iterate through the array and raise an exception when i come across false.

begin  result.each  do |method|
           raise  if (method == false) {
           rescue Exception => Form_Validation_Failure
                  puts "fail!"
           end }
       end

There is an error when i execute the code.Is this is the right way to raise and exception in  Ruby? Could somebody help with this please.

Cheers!


Ng-Change Not firing second time

I have the following select:

    <div class="form-group">
            <label class="col-md-4 control-label" for="activity">Activity</label>
            <div class="col-md-4">
                <select id="activity" name="activity" class="inputsvalues" ng-model="activitymodel.deptid" ng-change="getUsers(activitymodel.deptid)" ng-options="activity.DepartmentId as activity.ActivityDescription for activity in activities"></select>
            </div>
        </div>

The controller code:

    $scope.getUsers = function (id) {

    $http({
        method: 'GET',
        url: 'api/User/GetUsers/' + id,

    }).success(function (data, status, header) {
        $scope.users = data;

    }).error(function (data, status, headers, config) {
        $scope.status = status + ' ' + headers;
    });

}

The problem is that the ng-change function gets fired the first timeI select something. Second time onwards, it doesnt hit the controller. What could be wrong here?


BlackBerry - Create image viewer

I need to create an image slideshow in my app (i.e. the image should be changed at a regular interval of time with a fade in / fade out effect).  I have tried some code, but it throws illegal exception.

Is there any option to change images in picture scroll field programatically?  i.e. from a thread or something?

public class SlideTransition extends MainScreen {

    final Bitmap image000 = Bitmap.getBitmapResource("img1.jpg");
    final Bitmap image001 = Bitmap.getBitmapResource("img2.jpg");
    final Bitmap image002 = Bitmap.getBitmapResource("img3.jpg");

    final BitmapField animationField = new BitmapField(image000);
    int counter = 0;
    Timer animationTimer = new Timer();
    TimerTask animationTask;

    public SlideTransition() {
        animationTask = new TimerTask() {

            public void run() {
                if (counter == 0) {

                    animationField.setBitmap(image000);
                }

                if (counter == 1) {
                    animationField.setBitmap(image001);
                }
                if (counter == 2) {
                    animationField.setBitmap(image002);
                    counter = -1;
                }
                counter++;
            }
        };
        animationTimer.scheduleAtFixedRate(animationTask, 0, 100);
        add(animationField);
    }
}


Android IMAGE_CAPTURE always returns Activity.RESULT_CANCELED

I want to take a photo in my app. On the emulator everything works fine.
But on the tablet, the Intent immediately returns Activity.RESULT_CANCELED in onActivityResult. The picture is saved on the SD Card.

Here is the code for taking picture:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String tmpFile = CommonFunctions.generateRandomFileName() + ".jpg";
String fileName = CommonFunctions.getNoticeSavePath() + tmpFile;
System.out.println("Filename " + fileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(fileName)));
notice.setBild(tmpFile);
startActivityForResult(intent, RESULT_PICTURE);

Code for onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

        case RESULT_PICTURE:
            System.out.println("ResultCode" + resultCode);
            if (resultCode == Activity.RESULT_OK) {

            }
            else if (resultCode == Activity.RESULT_CANCELED){
                notice.setBild("");
                Toast.makeText(getBaseContext(), "Bild wurde nicht hinzugefügt", Toast.LENGTH_LONG).show();
            }
            break;
        }
    }

Permissions are set:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>

The result is always RESULT_CANCELED, but the photo is stored correctly on the sd card.
What could the problem be?


Lambda data frame reference a value in another column

How do I correctly reference another column value when using a Lambda in a pandas dataframe.

dfresult_tmp2['Retention_Rolling_temp'] = dfresult_tmp2['Retention_tmp'].apply(lambda x: x if x['Count Billings']/4 < 0.20 else '')

The above code gives me this error.

TypeError: 'float' object is not subscriptable


tracking down AWT exception in Clojure UI app under Leiningen

Referring to this SO question on a first UI program in Clojure, I created a new Leiningen app project:

lein new app a-ui-app

copied the source into the core.clj that leiningen generated and modified the -main routine to call it

(defn -main
  "See https://stackoverflow.com/questions/2792451/improving-my-first-clojure-program?rq=1."
  [& args]
  ;; work around dangerous default behaviour in Clojure
  (alter-var-root #'*read-eval* (constantly false))

  (doto panel
        (.setFocusable true)
        (.addKeyListener panel))

  (doto frame
        (.add panel)
        (.pack)
        (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
        (.setVisible true))

  (loop []
        (draw-rectangle panel @x @y)
        (Thread/sleep 10)
        (recur))
  )

I then run it via either

lein run

or

lein uberjar
java -jar ./target/a-ui-app-0.1.0-SNAPSHOT-standalone.jar

In both cases, the app works well, but in the terminal that I used to start it up, I get an exception after a random delay of several seconds:

Exception in thread "AWT-EventQueue-0"
  java.lang.IllegalArgumentException: No matching clause: 157 at
  a_ui_app.core$fn__16$fn__21$fn__22.invoke(core.clj:19) at
  clojure.lang.AFn.call(AFn.java:18) at
  clojure.lang.LockingTransaction.run(LockingTransaction.java:263) at
  clojure.lang.LockingTransaction.runInTransaction(LockingTransaction.java:231)
  at a_ui_app.core$fn__16$fn__21.invoke(core.clj:17) at
  a_ui_app.core.proxy$javax.swing.JPanel$KeyListener$6c415903.keyPressed(Unknown
  Source) at java.awt.Component.processKeyEvent(Component.java:6340) at
  javax.swing.JComponent.processKeyEvent(JComponent.java:2809) at
  a_ui_app.core.proxy$javax.swing.JPanel$KeyListener$6c415903.processKeyEvent(Unknown
  Source) at java.awt.Component.processEvent(Component.java:6159) at
  java.awt.Container.processEvent(Container.java:2083) many more
  lines...

I made no changes to project.clj -- just used the leiningen-generated one.

I'd like to understand what's going on.  I am by no means knowledgeable in Java Threading.  Is the problem related to the way leiningen launches the app's Java threads?  Is it unavoidable?  If not, how can I fix it, both for this little sample program and going forward, as a project pattern for future projects using the UI thread (which I think is AWT-EventQueue-0).


Right to left asp.net menu - Help me setup my CSS

Coders, I am trying to style my Asp.net menu control and I have a set of CSS definitions that styles my menu:
Here is the CSS:

.MainMenu
{

    background: url("http://cables.com.sa/en/ddtabmenufiles/media/blockdefault.gif") repeat-x scroll center center black;
    border-color: #625E00;
    border-style: solid;
    border-width: 1px 0;
    float: right;
    font: bold 13px Arial;
    margin: 0;
    padding: 0;
    width: 100%;
}

.MainMenu a {
    float: right;
}

.MainMenu li {
    display: inline;
    float: right;
}

.MainMenu li a {
    border-right: 1px solid white;
    color: white;
    float: right;
    padding: 9px 11px;
    text-decoration: none;
}

.MainMenu li a:visited
{
    color: white;
}

.MainMenu li a:hover, .MainMenu li a.current {
    background: url("http://cables.com.sa/en/ddtabmenufiles/media/blockactive.gif") repeat-x scroll center center transparent;
    color: white;
}

And here is the Asp.net ClusterManagerpage code:

    <asp:Menu ID="NavigationMenu" runat="server" CssClass="MainMenu" EnableViewState="False"
        IncludeStyleBlock="False" Orientation="Horizontal">
        <Items>
            <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" />
            <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
        </Items>
    </asp:Menu>

Notice that in the CSS I have setup the floating to be ‘float: right’ because I am using this CSS style for an Arabic menu (ie: text direction: right to left + float: right). But the problem is that my menu items are still showing on the left side.

My question is, how do I set my CSS to show my menu items on the left side?

Remarks: I want my menu items to appear like this website:
www.tech-nuke.com
And I am taking my current style from:
http://cables.com.sa/en/index.php?p=home

Thanks in advance.


Select distinct records with Min Date from two tables with Left Join

I'm trying to retrieve all distinct AccountId’s as well as the earliest InsertDate for each.  Occasionally the AccountId is not known and although the transactions may be distinct I want to bucket all of the ‘-1’s into their own group.

This is what I have attempted so far along with the schemas.

    CREATE TABLE #tmpResults (
        Trans Varchar(12),
    AccountId Varchar(50),
EarlyDate DateTime DEFAULT getdate(),                                                                               CardType Varchar(16))

insert #tmpResults
        select [Trans]                              = convert(varchar(12),'CashSale')
        ,   [AccountId]                             = b.AccountId
        ,   [EarlyDate]                             = min(b.InsertDate)
        ,   case when c.name LIKE '%VISA%'      then 'VISA'
                    when c.name LIKE '%MasterCard%' then 'MasterCard'
                    when c.name LIKE '%AMEX%'       then 'AMEX'
                    else 'Other'
            end as [CardType]
        from TransBatch b
        left join CardVer_3 c WITH (NOLOCK) ON c.Id = B.BatchId
        left join TransBatch b2
        on (b.accountid = b2.accountid and (b.InsertDate > b2.InsertDate or b.InsertDate = b2.InsertDate))
        and b2.accountid is NULL
        group by b.accountid, b.InsertDate,c.name
        order by b.accountid DESC

        select * from  #tmpResults

The table schemas are like so:

**TransBatch**
RecordId    |BatchId    |InsertDate     | AccountId     | AccNameHolder
6676    |   11  |   2012-11-01 05:19:04.000 |   12345   |   Account1
6677    |   11  |   2012-11-01 05:19:04.000 |   12345   |   Account1
6678    |   11  |   2012-11-01 05:19:04.000 |   55555   |   Account2
6679    |   11  |   2012-11-01 05:19:04.000 |   -1  |   NULL
6680    |   12  |   2012-11-02 05:20:04.000 |   12345   |   Account1
6681    |   12  |   2012-11-02 05:20:04.000 |   55555   |   Account2
6682    |   13  |   2012-11-04 06:20:04.000 |   44444   |   Account3
6683    |   14  |   2012-11-05 05:30:04.000 |   44444   |   Account3
6684    |   14  |   2012-11-05 05:31:04.000 |   -1  |   NULL

**CardVer_3**
BatchId     |Name
11      |MasterCard
12      |Visa
13      |AMEX
14      |GoCard

This will be an intermediate table, the output is planned to look like the attached.


Nil NSString method

I have an NSString that is stored in Core Data. It is optional, which I believe in the sqlite db means it can be null. I have a convenience method I call 'isEmptyOrWhitespace' shown here:

- (BOOL)isEmptyOrWhiteSpace {
    return self == nil ||
    self.length == 0 ||
    [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0;
}

When my string from Core Data is nil, it doesn't seem to call this method, that is the breakpoints are never hit. This is particularly annoying because a code chunk like this:

if(![string isEmptyOrWhitespace]) {
    [string doSomething];
}

doSomething is being run if string is nil, obviously not my intent. Is there a way to get around this without checking if my string is nil before calling a method on it? Or is this a "feature" of Objective-C that methods aren't run on nil objects?


Unit testing a jee filter

I am trying to test this filter:

public class HttpMethodOverrideHeaderFilter extends OncePerRequestFilter {
    private static final String X_HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (isMethodOverriden(request)) {
            HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER).toUpperCase(Locale.ENGLISH));
            filterChain.doFilter(wrapper, response);
        }
        else {
            filterChain.doFilter(request, response);
        }

    }

    private boolean isMethodOverriden(HttpServletRequest request) {
        String methodOverride = request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER);
        return RequestMethod.POST.name().equalsIgnoreCase(request.getMethod()) &&
                (RequestMethod.PUT.name().equalsIgnoreCase(methodOverride) || RequestMethod.DELETE.name().equalsIgnoreCase(methodOverride));
    }

    protected static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }

        @Override
        public String getMethod() {
            return this.method;
        }
    }

}

And this is the unit test:

@RunWith(MockitoJUnitRunner.class)
public class HttpMethodOverrideHeaderFilterTest {

    private static final String X_HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override";

    private HttpMethodOverrideHeaderFilter httpMethodOverrideHeaderFilter;

    @Mock
    private HttpServletRequest httpServletRequest;

    @Mock
    private HttpServletResponse httpServletResponse;

    @Mock
    private FilterChain filterChain;

    @Before
    public void setUp() {
        httpMethodOverrideHeaderFilter = new HttpMethodOverrideHeaderFilter();
    }

    @Test
    public void testDoFilterInternalWithPUTMethodAsOverrideHeader() throws Exception {
        when(httpServletRequest.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER)).thenReturn("PUT");
        when(httpServletRequest.getMethod()).thenReturn("POST");

        HttpServletRequest wrapper = new HttpMethodOverrideHeaderFilter.HttpMethodRequestWrapper(httpServletRequest, "PUT");

        httpMethodOverrideHeaderFilter.doFilterInternal(httpServletRequest, httpServletResponse, filterChain);
        verify(filterChain).doFilter(wrapper, httpServletResponse);
    }

}

The test is not passing as wrapper is not the same instance. Basically what I need to know is if the wrapper was set the PUT method. Any ideas?


Laravel Homestead composer errors

When I try to 'vagrant up' on a Homestead 5 box following the instructions on http://laravel.com/docs/5.0/homestead ,I get the following error. I am behind a proxy, however I believe I have it setup correctly in the Vagrantfile.

I have not installed composer locally (as the instructions did not include this), is that something I need to do?

Is there a way to confirm this is not an issue with my proxy settings in Vagrantfile?

==> default:   [Composer\Downloader\TransportException]

==> default:   The "https://getcomposer.org/version" file could not be downloaded: failed to open stream: Cannot connect to HTTPS server through proxy

==> default:

==> default:

==> default:

==> default: self-update [-r|--rollback] [--clean-backups] [--no-progress] [version]
The SSH command responded with a non-zero exit status. Vagrant
assumes that this means the command failed. The output for this command
should be in the log above. Please read the output to determine what


Convert Pdf to Image as per the pdf page

I want to upload a pdf then after I want to convert to image as per the pdf page means that If pdf have 2 pages then 2 images will generate.

After generate this image I want to store into table.

For example

I have a pdf table in that I upload a PDF and another table is image that I want to store pdf's images that newly generated.

I just need help for how to generate images from pdf as per the page

so How can i do this?

Please Help me?

Thanks


Play Framework: How to validate a subset of fields in an object?

I have an User object that has many attributes. In my edit profile screen I'm displaying a subset of those attributes. In the corresponding controller action how can I validate only those fields that are being edited and not all the fields in the User object?

I have annotated the fields in the User object with the MaxSize, Email, URL, etc. constraints and don't want to repeat them again by validating each field manually.

Any pointers would be greatly appreciated. Thanks!


PowerShell match names with user email addresses and format as mailto

So i have the below script which scans a drive for folders, it then pulls in a csv with folder names and folder owners and then matches them and outputs to HTML.

I am looking for a way to within this use PS to look up the users names in the csv grab their email address from AD and then in the output of the HTML put them as mailto code.

function name($filename, $folderowners, $directory, $output){
  $server = hostname
  $date =  Get-Date -format "dd-MMM-yyyy HH:mm"
  $a = "<style>"
  $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color:black;}"
  $a = $a + "Table{background-color:#ffffff;border-collapse: collapse;}"
  $a = $a + "TH{border-width:1px;padding:0px;border-style:solid;border-color:black;}"
  $a = $a + "TR{border-width:1px;padding-left:5px;border-style:solid;border-
  color:black;}"
$a = $a + "TD{border-width:1px;padding-left:5px;border-style:solid;border-color:black;}"
$a = $a + "body{ font-family:Calibri; font-size:11pt;}"
$a = $a + "</style>"

$c = " <br></br> Content"

$b = Import-Csv $folderowners
$mappings = @{}
$b | % { $mappings.Add($_.FolderName, $_.Owner) }

Get-ChildItem $directory | where {$_.PSIsContainer -eq $True} | select Name,
@{n="Owner";e={$mappings[$_.Name]}} | sort -property Name |
ConvertTo-Html -head $a -PostContent $c |
Out-File $output
}

name "gdrive" "\\server\location\gdrive.csv" "\\server\location$"
"\\server\location\gdrive.html"


Access a mesos-cluster-manager behind a domain name (not an IP)

Is it possible to run and access a mesos cluster manager on a machine that is placed behind a proxy?

I have successfully succeeded to deployed a MesosClusterManager/Marathon/MesosSalve on my local infrastructure.

The problem arises when I want to put the MesosSlave somewhere in the internet, so that MesosSlave and MesosClusterManager shall communicate through public IPs

My conf is the following:

              Internet                                                                          My Infra

      .----------------------.                   .-----------------.    .-----------------.              .-------------------------------------------------.
      |    Mesos Slave VM    |                   |  Front Machine  |    |      Proxy      |              |                     Tool-VM                     |
      |    178.22.17.248     |                   |  39.224.147.94  |    |    10.2.0.57    |              |                   10.1.10.176                   |
      |----------------------|                   |  my.domain.com  |    |-----------------|              |           192.168.5.1 (docker bridge)           |
      |                      |                   |-----------------|    |                 |              |-------------------------------------------------|
      |                      |                   |                 |    |                 |              |                                                 |
      |       __________     |                   | __________      |    | __________      |              |                 .-----------------------------. |
      |      [_...__..5051.°]|                   |[_..5050.__...°] |<---|[_..5050.__...°] |<------------^|                 |   Mesos-cluster-manager Container    | |
      |                      |                   |                 |    |                 |              \ __________      | 192.168.5.4 (docker bridge) | |
      |                      |                   | __________      |    | __________      |              |[_..5050.__...°]^|-----------------------------| |
      |                      |                   |[_..2181.__...°] |<---|[_..2181.__...°] |<------------^|                 \ __________                  | |
      |                      |                   |                 |    |                 |              \ __________      |[_..5050.__...°]             | |
      |                      |                   |                 |    |                 |              |[_..2181.__...°]^| __________                  | |
      |                      |                   |                 |    |                 |              |                 \[_..2181.__...°]             | |
      |                      |                   |                 |    |                 |              |                 '-----------------------------' |
      '----------------------'                   '-----------------'    '-----------------'              '-------------------------------------------------'

However:

My domain infra redirect everthing that arrives from outside on ports 5050 (for Mesos) and port 2181 (zookeeper) ONLY for requests that are addressed to the domain 'my.domain.com' (which is a virtualhost of  39.224.147.94). But not for the other requests (that are arriving on 39.224.147.94).

So I try to execute the service through CLI for the moment:

Execute Mesos Cluster Manager(in Mesos Cluster Manager Container)

/usr/sbin/mesos-cluster-manager --ip=192.168.5.4 --work_dir=~/Mesos/mesos-0.23.0/workdir/ --zk=zk://192.168.5.4:2181/mesos --quorum=1 --log_dir=/var/log/mesos --external_log_file=/dev/stdout

Execute Marathon (in Mesos Cluster Manager Container)

/usr/bin/marathon --zk zk://192.168.5.4:2181/marathon --cluster-manager zk://my.domain.com:2181/mesos

Execute Mesos Slave (in Mesos Slave VM)

/usr/sbin/mesos-slave --cluster_manager=my.domain.com:5050 --work_dir=/var/lib/mesos/agent --port=8009  --containerizers=docker  --executor_registration_timeout=3mins --log_dir=/var/log/mesos

The Mesos Cluster Manager can see the Slave resources.
However, when I send a Job through Marathon, this job stay in a waiting state.

It seems that the slave is not able to communicate on the hostname of the Cluster Manager, but only using it's public IP:

I have this in the Slave logs:

New cluster_manager detected at cluster_manager@39.224.147.94:5050

However incoming traffic on 39.224.147.94:5050 is blocked by my infra (only my.domain.com:5050 is accepted)

So, is it possible to create a connection between Cluster Manager and Slaves, using domain names, but not IPs?


Color Text Only Partially Working

When I input something like:

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

the output I get is:

With no color.

I've heard you any need to enable vt100 emulation for windows, but when I search for how to do that, I haven't seen any answers.

All answers are very appreciated!


Java : image processing - how to get set of images to same standard

I need to develop the simple skin disease diagnose system using  image processing and neural network. To use images in neural network, image should be same standard and, To identify the skin disease we should apply some image processing technique as well.

But I don't know what image processing technique apply first and what are they?
 As I read from references I think I need to apply image filtering technique, edge detection technique , etc...

Can someone who is expert in this please specify the image processing technique step by step. no need coding I just want to know image processing technique names and there order.

This is reference:
reference