Concourse CI windows/strict mime type checking

When running concourse ci v3.3.2 locally on Windows I get these errors:

Refused to execute script from
  'http://192.168.178.29:8080/public/index.js?id=932c553753eec4ef375e1c17f4b28c10' because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled.
  192.168.178.29/:1 Refused to execute script from 'http://192.168.178.29:8080/public/d3.v355.min.js?id=5936da7688d010c60aaf8374f90fcc2b' because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled.
  192.168.178.29/:1 Refused to execute script from 'http://192.168.178.29:8080/public/graph.js?id=3e2a3f561ec6c52216e80266ef0212d2' because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled.
  192.168.178.29/:1 Refused to execute script from 'http://192.168.178.29:8080/public/jquery-2.1.1.min.js?id=e40ec2161fe7993196f23c8a07346306'
  because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled.
  192.168.178.29/:1 Refused to execute script from 'http://192.168.178.29:8080/public/concourse.js?id=b4688d002041187f6c55f6e8699442ba' because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled. (index):1 Refused to execute script
  from
  'http://192.168.178.29:8080/public/elm.min.js?id=d38f054604f3aaf5cd4eb0616b3cb3ef' because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled. (index):20 Uncaught ReferenceError: Elm
  is not defined
      at (index):20

It's probably something obvious but couldn't find anything on google/stack overflow for these errors in combination with Concourse


Android - hidden text --> show text for 2 seconds --> hide text again

I am developing a board game that user plays with android. Since android is quite fast, I want to fake that android is performing some tough calculations and thus needs time for its next move.

What I want to do:-

User turn - he moves.

Android turn - android shows text "I am thinking" for 2 seconds

Android hides that text and and only after that moves his turn.

I tried doing:-

onAndroidTurn(){
    textView1.setVisibility(View.VISIBLE);
    Thread.sleep(2000);
    textView2.setVisibility(View.GONE);
}

But what happens is that thread sleeps but text is not shown (okay I know why).

Then searching on stackoverflow, I learnt a way:-

onAndroidTurn(){
    textView1.setVisibility(View.VISIBLE);
    new Handler().postDelayed(new Runnable(){
            void run() {
                textView1.setVisibility(View.GONE);
            }
    }, 2000);
}

Now what this does is that it runs that text in another thread and android's turn is updated on screen and after moving it's turn android showing "Thinking" is total stupidity.

What can I do for this?


AngularJS does not evaluate expression

I am beginner in AngularJS, so I try to run basic code. However, this simple code does not work in a way I want. The html code is the following:

<!DOCTYPE html>
<html ng-app>
<head>
  <script src="js/angular.min.js"></script>
  <script>
    function MyFirstCtrl($scope) {
      var employees = ['Jon Doe', 'Abe Lincoln', 'Hugh Grant'];
      $scope.ourEmployees = employees;
    }
  </script>
</head>
<body ng-controller='MyFirstCtrl'>
  <h2>Number of Employees: {{ourEmployees.length}}</h2>
</body>
</html>

I'd expect that the correct result is Number of Employees: 3
Instead of this, the browser (both Firefox and Edge) shows the following: Number of Employees: {{ourEmployees.length}}. Since other simple codes did work, the problem is surely not the reference to the angular.min.js file.

Thanks in advance.


Disable Volley logs in Android application

The problem

I'm developing a SDK with using the Volley library for http(s) calls.

I'm able to hide my application logs using a customize Log class wrapper,  and I would like to disable every log level printing of Volley, because it might expose sensitive information sent by HTTPS.

I know you can use proguard to disable logging of application, but I also want to be able to toggle logging on and off from the server side for debugging specific scenarios.

What have I tried

I took a look at the source, and it seems that the DEBUG flag in the VolleyLog class only changes the log level, but keeps ERROR calls in the log, so it isn't a solution for me.

Is it possible to hide all Volley logs ?


How to properly setup CucumberJS in a rails app with backbone front-end developed with backbone-on-rails gem

I am developing a rails 3.2 app with Cucumber/capybara/rspec and the backbone-on-rails gem for front-end dev. I would like to use CucumberJS and Jasmine for testing the front-end, but I can't manage to properly setup CucumberJS.


Why is not the MongoId 12-byte long but the 24-byte?

According to the official document:

A BSON ObjectID is a 12-byte value
  consisting of a 4-byte timestamp
  (seconds since epoch), a 3-byte
  machine id, a 2-byte process id, and a
  3-byte counter

But actually it's a 24-byte value like 4d7f4787ac6d604009000000

Why does this happen ?


Getting TypeError: 'NoneType' object is not iterable when sending ajax post request django views

I want to print the list of all my checked choices in my django view function,but when i send throught ajax selected data,i get the following error in my console:

Traceback (most recent call last):
  File "C:\Users\lislis\DJANGO~2\DJANGO~1.2\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\lislis\DJANGO~2\DJANGO~1.2\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\lislis\DJANGO~2\DJANGO~1.2\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\lislis\Django-VEnvs-Projects\django 1.11.2\src\rapport_sante\papa\views.py", line 78, in stat_ajax
    for d in tb_ids:
TypeError: 'NoneType' object is not iterable
[12/Aug/2017 11:53:07] "POST /sante/stat-ajax/ HTTP/1.1" 500 19573

Here is a part of my ajax post request:

  var data =[];
            $(":checkbox:checked").each(function() {
                data.push($(this).val());
            });

        if(data.length==0)
        {
            alert("Veuillez cocher au moins une dps");
            alert(data.length);
        }
        else
        {

              $.ajax({
        url: "{% url 'papa:stat-ajax' %}",
        type:"post",
        data: {dpsID:data,csrfmiddlewaretoken: '{{ csrf_token }}'},
        success:function(data)
        {
            //Some code
        }
      });

Here is my view function,where i would like to display all the data contained in the dpsID of my ajax POST request:

def stat_ajax(request):
    tb_ids=request.POST.get('dpsID')
    for d in tb_ids:
        print(d)


List all system certificate stores

I'm looking for a way to get all system certificate stores, in any location  (CurrentUser or LocalMachine).

The StoreLocation enumeration clearly won't include user-defined certificate stores created with X509Store(String) or X509Store(String, StoreLocation). Also this doesn't define other standard stores such as SPC or Request.

I've looked at the crypto32.dll API and I couldn't see anything relevant in there apart from register/unregister.

Non file-system based stores appear in the registry (eg HKEY_CURRENT_USER\SOFTWARE\Microsoft\SystemCertificates\Root). The PowerShell Certificate Provider can interrogate stores. Is this -- querying the registry -- what it's doing under the hood? Would such a hand-rolled solution be portable between XP/Vista/7/8?


Wait for user action in while loop - JAVA

I am writing a Reversi application. I implemented the turns manager class, but I have a little problem in the while loop.

This is my snippet:

while (!table.isFull() || passFlag != 2) {
    if (player1.isActive()) {
        for (int i = 0; i < table.getSize(); i++) {
            for (int j = 0; j < table.getSize(); j++) {
                table.getField(i, j).addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                if (e.getSource() instanceof Field) {
                                    ((Field) e.getSource()).changeToBlack();
                                }
                            }
                        });
            }
        }
    }
    if (player2.isActive()) {
        for (int i = 0; i < table.getSize(); i++) {
            for (int j = 0; j < table.getSize(); j++) {
                table.getField(i, j).addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                if (e.getSource() instanceof Field) {
                                    ((Field) e.getSource()).changeToWhite();
                                }
                            }
                        });
            }
        }
    }
    sentinel.changeActivePlayer(player1, player2);

The table is a grid of buttons, and the fields are the buttons. The loop does not wait for the player interaction. How can I implement the code so that it waits for the user's mouse click?

This is the full code of this class

package Core;

import GUILayer.Field;
import GUILayer.MainFrame;
import elements.Player;
import elements.Table;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TurnManager {

    int passFlag = 0;
    int TurnFlag = 0;
    Sentinel sentinel = new Sentinel();

    public TurnManager() {
    }

    public void manage(MainFrame mainframe, Table table, Player player1, Player player2) {

        while (!table.isFull() || passFlag != 2) {
            if (player1.isActive()) {
                for (int i = 0; i < table.getSize(); i++) {
                    for (int j = 0; j < table.getSize(); j++) {
                        table.getField(i, j).addActionListener(
                                new ActionListener() {

                                    public void actionPerformed(ActionEvent e) {
                                        if (e.getSource() instanceof Field) {
                                            ((Field) e.getSource()).changeToBlack();
                                        }
                                    }
                                });
                    }
                }
            }
            if (player2.isActive()) {
                for (int i = 0; i < table.getSize(); i++) {
                    for (int j = 0; j < table.getSize(); j++) {
                        table.getField(i, j).addActionListener(
                                new ActionListener() {

                                    public void actionPerformed(ActionEvent e) {
                                        if (e.getSource() instanceof Field) {
                                            ((Field) e.getSource()).changeToWhite();
                                        }
                                    }
                                });
                    }
                }
            }
            sentinel.changeActivePlayer(player1, player2);
        }
    }
}


Search with grep SQL numeric data types

I'm trying to do a grep to list all files in a directory containing a specific string variation on a linux system.  The files are DDLs for stored procedures and I'm looking for all files that have a NUMERIC or DECIMAL declaration with a precision of 2 (i.e.  DECIMAL(x,2) or NUMERIC(x,2)).  Case insensitive, and Whitespace is to be ignored.

Examples:

DECIMAL(13,2)
DECIMAL(13, 2)
DECIMAL( 13, 2 )
Decimal(13 , 2)
DECIMAL     ( 13, 2    )
NUMERIC(13         , 2)
numeric ( 13 , 2)
NUMERIC(8,2      )
CAST(INT (PURCHASE_DATE ) AS NUMERIC(8,0)) AS BUYDATE;

What I've come up with thus far is:

grep --include='*.DDL' -inP 'sproc' -e '.*Numeric|Decimal *\( *[0-9] *\, *2 *\).*'

But of course, its not working and I'm simply missing the reason why.  Any help would be greatly appreciated.


Extracting an element of a list in a pandas column

I have a DataFrame that contains a list on each column as shown in the example below with only two columns.

    Gamma   Beta
0   [1.4652917656926299, 0.9326935235505321, float] [91, 48.611034768515864, int]
1   [2.6008354611105995, 0.7608529935313189, float] [59, 42.38646954167245, int]
2   [2.6386970166722348, 0.9785848171888037, float] [89, 37.9011122659478, int]
3   [3.49336632573625, 1.0411524946972244, float]   [115, 36.211134224288344, int]
4   [2.193991200007534, 0.7955134305428825, float]  [128, 50.03563864975485, int]
5   [3.4574527664490997, 0.9399880977511021, float] [120, 41.841146628802875, int]
6   [3.1190582380554863, 1.0839109431114795, float] [148, 55.990072419824514, int]
7   [2.7757359940789916, 0.8889801332053203, float] [142, 51.08885697101243, int]
8   [3.23820908493237, 1.0587479742892683, float]   [183, 43.831293356668425, int]
9   [2.2509032790941985, 0.8896196407231622, float] [66, 35.9377662201882, int]

I'd like to extract for every column the first position of the list on each row to get a DataFrame looking as follows.

    Gamma   Beta
0   1.4652917656926299  91
1   2.6008354611105995  59
2   2.6386970166722348  89
...

Up to now, my solution would be like [row[1][0] for row in df_params.itertuples()], which I could iterate for every column index of the row and then compose my new DataFrame.

An alternative is new_df = df_params['Gamma'].apply(lambda x: x[0]) and then to iterate to go through all the columns.

My question is, is there a less cumbersome way to perform this operation?


onCreate(Unknown Source) for Application class with Proguard (only happens on Samsung devices)

I've been testing my app on Sony and Nexus devices as well as multiple emulators (API 10 - 19) for several weeks and things seem fine, however, two of my testers (who live remotely) are experiencing crashes during startup and ACRA isn't offering the option to send a crash log email, which leads me to believe it's a crash before ACRA is even instantiated. ACRA works as expected on my devices and emulators and offers to send an email (via default app).

Are Samsung phones doing some special initialization? Am I doing anything in the following code which could cause a crash?

@ReportsCrashes(
        formKey = "", // This is required for backward compatibility but not used
        mailTo = "crash@mydomain.com",
        customReportContent = {
                ReportField.APP_VERSION_CODE,
                ReportField.APP_VERSION_NAME,
                ReportField.ANDROID_VERSION,
                ReportField.PHONE_MODEL,
                ReportField.CUSTOM_DATA,
                ReportField.STACK_TRACE,
                ReportField.LOGCAT }
)
public class AppState extends Application {

    private static final String DIRECTORY_ROOT = Environment.getExternalStorageDirectory();
    private static final String DIRECTORY_PICTURES_APP = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + File.separator + "MyApp";

    private static final LogConfigurator logConfigurator = new LogConfigurator();
    private static final Logger logger = Logger.getLogger(AppState.class);

    @Override
    public void onCreate() {
        super.onCreate();

        ACRA.init(this);

        // try to create log file and directory; if successful, configure ACRA to include last lines with crash report
        if (createLogFile()) {
            ACRAConfiguration config = ACRA.getConfig();
            config.setApplicationLogFile(LOGGER_FILENAME);
            ACRA.setConfig(config);
        }

        ...log4j, database init, etc...

The source for the project is located here on SourceForge.

EDIT #1:

Finally got one of the Samsung Remote Test Lab devices working! Screen still isn't visible, but I can at least see logcat. Here is the reason for the crash:

ERROR  AndroidRuntime  at org.dumpsterdiver.sync.AppState.onCreate(Unknown Source)

So that means the system is unable to find my Application class? After a bit of Googling similar problems, I think it might be a proguard error (sigh, again), so I've been playing with various suggestions from other answers. None of these have helped so far (still experimenting with various values):

-keep public class org.dumpsterdiver.sync.AppState
-keep public class * extends android.app.Application
-keep public class * extends com.actionbarsherlock.app.SherlockActivity

EDIT #2:

Adding this line to my proguard config file seems to fix the problem:

-keep class * { *; }

But my APK is 500 KB larger (3.7 -> 4.2 MB) and I suspect this probably defeats half the point of using proguard in the first place? Is there a better solution?


RoR generated sql has where

I have 3 tables stauscode, worequest and employee.  Worequest belongs to employee and employee has_many worequests.  Worequest belongs to statuscode and statuscode has many worequests.

I also have a scope for worequest:

   scope :notcompl, where(:statuscode_id != Statuscode.last, true)

I'm trying to display the worequests for the employee that are not completed:

 <% @employee.worequests.notcompl.each do |worequest| %>

The error I get:
G::Error: ERROR:  argument of AND must be type boolean, not type integer
LINE 1: ...uests"  WHERE "worequests"."employee_id" = 2 AND (1) ORDER B...

I'm trying to view employee number 2.  I can't figure out why it's putting the "and (1)" into the SQL.

Any ideas?

Thanks!


One to many join to last modified record in the most efficient way

I realise that variations of this question have been asked before but I'd like to know the most efficient solution to my particular issue.

I have two tables...

Event (event_id, customer_email...)

Customer (customer_email, last_modified...)

I'm joining these two tables and only want the customer with the greatest last_modified date. The customer table is absolutely huge so was wondering the best way to go about this.


How do I wait for a yield?

I have a function findOrCreateUser that returns a generator. But I need to call a callback done when the function has completed. How do I do this?

I tried calling next() on the generator but the result was pending.

passport.use(new FacebookStrategy({
        clientID: fbConfig.appId,
        clientSecret: fbConfig.appSecret,
        callbackURL: 'http://localhost:' + (process.env.PORT || 3000) + '/auth/facebook/callback'
    },
    function(token, tokenSecret, profile, done) {

        var user = yield userRepository.findOrCreateUser(
            profile.id,
            profile.name,
            'pic');

        return user;
    })
);


ANDROID Volley + Gson (POST)

hello.

I want to make a post request using gson.

I got the class implemented into android website...
http://developer.android.com/intl/pt-br/training/volley/request-custom.html

UserRequestHelper.userRequest(Request.Method.POST, EndpointURL.USUARIO, null, new Response.Listener<Usuario>() {
                    @Override
                    public void onResponse(Usuario response) {
                        Toast.makeText(getActivity(), "Cadastro realizado com sucesso!", Toast.LENGTH_SHORT).show();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "Erro ao realizar cadastro.", Toast.LENGTH_SHORT).show();
                    }
                });

I need a body to send the user? How i send the object user to make a post request?

Could someone help me with this?


Update DOM in Ruby on Rails 5

Have a problem with my app on ruby on rails 5, after ajax request cannot run javascript. I think this is problem with DOM, but I not have a good knowledge with JavaScript and cannot fix this problem. Will be very

appreciation everyone who will try to help me.

movies_controller.rb

 def home
if params[:search]
  @movies = Movie.search(params[:search]).order('created_at DESC').page(params[:page]).per(20)
  @movies = @movies.genre(params[:genre]).order('created_at DESC').page(params[:page]).per(20)
  @movies = @movies.date_relist(params[:date_relist]).order('created_at DESC').page(params[:page]).per(20)
  @movies = @movies.rating(params[:rating]).order('created_at DESC').page(params[:page]).per(20)
else
  @movies = Movie.all.order('created_at DESC').page(params[:page]).per(20)
  @movies_genre = Movie.all.select(:genre).uniq.order('genre ASC')
  @date_relist = Movie.all.select(:date_relist).uniq.order('date_relist DESC')
  @rating = (Movie.all.select(:rating).uniq).order('rating DESC')
end

end

home.html.erb

<div class="container">
<%= form_for root_path, method: :get, id: "movies_search", remote: true do %>
<%= label_tag :search %>
<%= text_field_tag :search, params[:search]%>
<%= label_tag :genre %>
<%= select_tag :genre, options_from_collection_for_select(@movies_genre, "genre", "genre") %>
<%= label_tag :date_relist %>
<%= select_tag :date_relist, options_from_collection_for_select(@date_relist, "date_relist", "date_relist"), include_blank: true %>
  <%= label_tag :rating %>
<%= select_tag :rating, options_from_collection_for_select(@rating, "rating", "rating"), include_blank: true %>
<%= submit_tag "Search", name: nil  %>

<div class="content">
<div class="wrapper">
  <div id="movies"> <%= render partial: 'movies' %>
  </div>
</div>

home.js.erb

$("#movies, .pagination").html("<%= escape_javascript(render("movies")) %>")

_movies.html.erb

<% @movies.each do |m| %>

<div class="card">
  <div class="card__container card__container--closed">
    <svg class="card__image" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1920 1200" preserveAspectRatio="xMidYMid slice">
      <defs>
        <clipPath id="clipPath<%=m.id%>">
          <polygon class="clip" points="0,1200 0,0 1920,0 1920,1200"></polygon>
        </clipPath>
      </defs>
      <image clip-path="url(#clipPath<%=m.id%>)" width="1920" height="1200" xlink:href="/pictures/<%= m.img %>"></image>
    </svg>
    <div class="card__content">
      <i class="card__btn-close fa fa-times"></i>
      <div class="card__caption">
        <h2 class="card__title"><%= m.title %></h2>
        <p class="card__subtitle">Genre - <%= m.genre %></p>
      </div>
      <div class="card__copy">
        <div class="meta">
          <img class="meta__avatar" src="/pictures/<%= m.img %>" alt="author01" />
          <img class="krug"/>
          <div class="description">
            <span class="meta__author">Running Time - <%= m.runtime %></span><br>
            <span class="meta__date">Release Date - <%= m.date_relist %></span>
          </div>
        </div>
        <div class="text" style="text-align: center">
          <p>
            <%= raw(m.trailer) %>
            <br>
            <%= m.desc %>
          </p>
        </div>
      </div>
    </div>
  </div>
</div>


How can I access Dropwizard Resource directly, and not via REST

I've create Dropwizard Resource and mapped it to REST API.
Now I want to reuse this Resource API from other points in my code as a JAVA API.
How can I do it?

This is the Resource class:

@Path("/providers_new")
public class ProviderResource {
    private ProviderDAO dao;

    public ProviderResource(ProviderDAO dao) {
        this.dao = dao;
    }

    @GET
    @Path("/get")
    @Produces("application/json")
    public List<Provider> getAll() {
        return dao.getAllProviders();
    }
}

Please note that ProviderResource is initialized with dao:

public class EntitiesService extends Service<EntitiesServiceConfiguration> {
    public static void main(String[] args) throws Exception {
        new EntitiesService().run(args);
    }

    @Override
    public void initialize(Bootstrap<EntitiesServiceConfiguration> bootstrap) {
        bootstrap.setName("entities");
        ...
    }

    @Override
    public void run(EntitiesServiceConfiguration configuration,
                Environment environment) throws ClassNotFoundException {
        final DBIFactory factory = new DBIFactory();
        final DBI jdbi = factory.build(environment, configuration.getDatabaseConfiguration(), "my_db");
        final ProviderDAO dao = jdbi.onDemand(ProviderDAO.class);
        environment.addResource(new ProviderResource(dao));
        ...
    }
}

Now that ProviderResource is on the air, I would like to use it from my code. Something like:

ArrayList<Provider> providers = iDontKnowHowToGetProviderResource.getAll();

What do you say?


NHibernate - Performance Tuning with Native SQL

I am trying to use NHibernate to map a graph built with the following entites to the relational database (The code is incomplete and just for demo purpose, which should look straightforward). Potentially Node and Edge classes may have subclases and there are already a string of subclasses defined inherited from Node class. For all the inheritance relationships in this model, the mapping type used is joined-subclass (table-per-subclass);

class GraphObject { ... }

class Node : GraphObject {
   List<Edge> IngoingEdges;
   List<Edge> OutgoingEdges;
}

class Edge : GraphObject {
   Node StartNode { get; set; }
   Node EndNode { get; set; }
}

For connections between nodes and edges a dual many-to-one mapping is used as follows,

many-to-one from Edge.StartNode to nodes(.OutgoingEdges);
many-to-one from Edge.EndNode to nodes(.IngoingEdges)

Since there's a need to work with huge volume data in our project (millions of nodes and edges) and we would like to both keep having the benefits NHibernate provides and minimize the performance issues. Unfortunately it seems to take nearly an hour to save or load such a model. What I'm currently doing is trying to figure out a way to finish loading in one statement and see how long it takes. I made a few attempts and I used NHibernate Profiler to keep track of the SQL statements generated by the NHibernate framework when doing things like loading the entire graph from the data persistence, but so far I haven't managed to eliminate that huge amount of individual queries apparently for determining which are the start and end nodes for specific edges which look like

select ...StartNode as .., ..Id as .., ... from Link link where link.StartNode=10 (a number indicating node id)

which means I am kind of suffering from the so-called N+1 issues.
So is there anyone wo has come across a similar problem and can give me some idea, either in native SQLs or improving performance for this particular case by other approaches. I would really appreciate that. Any questions regarding points unclear are also welcome.


IIS AppDomain unloading in an Azure environemnt

As far as I understand, in a Windows Azure web role - every .svc is loaded in it's own App Domain. Does IIS ever unload the AppDomain duirng its process lifetime so that invocation (typically via a HTTP call) of the svc will trigger Application_Start() (again)?


Orca Power Shell

I am trying to create a transform using Orca so that I can automate the install of an msi file. The problem is I struggling to find out how I automate the clicking of a 'Next' button that would appear in the Wizard. I thought that I needed to create a property name for the 'Next Button' in the 'Controls' table in Orca then add a new row into the 'Property' table in Orca. Then add the value of '1' to the value of the newly craeted property. Bu this didnt work when I generated the transform file and ran the following command line -

msiexec /I "msiName.msi" TRANSFORM="transformName.mst"

Can anybody shed any light?


Solving StringIndexOutOfBoundsException

I received a crash report, which is about java.lang.StringIndexOutOfBoundsException in ZhuangDictActivity$SearchDicAsyncTask.doInBackground

Here is the ZhuangDictActivity$SearchDicAsyncTask.doInBackground:

private class SearchDicAsyncTask extends AsyncTask<String, Integer, String> {

        private byte searchStatus;

        @Override
        protected String doInBackground(String... params) {
            if (params[0].length() > 0) {
                word = params[0].trim();
                long[] index = null;

                FileAccessor in = null;
                DictZipInputStream din = null;
                try {

                    char key = GB2Alpha.Char2Alpha(word.charAt(0));
                    tableName = DatabaseHelper.transTableName(key);

                    index = databaseHelper.queryTable(tableName, word);

                    if (index != null) {
                        in = new FileAccessor(new File(dictFileName), "r");
                        byte[] bytes = new byte[(int) index[1]];
                        if (isDZDict) {
                            din = new DictZipInputStream(in);
                            DictZipHeader h = din.readHeader();
                            int idx = (int) index[0] / h.getChunkLength();
                            int off = (int) index[0] % h.getChunkLength();
                            long pos = h.getOffsets()[idx];
                            in.seek(pos);
                            byte[] b = new byte[off + (int) index[1]];
                            din.readFully(b);
                            System.arraycopy(b, off, bytes, 0, (int) index[1]);
                        } else {
                            in.seek(index[0]);
                            in.read(bytes);
                        }

                        wordDefinition = new String(bytes, "UTF-8");
                    } else {
                        searchStatus = 0;
                        return null;
                    }
                } catch (FileNotFoundException ffe) {
                    searchStatus = 1;
                    return null;
                } catch (IOException ex) {
                    ex.printStackTrace();
                    searchStatus = 2;
                    return null;
                } finally {
                    try {
                        if (din != null)
                            din.close();
                        if (in != null)
                            in.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

            }
            return wordDefinition;
        }
    }

The complete code is available here.
I have limited knowledge in Java and Android development. How should I solve this? I intended to post the complete stack traces but stackoverflow do not allow me to do so because it stated my question has too many code. Anyway, the line which is causing the problem is char key = GB2Alpha.Char2Alpha(word.charAt(0));.


Joomla Components are not working on webserver, but working on WAMP Server(Localhost), Why?

I am using Joomla1.5, Here some Components (TPJOBS) working very well on WAMP Server 2.1 (Localhost) but When I upload on Web Server , Components are not working .  Can anybody tell why this is happening , What changes I need in Web Server to run Components as they are working well on WAMP Server.


Question regarding creating windows service

I have got few questions regarding creating windows service.
I have created a windows service.But Im getting an error reagrding that.
public partial class xyz : servicebase
{
public xyz()
{
InitializeCompoenent();
}
}

it couldn't resolve InitializeComponent().Does anybody any reason.
I have set it up out as console application instead of windows application.


Android Read Text and split into multidimensional array dynamically

I read this thread, but, how can I put text from a file dynamically into multidimensional array?

Data like:

1,4,5,7,nine

11,19

22,twenty-three,39

30,32,38
..
..


How can I find which java class reads a particular xml file?

I'm workin on a java application for which i don't have all the source codes. The application is based on spring framework, and at startup it parses lots of xml files from different directories. Then it makes an internal cache of the given xml content which I would like to disable and make changes in the class to read the xml content when it's needed and don't cache them. For this reason i have to find out which class opens my xml.

(If i can find it out, then i can ask for source code access, but till then i wont get access to it.)

What else i know about this class is it parses lots of xmls from different directories so the filename wont be hardcoded into the class.

I was thinking of to use a decompiler to reverse engineer the class files, but there are a lot, and the package hierarchy is too deep to do it one by one. Maybe there is a way to decompile whole jar files at once with an eclipse plugin or a command line tool, but i don't know how. Anyway maybe there is a much simpler solution.

Any ideas?


How to simulate a service killed by the Android system

While developing I wanted to test the situation where the system kills a service. This is because I'm loosing connection when communicating between the Android Wear and the handheld. And I think that it is related with the system killing some services.

Does anyone have a suggestion on how to approach this?


WPF Multiple triggers on the same property not working right

I have 2 triggers on the same property of a checkbox, and it doesn't work quite right.

<ControlTemplate.Triggers>

    <Trigger Property="IsChecked" Value="False">
        <Setter TargetName="InnerText" Property="Text" Value="False" />
        <Trigger.EnterActions>
            <BeginStoryboard Storyboard="{StaticResource OnUnCheck}"/>
        </Trigger.EnterActions>
    </Trigger>

    <Trigger Property="IsChecked" Value="True">
        <Setter TargetName="InnerText" Property="Text" Value="True" />
        <Trigger.EnterActions>
            <BeginStoryboard Storyboard="{StaticResource OnCheck}"/>
        </Trigger.EnterActions>
    </Trigger>

</ControlTemplate.Triggers>

When I uncheck the CheckBox, the text is set, and the storyboard gets called just fine. But then when I check the CheckBox, the text gets set properly, but the storyboard isn't called. I can then uncheck the CheckBox, and that storyboard still works.

Then, if I swap the Trigger order, so Value="True" is the first one, only that storyboard works. In both cases the text is set just fine, and it confirms that both storyboards work. Its just the storyboard in the second Trigger doesn't get called in either case. Do I need to use a MultiTrigger...?

Edit: My storyboards were backward, so it's the first Trigger not calling the storyboard, not the second


Speed up reading results in batch script

What I am trying to do, is speed up  my reading results of batch file.

Am trying to get different values using netsh commands and then present them in my script console but it takes to long.
See below a small part of my script to get the idea. (this is just a small part, I'm actually getting around 50 different values and using more netsh commands)

Does anybody know a way to speed up the process?

.
.
.
netsh interface ipv4 show config %AdapterLAN%  >temp
for /f "tokens=3" %%i in ('findstr "IP Address" temp') do set ip=%%i
echo.  IP Address        : %ip%

for /f "tokens=5 delims=) " %%i in ('findstr  "Subnet Prefix" temp') do  set mask=%%i
echo.  Mask              : %mask%

for /f "tokens=3" %%i in ('findstr  "Gateway:" temp')  do set gateway=%%i
echo.  Gateway           : %gateway%

for /f "tokens=1,5,6" %%a in ('findstr  "DNS" temp') do set dns1=%%a&set dns5=%%b&set dns6=%%c
If "%dns1%"=="Statically" set dns=%dns5%
if "%dns1%"=="DNS"        set dns=%dns6%
echo.  DNS Server        : %dns%

for /f "tokens=3" %%i in ('findstr "Gateway Metric" temp') do set GMetric=%%i
for /f "tokens=2" %%i in           ('findstr "InterfaceMetric" temp')   do set IMetric=%%i
set /a metricLAN=Gmetric + imetric
echo.  Metric            : %metricLAN%

for /f "tokens=3" %%i in ('find "DHCP enabled" temp') do set LANDHCP=%%i
If "%dns1%"=="Statically"  set xx=Static
if "%dns1%"=="DNS"         set xx=DHCP
If /i %LANDHCP%==No        set LANDHCP=Static
if /i %LANDHCP%==YES       set LANDHCP=DHCP
echo.  Obtained IP       : %LANDHCP%
echo.  Obtained DNS      : %xx%
for /f "tokens=3 delims=," %%a in ('getmac /v /fo csv ^| find """%AdapterLAN-without-Q%""" ')  do set macLAN=%%a
echo.  MAC-Addres        : %macLAN%
del temp
.
.
.
netsh wlan show profile >temp
.
Do a similar process of getting values from another netsh command sent them
in the temp file …echo the one I want on the screen ..delete the file etc.


convert date time from EU time zone to PST

i have a list of datetimes in EU time zone:

[u'2014-11-01T09:00:00+01:00', u'2014-11-02T00:00:00+01:00', u'2014-11-03T00:00:00+01:00', u'2014-11-04T00:00:00+01:00', u'2014-11-05T00:00:00+01:00', u'2014-11-06T00:00:00+01:00', u'2014-11-07T00:00:00+01:00', u'2014-11-08T00:00:00+01:00', u'2014-11-09T00:00:00+01:00', u'2014-11-10T00:00:00+01:00', u'2014-11-11T00:00:00+01:00', u'2014-11-12T00:00:00+01:00', u'2014-11-13T00:00:00+01:00', u'2014-11-14T00:00:00+01:00', u'2014-11-15T00:00:00+01:00', u'2014-11-16T00:00:00+01:00', u'2014-11-17T00:00:00+01:00', u'2014-11-18T00:00:00+01:00', u'2014-11-19T00:00:00+01:00', u'2014-11-20T00:00:00+01:00', u'2014-11-21T00:00:00+01:00', u'2014-11-22T00:00:00+01:00', u'2014-11-23T00:00:00+01:00', u'2014-11-24T00:00:00+01:00', u'2014-11-25T00:00:00+01:00', u'2014-11-26T00:00:00+01:00', u'2014-11-27T00:00:00+01:00', u'2014-11-28T00:00:00+01:00', u'2014-11-29T00:00:00+01:00', u'2014-11-30T00:00:00+01:00', u'2014-12-01T00:00:00+01:00']

How do i convert each of them to PST time zone?


How can I conditionally include a file based on build configuration in Xcode?

I have an Xcode project with a large number of targets where I would like to include a settings bundle for apps built under the Ad-hoc and Debug configurations, but not under the Release configuration.

Build Phases don't seem to allow for making themselves conditional on configuration (they can obviously be conditional on target, but doubling the number of targets in the project would make it completely unusable).

That leaves writing a custom Build Rule. My plan is to exclude the Settings.bundle from all targets, and create a build rule that conditionally copies it into the product package, but applicable examples are really hard to find.

The build rule I've started has the Process setting set to "Source files with names matching:" and Settings.bundle as the name. The Using setting is "Custom script:".

My custom script is as follows (with the caveat that my bash scripting is on a cargo cult level):

if [${CONFIGURATION} = 'Debug'] then
    cp -r ${INPUT_FILE_PATH} ${DERIVED_FILES_DIR}/.
fi

Finally, I have ${DERIVED_FILES_DIR}/Settings.bundle listed as an output file.

Since I'm here, it should be obvious that it's not working. My first question is whether there is somewhere I can view the output of the build rules as the execute to make sure that 1) it's actually being executed and that 2) I don't have a stupid syntax error somewhere.

Also, what's the proper location (in the form of an environment variable) to copy the output to?


django unit testing on multiple databases

I'm working on a django project where all my unit test cases were working perfectly.

Ass soon as I introduced a second database all my test cases that inherit from TestCase are broken. At this stage I haven't build any test case for that second database but my router is working fine.

When I run the tests I get the error,

"KeyError: 'SUPPORTS_TRANSACTIONS'"

It appears to me that is trying to check that that all the databases that I've got setup support transactions but the second database is never created.

Any ideas on how to have the test script to build the second database.


Hash Array Mapped Trie performance

I'm trying to implement Hash Array Mapped Trie in Java. Before, I thought that this data structure should be more memory efficient than Hash Map, but when i made first memory measurements using Visual Vm, i found that my implementation require more memory then Hash Map (also "put" operation is slower). I can't understand : HAMT really requires more memory or i made mistake in implementation.
Similar performance results as in this question.

Has "Hash Array Mapped Trie" performance advantages over "Hash Table" ("Hash Map")?


What does mode_t 0644 mean?

#define COPYMODE 0644
creat(argV[2],COPYMODE);

I have these two lines of code in a copy.c file.
I don't know what it means.
Please give some example about it


Limit number of file watched with nodejs

I have a script written in nodejs with chokidar where I listen into a folder when a file is added.

When a file is added start a function with many loop.

Sometimes the system add 100 or more files at the same time so the event add is called 100 times and the server can crash.

Is there a way to limit watched file and the others wait until watched file are closed?

For example I decide that I can't watch more than 10 files at the same time, the other files wait until first 10 finished their thing.

Is possible?

This is my script:

var chokidar = require('chokidar');
var sys = require('sys')
var exec = require('child_process').exec;

var folder = process.argv[2];
var watcher = chokidar.watch('tmp/xml/' + folder + '/', {ignored: /^\./, persistent: true});
watcher
  .on('add', function(path) {
    var filenameArr = path.split('/');
    filename = folder + '/' + filenameArr[filenameArr.length - 1];

    function puts(error, stdout, stderr) { sys.puts(stdout) }
    exec('bin/cake manager readXmlAndSave ' + filename, puts);
})


Understanding exchangeArray function in Table Gateway pattern in ZF2

I am new in ZF2 and i created one module in my application where i have used Table Gateway pattern, I observed that for table gateway exchangeArray() function is being used.

Can Anyone briefed about how exchangeArray() function works internally.

Thanks In Advance !!


Python 3.5: FileNotFoundError: [Errno 2] No such file or directory

I learned Python but hadn't used it in a few months so I am perhaps rusty. I am just trying to start a project by reading from a csv text file. I understand that there are several questions on this site about this error, but I haven't found one that fixes the issue. This is probably really basic and I wanted to figure this out without posting a question, but after several hours I really don't get it. Sorry if I missed a question that has answered this, but I have checked a lot of questions first. Here is all of my code:

import csv
with open('C:\\Users\\Ben.Brittany-PC\\Documents\\stats.txt', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        print(row)

and the error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Ben.Brittany-PC\\Documents\\stats.txt'


Entity Framework not updating naviation proprties with automatic change tracking disabled

I have one unitOfWork in my Domain Logic that retrieves tens of thousands of XML nodes, creates disconnected entities called "retreivedBooks" from the XML and updates Book entities in the database based on the retreivedBooks. For this particular unitOfWork's dbContext in my application, I have disabled change tracking due to very bad performance when there are lots of entities in the database. This has improved performance - great.

However it is no longer updating navigation properties. Here is a made up example to demonstrate the problem:

 public class Book
 {
      public string Title;
      public string Author;
      public virtual List<Page> Pages;
 }

_unitOfWork.Context.Configuration.AutoDetectChangesEnabled = false;
_unitOfWork.Context.Configuration.ValidateOnSaveEnabled = false;

foreach(Book retreivedBook in retreivedBooks )
{
    Book existingBook= _unitOfWork.BookRepository.SingleOrDefault(b=>b.Id=retreivedBook.Id);
    if(book!=null)
    {
         existingBook.Title=retreivedBook.Title;
         existingBook.Author=retreivedBook.Author;
         existingBook.Pages=retreivedBook.Pages;
         _unitOfWork.Context.Entry(existingBook).State = EntityState.Modified;
    }
}
_unitOfWork.Save();

In the example above, the Title and Author properties of books in the database get updated correctly, but the list of Pages does not.

By the way, I don't check for existing Pages based on retreived Pages. We can assume that pages are always different every time so the book.Pages property will be replaced on every update.

Can anyone help to explain why the pages property does not get updated in the database?


How to fix font baseline in Android Lollipop when working with custom icon fonts?

I am currently using FontAwesome in one of my Android projects. I primarily use it to display icons to the left of text on certain buttons. I noticed that since upgrading one of my test devices to Lollipop, the icons began sagging below the baseline of the text on the button.
Please see the images below:

Android KitKat (Nexus 7) - good:

Android Lollipop (Nexus 4) - bad:

Please note that the bottom of the icon in the first image sits on the baseline of the text, while the bottom of the icon in the second image is below the baseline.

Code:

<string name="button_text_logout"> LOG OUT</string>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:textSize="@dimen/text_size_menu_item"
    android:textColor="@color/white"
    android:gravity="center_vertical"
    android:text="@string/button_text_logout"
    android:paddingLeft="@dimen/action_item_padding"
    android:paddingRight="@dimen/action_item_padding"/>

Typeface typeface = Typeface.createFromAsset(context.getAssets(), "fontawesome-webfont.ttf");
logOutTextView.setTypeface(typeface);

I am using the fa-sign-out icon. The code works fine on all devices running versions of Android prior to 5.0. Is there any way to fix this?


Is there a .NET performance counter to show the rate of p/invoke calls being made?

Is there a .NET performance counter to show the rate of p/invoke calls made?  I've just noticed that the application I'm debugging was making a call into native code from managed land within a tight loop.  The intended implementation was for a p/invoke call to be made once and then cached.  I'm wondering if I could have noticed this mistake via a CLR Interop or Remoting .NET performance counter.  Any ideas?


Webgl Framebuffer low Picture - Quality

My framebuffer has very low picture- quality (Android). What can I do to get better quality? Hier is a screen shot:

Hier is a part of my code:

RenderingEngine.prototype.getPixel = function(x, y, drawObjects){
var framebuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
framebuffer.width = this.canvas.width;
framebuffer.height = this.canvas.height;

var depthBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);

// allocate renderbuffer
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, framebuffer.width, framebuffer.height);

// attach renderebuffer
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);

var colorBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, colorBuffer);
// allocate colorBuffer
gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, framebuffer.width, framebuffer.height);

// attach colorbuffer
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorBuffer);

if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) {
   alert("this combination of attachments does not work");
}

gl.clearColor(1, 1, 1, 1);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

renderingEngine.draw(drawObjects);
var pixel = new Uint8Array(4);
gl.readPixels(x, this.canvas.height - y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
return pixel;
 }


How to execut an SQL query in a vba module

I am currently stuck on trying to execute an SQL query to a vba module.

Option Explicit
Public con As ADODB.Connection
Public Const CONNECTION_STRING As String = "Provider=SQLOLEDB; uid=;pwd=; DATABASE=MFBPRD; SERVER=MCPLONSQL01;Integrated Security=SSPI;"

    Function Run()
    Call ConnectDB
    Dim Cmd As ADODB.Command
    Dim rcs As ADODB.Recordset
    Dim SQL As String
    Dim res() As String

    Set Cmd = New ADODB.Command
    Set Cmd.ActiveConnection = con

     SQL = "select tl.id, al.price_crossing, al.price_exchange_fees, tl.charges_execution, tl.charges_mariana, tl.charges_exchange, tl.trade_date, un.value, tl.nb_crossing  from mfb.trade_leg tl"
     SQL = SQL & "inner join mfb.trade t on t.id = tl.id_trade"
     SQL = SQL & "inner join mfb.instrument i on t.id_instrument = i.id"
     SQL = SQL & "inner join mfb.instrument_type it on it.id = i.id_instrument_type"
     SQL = SQL & "inner join mfb.options o on o.id_instrument = i.id"
     SQL = SQL & "inner join mfbref.mfb.underlying un on un.id = o.id_underlying"
     SQL = SQL & "inner join mfb.allocation_leg al on al.id_trade_leg = tl.id"
     SQL = SQL & "where tl.trade_date > '20160101' and t.state = 3"

    Cmd.CommandText = SQL
    Set rcs = Cmd.Execute()

End Function

Under this I added the code to call ConnectDB.


naming convention when typedef standard collections

I am looking for naming conventions for typedef of lengthy collections definitions. We have some c++ code which used auto to get away with style murder, but we need to make this code compiling on a non c++11 compiler. We are looking to establish a convention for typedef of collections, which can become quite lengthy

For instance

typedef std::map<enum MyFirstEnum,enum MySecondEnum> map_enum2_by_enum1_t
typedef map_enum2_by_enum1_t::value_type             vtype_map_enum2_by_enum1_t
typedef map_enum2_by_enum1_t::iterator               map_iterator_enum2_by_enum1_t

There are so many nuances (iterator before t than at beginning, using type rather than t, ditching the prefix map, etc...) that half of the time you select one nuance, half of the time you select the other.
At the end no typedef look like the other.


Why SQL Server DATETIME type saves time in ticks of 1/300 of a sec?

SQLServer datetime format is stored as 8 bytes where the first four bytes are number of days since Jan 1, 1900 and the other four bytes are number of ticks since midnight. And the tick is 1/300 of the second.

I'm wondering why is that? Where is that 1/300 came from? There must be some historic reason for that.


How to point a sprite in a specified direction in micro:bit?

I'm working on a basic game for micro:bit just as a way to learn the technology, and I was hoping that one of the sprites would move in the direction of the compass.

Is there a way to do this?


Why I can not find my Iphone device in xcode

I have added my iphone as device and associate it with provisioning. Then I download the newest provisioning and install it (I have successed added ipad as test device before).

Now, in the "Organizer", I can see the iphone device but when I connect iphone device I can not find the iphone device to run my app. My software version is 4.2.1, is it the version not the latest that lead to this problem? Or what is the possible reason?


Powershell test for noninteractive mode

I have a script that may be run manually or may be run by a scheduled task. I need to programmatically determine if I'm running in -noninteractive mode (which is set when run via scheduled task) or normal mode. I've googled around and the best I can find is to add a command line parameter, but I don't have any feasible way of doing that with the scheduled tasks nor can I reasonably expect the users to add the parameter when they run it manually.
Does noninteractive mode set some kind of variable or something I could check for in my script?

Edit:
I actually inadvertently answered my own question but I'm leaving it here for posterity.

I stuck a read-host in the script to ask the user for something and when it ran in noninteractive mode, boom, terminating error. Stuck it in a try/catch block and do stuff based on what mode I'm in.

Not the prettiest code structure, but it works. If anyone else has a better way please add it!


How to set up HotSwap in Eclipse

I am new to Eclipse thus this may be really beginner questions from me.
I want to set up hot-swap in Eclipse so non structural changes can be done and seen right in the running application. (Game development)

I think I have to have tomcat running. I don`t know how it works, never tried it but I have it in my Eclipse Servers tab configured, I can run it but it will generate bunch of errors when I debug with tomcat:

INFO: At least one JAR was scanned for TLDs yet contained no TLDs.

Please, could you navigate me in depth step by step how to set up the code replace in Eclipse? Also there are some External Web modules etc. Do I need it with Tomcat for hotswap?


How to save a component of a xml string in a file(Windows Phone memory) which is a response of server?

I am getting a responce from server in xml form in windows phone silverlight project. I want to store a special component of the string in a file (Windows Phone memory). For example, I am getting the following responce from server

<SJK><tableid>919844444444</tableid><Result_Code>0</Result_Code><Str_Result><mykey><Modulus>d534257d63f07f53d</Modulus><Exponent>010011</Exponent></mykey></Str_Result></SJK>

From this string, I want to store d534257d63f07f53d which is enclosed in <Modulus>d534257d63f07f53d</Modulus> and also  010011 which is enclosed in <Exponent>010011</Exponent>

Please help me out.


How to retrieve the result value and a select statement of a stored procedure at the same time in C#?

OK so this might sound a bit weird!

The thing is that in a project there are many stored procedure already written like this:

CREATE PROCEDURE [Status_Insert]

        @StatusId       int OUTPUT,
        @Status         nvarchar (50),
        @IsDeleted      bit = 0

AS

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRAN

INSERT INTO dbo.[Status]
(
        [Status],
        [IsDeleted]
)
VALUES
(
        @Status,
        @IsDeleted
)

SET @StatusId = @@IDENTITY

COMMIT TRAN
RETURN 1
END TRY

BEGIN CATCH
ROLLBACK TRAN

DECLARE @ErrorNumber_INT INT;
DECLARE @ErrorSeverity_INT INT;
DECLARE @ErrorProcedure_VC VARCHAR(200);
DECLARE @ErrorLine_INT INT;
DECLARE @ErrorMessage_NVC NVARCHAR(4000);

SELECT
        @ErrorMessage_NVC = ERROR_MESSAGE(),
        @ErrorSeverity_INT = ERROR_SEVERITY(),
        @ErrorNumber_INT = ERROR_NUMBER(),
        @ErrorProcedure_VC = ERROR_PROCEDURE(),
        @ErrorLine_INT = ERROR_LINE()

RETURN -1
END CATCH

The primary key is an Identity and an output variable is used to retrieve its value after the insert statement. (By the way, is this approach a good practice?)

Now the return values are used to indicate the success or failure of the procedure. (IE.  if the operation was successful 1 is returned and -1 is returned if the operation has failed)
If there is an error in the execution of the procedure, the last select statement will return the error to the user.

Now how can I call this procedure in C# and get these results at the same time?
What I want to do is, execute the procedure, and get the return value, if it was 1 then get the result of the last select statement (which contains more info about the error that has occured)
Thanks in advance.


Color tinted UIImages gets pixelated

I am having problem understanding the reason for the following method, to return images that are visibly pixelated. I have double checked the size of the image, and it is fine. What's more, without tinting it, the image edges are smooth, and lack pixelation.

The method for tinting image, based on IOS7 ImageView's tintColor property, works fine, however I would love to find out what is wrong with the following code, because it seems to work for everybody but me. Thanks!

- (UIImage *)imageTintedWithColor:(UIColor *)color
{
if (color) {
    UIImage *img = self; // The method is a part of UIImage category, hence the "self"
    UIGraphicsBeginImageContext(img.size);

    // get a reference to that context we created
    CGContextRef context = UIGraphicsGetCurrentContext();

    // set the fill color
    [color setFill];

    // translate/flip the graphics context (for transforming from CG* coords to UI* coords
    CGContextTranslateCTM(context, 0, img.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    // set the blend mode to color burn, and the original image
    CGContextSetBlendMode(context, kCGBlendModeColorBurn);
    CGRect rect = CGRectMake(0, 0, img.size.width, img.size.height);
    CGContextDrawImage(context, rect, img.CGImage);

    // set a mask that matches the shape of the image, then draw (color burn) a colored rectangle
    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    CGContextAddRect(context, rect);
    CGContextDrawPath(context,kCGPathFill);

    // generate a new UIImage from the graphics context we drew onto
    UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    //return the color-burned image
    return coloredImg;
}

return self;

}


disable the dates based on the date selected in the first datepicker field

I am working on angularjs application. User can select date from the From Date picker and To Date picker fields.
I want to disable the date selection in the To Date picker based on the date user selected in From Date picker field.
eg) If user has selected 02/23/2017 in From Date picker field, all the dates before 02/23/2017 should be disabled in To Date picker.

Demo here

I tried assigning model1 to the min-date attribute of To Date as shown below but that was not working. And even tried to display To-Date field date picker calendar pop up as soon as the user has selected the date in the From-Date field but ended up with javascript errors. Any suggestions would be helpful.

 <input type="text" uib-datepicker-popup="{{dateformat}}" min-date={{model1}} ng-model="model2" is-open="showdp" />

Below is the code:

     <div style="float:left" ng-controller="fromDateCtrl">
        From Date:
        <input type="text" uib-datepicker-popup="{{dateformat}}" min-date="mindate" ng-model="model1" is-open="showdp" />
        <span>
        <button type="button" class="btn btn-default" ng-click="showcalendar($event)">
            <i class="glyphicon glyphicon-calendar"></i>
        </button>
    </span>
    </div>
    <div style="float:left" ng-controller="toDateCtrl">
        To Date:
        <input type="text" uib-datepicker-popup="{{dateformat}}" min-date="mindate" ng-model="model2" is-open="showdp" />
        <span>
        <button type="button" class="btn btn-default" ng-click="showcalendar($event)">
            <i class="glyphicon glyphicon-calendar"></i>
        </button>
    </span>
    </div>

js code:

   angular.module('plunker', ['ngAnimate', 'ui.bootstrap']);
        angular.module('plunker').controller('fromDateCtrl', function ($scope) {
            $scope.today = function () {
                $scope.model1 = new Date();
            };
            $scope.mindate = new Date();
            $scope.dateformat="MM/dd/yyyy";
            $scope.today();
            $scope.showcalendar = function ($event) {
                $scope.showdp = true;
            };
            $scope.showdp = false;
        });

        angular.module('plunker').controller('toDateCtrl', function ($scope) {
            $scope.today = function () {
                $scope.model2 = new Date();
            };
            $scope.mindate = new Date();
            $scope.dateformat="MM/dd/yyyy";
            $scope.today();
            $scope.showcalendar = function ($event) {
                $scope.showdp = true;
            };
            $scope.showdp = false;
        });


CheckBox On GridView Lose State after selection

I Have a Problem With GridView CheckBoxes.
    I added Selection For My GridView and Every time i Select a Row, After PostBack My Checked CheckBoxes Loss their value. any Advice ?

Added Page Load.

My GirdView:
----------------
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="RulesGridView" runat="server" CellPadding="8" DataSourceID="RulesDataSource" ForeColor="#333333" GridLines="None" OnRowCreated="RulesGridView_RowCreated" OnSelectedIndexChanged="RulesGridView_SelectedIndexChanged" ViewStateMode="Enabled">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="false" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>

C# Code behind:
-------------------
  protected void RulesGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] =           "this.style.cursor='pointer';this.style.textDecoration='underline';";
                e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                e.Row.ToolTip = "Click to select row";
                e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.RulesGridView, "Select$" + e.Row.RowIndex);
            }
        }
protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            Session["RuleList"] = new List<Rule>();
            Session.Timeout = 180;
            //LstRules.Items.Clear();
            string folder = ConfigurationManager.AppSettings["MovieCreatorGUIRulesFolder"];
            XmlSerializer mySerializer = new XmlSerializer(typeof(List<Rule>));
            StreamReader reader = new StreamReader(folder + "\\DB" + txtdbnum.Text + "Rules.xml");
            List<Rule> RuleList = (List<Rule>)mySerializer.Deserialize(reader);
            reader.Close();
            Session["RuleList"] = RuleList;
        }
        ZoomInCommon.Users.UserInfo userInfo = PublishManager.GetCurrentYoutubeUser(-1);
        if (userInfo == null)
            txtYoutubeLoginUser.Text = "Not Logged In";
        else
            txtYoutubeLoginUser.Text = userInfo.DisplayName;
    }


MFMessageComposeViewController setting the UINavigationItem titleView

I'm having a problem overriding the title view of MFMessageComposeViewController's navigation item. Here is the code:

MFMessageComposeViewController *messageViewController = [[MFMessageComposeViewController alloc] init];
messageViewController.body=@"SMS Body";
CGRect frame = CGRectMake(0, 0, 100.0, 45.0);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text=@"Title";
messageViewController.navigationItem.titleView=label;
[label release];
[self.navigationController presentModalViewController:messageViewController animated:YES];
[messageViewController release];

I have also tried:
    messageViewController.navigationController.navigationItem.titleView=label;

I should also point out that this is for iOS 4, in iOS 5 I use the new setTitleTextAttributes method which works great.

Thoughts?


PHP Login does not work

I have a simple Login system which won't work and I can't figure out why. Once I press the login button nothing happens, the site just reloads instead of redirecting me or giving me any error messages.

if(!empty($_POST['email']) && !empty($_POST['password'])){

    $records = $conn->prepare('SELECT email, password FROM Profiles WHERE email = :email');
    $records ->bindParam(':email', $_POST['email']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);

    $message = '';

    if(count($results) > 0 && password_verify($_POST['password'], $results['password'])){

        $_SESSION['user_email'] = $results['email'];
        header("Location: main.php");
    }else{
        $message = 'Sorry, those credentials do not match';
    }
}

And here's the HTML form.

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
    <input type="text" placeholder="Email" name="email"> <br/> <br/>
    <input type="password" placeholder="Password" name="password"> <br/> <br/>
    <input type="submit" value="Login">
</form>


How to sort NSarray in Sections for UITableview

Hi how can I sort my Array in sections by Day , I get the data form my webserver (Json) and parse to NSDictionary then save to NSMutableArray... I understand I need to implement

(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

titleForHeaderInSection:

Row for Section:

NSMutableArray Log

2012-04-26 06:12:51.256 passingdata[91699:fb03] array : (
{
post =         {
    "CLASS_LEVEL" = "Intro/General";
    "CLASS_TYPE" = "Muay Thai";
    "DAY_OF_WEEK" = Sunday;
    ID = 19;
    "ORDER_BY" = 5;
    TIME = "1:00pm - 2:30pm";
};
}
{
post =         {
    "CLASS_LEVEL" = "General/Intermediate/Advanced";
    "CLASS_TYPE" = "Muay Thai Spar - Competitive";
    "DAY_OF_WEEK" = Friday;
    ID = 27;
    "ORDER_BY" = 5;
    TIME = "6:00pm - 9:00pm";
};
},
{
post =         {
    "CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
    "CLASS_TYPE" = "Fighters Training";
    "DAY_OF_WEEK" = Monday;
    ID = 1;
    "ORDER_BY" = 1;
    TIME = "9:30am - 11:00pm";
};
},

I can Display all the Data on my table , but I want to do it by section for each day (mon ,tue , wed.. sun), I have try NSpredicate and NSSet but still not working .

I don't know how to group items by day and get all the information to implement all the methods.

Any ideas ?? Thanks


SSRS - RDLC Tablix Rows will not split across pages

I have a tablix with two columns of data (the section name and the section text).  The section text has grown so large for some sections that the row representing the section takes up 2/3 or more of the page.  THe report prints fine until on of these large rows would have to split over the end of a page and continue on the next page.  In this case, and only in this case, the rows leaves large amounts of white space on current page and start on the next page (as if it had a page break before it)

I have already set the Tablix General Property "keep together on one page if possible" to true and all the other page break options for the tablix and row groups to false, to no avail.

Does anyone know of a trick or work around to make the large rows split over pages??


Intermixing HTML form and table

For a standard "add item" form page it is desirable to have two submit buttons: an "OK" button and a "cancel" button, where the former POSTs the form to one URL, and the latter GETs some other URL.

This obviously means that two separate FORMs are needed, and, if laid out with tables, the markup would go as follows:

<form action="add.html" method="post">
 <table>
  <tr>
   <td>Enter data:</td><td><input type="text" name="data"/></td>
  </tr>
 </table>
 <input type="submit" value="OK"/>
</form>
<form action="index.html" method="get">
 <input type="submit" value="Cancel"/>
</form>

However, this would result in the two buttons being placed below each other. It would be desirable to have them placed side by side. The following works:

<form action="add.html" method="post">
 <table>
  <tr>
   <td>Enter data:</td><td><input type="text" name="data"/></td>
  </tr>
  <tr>
   <td><input type="submit" value="OK"/></td>
</form>
<form action="index.html" method="get">
   <td><input type="submit" value="Cancel"/></td>
  </tr>
 </table>
</form>

But although I've seen it used on commercial websites, I guess it's not quite legal HTML.

So thus:

1) Since the second methods works, are there any good reasons for not using it?

2) Are there any better solutions?

EDIT: This was a silly question. The second method is unnecessary. Solution: add to the first method a CSS rule of:

form
{
  display: inline;
}


replicating wtikay - IE - currentStyle doesn't update when it ought to

I am trying to replicate, with my own code, the history-sniffing demo seen on http://wtikay.com/ and various other places.  (It's a long story.)

I have something that works reliably in most older browsers (latest Safari and Chrome releases and Firefox 4 betas have a defense) -- but it doesn't work in IE7 or 8 (haven't tried 6), and I cannot figure out why.  It seems to be that IE just isn't bothering to update its rendering when I change the href property on an a element -- but as far as I can tell, that's exactly what wtikay does, and it works.

Test file:

<!doctype html>
<html><head>
<title>gevalt</title>
<style>
  body { background-color: gray }
  a:link { text-decoration: none; color: black }
  a:visited { color: white }
</style>
<body>
<span id="container"><a href="" id="testlink">test</a></span>
<a href="ftp://">minus</a>
<a href="http://www.google.com/">plus</a>
<script>
window.onload = function()
{
    var testlink = document.getElementById("testlink");
    var results = document.getElementById("results");
    var container = document.getElementById("container");
    var report = "";

    testlink.href = "ftp://";
    container.removeChild(testlink);
    container.appendChild(testlink);
    report += " -" + (testlink.currentStyle || window.getComputedStyle(testlink, "")).color;

    testlink.href = "http://www.google.com/";
    container.removeChild(testlink);
    container.appendChild(testlink);
    report += " +" + (testlink.currentStyle || window.getComputedStyle(testlink, "")).color;

    results.appendChild(document.createTextNode(report));
};
</script>
<pre id="results">
</pre>
</body></html>

In a browser where it works, the words "test" and "plus" will be white (assuming you have visited www.google.com in that browser), the word "minus" will be black, and it will print something like "-rgb(0,0,0) +rgb(255,255,255)" underneath.  In IE, "test" will be black instead of white, and underneath it will read "-black +black".  Or possibly "test" will be white but underneath it will read "-white +white".  Both those are failures.

Any help would be most appreciated.


command line arguments with multiple output files

If I want two output files from a command line argument, can I just specify a third argument? i.e.

            infile=sys.argv[1]
            outfile1=sys.argv[2]
            outfile2=sys.argv[3]

And then when i'm typing the command into terminal:

        python script.py infile.txt outfile1.txt outfield.txt

And get 2 output files?


Java HttpsServer - Forcing TLSv1.1

I am running Java 8 and using com.sun.net.httpserver.HttpsServer to create a HTTPS server. I have a working implementation using a trusted CA signed EC certificate in a Java KeyStore.

I have been looking at how I could restrict what Ciphers and Protocols the server could support (similar to Apache using "SSLProtocol" and "SSLCipherSuite" in the configuration) - mainly to enforce a higher level of security by disabling the use of SHA-1.

No one should really be forcing TLSv1.1 over 1.2, but I am just doing this to prove a point that the following configuration works:

KeyStore ks = KeyStore.getInstance("JKS");
// Load KeyStore into "ks"

KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, jksPassword.toCharArray());

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

HttpsServer hsS = HttpsServer.create(sBind, 0);
hsS.setHttpsConfigurator(new HttpsConfigurator(sc) {
  @Override
  public void configure(HttpsParameters p) {
    try {
      SSLContext c = getSSLContext();
      SSLEngine e = c.createSSLEngine();

      p.setNeedClientAuth(false);
      p.setProtocols(new String[] { "TLSv1.1" });
      p.setCipherSuites(e.getEnabledCipherSuites());
      p.setSSLParameters(c.getDefaultSSLParameters());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
});

Even though I use setProtocols() to only accept "TLSv1.1", this doesn't seem to stop "TLSv1.2" connections and everything from Chrome to IE still uses "TLSv1.2". If I disable the use of "TLSv1.2" and "TLSv1.1" in IE and just leave "TLSv1.0" enabled then it will still work and negotiate "TLSv1.0". The setProtocols() method doesn't seem to do anything!?!

If I got this working then I was going to modify the list of Ciphers using setCipherSuites().


Conversion of co-ordinates from points to mm

I have a code using AWT graphics and applets.

public class Draw extends Applet{

        public void paint(Graphics g){
                g.drawLine(10,10,20,10);
        }
}

The code above draws a line of 10 units. I am not really sure which unit is the one being used by default. However, I am looking to draw a 10mm line. Finally I would be exporting this output as a PDF and I need the PDF to have a line of required length in mm. How can this be achieved? Thanks in advance.


Update javascript with html select value

Here is my code:

<select name="points">
  <option value="5">5 points</option>
  <option value="10">10 points</option>
  <option value="50">50 points</option>
</select>

here is my Javascript code:

<script
  src="https://checkout.stripe.com/checkout.js" class="stripe-button"
  data-key="test key"
  data-amount="option value here" // i need help here
  data-name="Site Name"
  data-description="2 widgets ($20.00)"
  data-image="/128x128.png">
</script>

The javascript code is a button for a popup. i want to get the select option value and i want to insert that into the data-amount in the js code. how can i do that?