vendredi 11 septembre 2015

changing button image removes skscene

I started my projects as a Spritekit game. Put a button on top of my defaultviewcontroller in storyboard. Presented a scene in viewwilllayoutsubviews.

 if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
            // Configure the view.
            let skView = self.view as! SKView
            self.skView = skView
            skView.showsFPS = true
            skView.showsNodeCount = true

            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true

            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = SKSceneScaleMode.AspectFill
            println("Width: \(scene.frame.width) andHEight: \(scene.frame.height)")
            scene.gameSceneDelegate = self
            sceneStack.append(scene)
            skView.presentScene(scene)
        }

After some time I transitioned to a new scene through viewcontroller code:

skView.presentScene(scene, transition: transition)

Now the scene changes but the button I had put on view storyboard stays there.. on top of the scene. Now On pressing the button I change the image of button... This surprisingly results in the scene changing back to the previous scene. As a result on changing the buttons any property it results in poping of my new scene and reverts back to the scene I presented initially.



via Chebli Mohamed

merge 2 array key values into one key value php

lets say i have an array like this:

Array
(
    [0] => first one
    [1] => second
)

Essentially i want to get both of the values and put them into the same value but separated with a comma.

The desired output would be this:

Array
(
    [0] => first one, second
)

I'm not sure what function can achieve this



via Chebli Mohamed

MATCH reverse order

In an excel sheet, I have from A1 to A6:

1, 2, 4, 6, 8, 9

I would like, using MATCH function, to retrieve the smallest interval that contains 5. Here, 4 and 6.

I can easily use the MATCH and INDEX function to find 4, but I can't find a way to find the 6.

How can I reverse the order of the Array in the MATCH function?



via Chebli Mohamed

Ruby. Pry. Is there a way to stop a long running command with out exiting out of the whole pry session

I want something to stop a pry command but I don't want to exit to my shell. control-c is not what I'm looking for. I'm not trying to exit out of a loop or out of the entire session. I simply want to return to the pry prompt if I run a line of code that takes a long time...



via Chebli Mohamed

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

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

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

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

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



via Chebli Mohamed

Prevent rdlc subreport from growing and moving within main report

I keep dealing with visual studio 2013 report designer.

My biggest problem at the moment is to spare exaclty one sheet of a4 paper (210 mm * 297 mm) per every data record. The length of the details section of the main report varies all the time depending on the lengths of subreports and (seems to me) something else.

Is there a way to keep unchanged both the size and location of a subreport within the main report ?

Thank you in advance !



via Chebli Mohamed

Yii2 Html::dropDownList and Html::activeDropDownList trade-off

In Yii2, using Html::activeDropDownList, I can submit data in a form like the following:

 <?= Html::activeDropDownList($model, 'category', ArrayHelper::map($categories, 'id', 'name'), [
       'multiple' => 'multiple',
       'class' => 'multiselect',
 ]) ?>

Is there a way to specify pre-selected categories in the above? I know it can be done using Html::dropDownLost like the following:

<?= Html::dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name'), [
     'multiple' => 'multiple',
     'class' => 'multiselect',
]) ?>

But there is a trade-off! There is no place to indicate that this is some data attached to a certain model to submit as there was using Html::activeDropDownList.

One of the solution I found was to use ActiveForm like the following:

<?= $form->field($model, 'category')
      ->dropDownList('category', [1, 3, 5], ArrayHelper::map($categories, 'id', 'name')
]) ?>

The problem I have with that last option is that I am not able to specify the html options such as 'multiple' and css such as 'class'.

Any help on being able to use drop down list with the ability to specify that the list be multiselect and have pre-selected values? Also if someone directed me to a resource where I can read about when and where to choose activeDropDownList or dropDownList, I would really appreciate that.

Thanks!



via Chebli Mohamed

Angularjs - bind dynamic data to predefined template

I'm trying to bind dynamic scope variable with predefined html template. The data is being built based on user selection via drop-down and has ng-click on a button that calls the method to build scope variable, see below for an example:

HTML:

<select id="category" class="form-control" ng-model="dataParam.category">
    <option value="">Choose Category</option>
    <option value="">overview</option>
    <option value="">mention</option>
    <option value="">sentiment</option>
</select>
<button ng-click="buildMetricData()" class="form-control">New</button>

I have template defined as overview-form-temp.html and using ng-include to load it on the view:

<section id="overview" class="well custom-margin" ng-include="'Views/overview-form-temp.html'"></section>

Template:

<form id="overview-form" name="overview-form" novalidate>
    <fieldset class="space-bottom">
        <legend>U.S. Brand Reputation</legend>
        <div class="form-horizontal form-widgets col-sm-12">
            <div class="form-group">
                <label for="awarness" class="col-sm-3">Awareness:</label>
                <div class="col-sm-2">
                    <input type="number" min="0" id="awareness" class="form-control" ng-model="metricData.subcategory['us total']['awareness']" />
                </div>
                <div style="clear:both;"></div>
                <label for="hight-trust" class="col-sm-3">High Trust:</label>
                <div class="col-sm-2">
                    <input type="number" min="0" id="high-trust" class="form-control" ng-model="metricData.subcategory['us total']['high trust']" />
                </div>
            </div>
        </div>
    </fieldset>
</form>

Controller:

var app = angular.module('AdminApp',[]);
app.controller('MainDataContrl', ['$scope','$compile', function($scope,$compile){
    $scope.buildMetricData = function(){

        $scope.metricData = {
            params:{},
            subcategory:{}
        }

        switch($scope.metricData .params.category){
            case 'Overview':
                $scope.metricData.subcategory['us total'] = {};
                break;
        }
    }
}]);

The data is building the way expected but I'm having issues binding it to the template above.



via Chebli Mohamed

How unreferred values from string pool get removed?

I'm curious how values from a string-pool get removed?

suppose:

String a = "ABC"; // has a reference of string-pool
String b = new String("ABC"); // has a heap reference

b = null;
a = null;

In case of GC, "ABC" from the heap gets collected but "ABC" is still in the pool (because its in permGen and GC would not affect it).

If we keep adding values like:

String c = "ABC"; // pointing to 'ABC' in the pool. 

for(int i=0; i< 10000; i++) {
  c = ""+i;
  // each iteration adds a new value in the pool. Previous values don't have a pointer.
}

What I want to know is:

  • Will the pool remove values that are not referred to? If not, it means that the pool is eating up unnecessary memory.
  • What is the point then because the JVM is using the pool?
  • When could this be a performance risk?


via Chebli Mohamed

Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerShadow(int, int)' on a null object reference

Due to my lack of knowledge on this I'm jumping from one problem to another. I've been trying to figure it out for hours now and looked through various previous questions but not getting anywhere. Most recent is this error:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerShadow(int, int)' on a null object reference
        at XXXX.NavigationDrawerFragment.setUp(NavigationDrawerFragment.java:136)
        at XXXX.EditFactFind.onCreate(EditFactFind.java:72)
        at android.app.Activity.performCreate(Activity.java:5990)

My Activity (the main point that it's failing) is:

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
//import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class EditFactFind extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    public static final int RESULT_DELETE = -500;
    private boolean isInEditMode = true;
    private boolean isAddingFactFind = true;
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private CharSequence mTitle;

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

        final Button saveButton = (Button)findViewById(R.id.saveButton);
        final Button cancelButton = (Button)findViewById(R.id.cancelButton);
        final EditText titleEditText = (EditText)findViewById(R.id.titleEditText);
        //final EditText factFindEditText = (EditText)findViewById(R.id.factFindEditText);
        final TextView dateTextView = (TextView)findViewById(R.id.dateTextView);
        final Button nextButton =(Button) findViewById(R.id.nextButton);

        //Create fragment and give it an argument for the selected article
        secA_pg1 iniSecFrag = new secA_pg1();
        Bundle args = new Bundle();
        args.putInt(secA_pg1.ARG_INDEX, 1);
        iniSecFrag.setArguments(args);

        FragmentTransaction initialTransaction = getFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        initialTransaction.replace(R.id.fragment_container, iniSecFrag);
        initialTransaction.addToBackStack(null);

        //Commit the transaction
        initialTransaction.commit();

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        Serializable extra = getIntent().getSerializableExtra("FactFind");
        if(extra != null)
        {
            FactFind factFind = (FactFind) extra;
            titleEditText.setText(factFind.getTitle());
          //  factFindEditText.setText(factFind.getFactFindTitle());

            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            String date = dateFormat.format(factFind.getDate());

            dateTextView.setText(date);

            isInEditMode = false;
            titleEditText.setEnabled(false);
          //  factFindEditText.setEnabled(false);
            saveButton.setText("Edit");

            isAddingFactFind = false;

        }

        cancelButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED, new Intent());
                finish();
            }
        });

        nextButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //secA_pg1 secFrag = (secA_pg1) getFragmentManager().findFragmentById(R.id.Sec_A_pg1_fragment);
                //Create fragment and give it an argument for the selected article
                secA_pg2 newSecFrag = new secA_pg2();
                Bundle args = new Bundle();
                args.putInt(secA_pg2.ARG_INDEX, 2);
                newSecFrag.setArguments(args);

                FragmentTransaction transaction = getFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                transaction.replace(R.id.fragment_container, newSecFrag);
                transaction.addToBackStack(null);

                //Commit the transaction
                transaction.commit();
            }
        });

        saveButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                if(isInEditMode)
                {
                    Intent returnIntent = new Intent();
                    FactFind factFind = new FactFind(titleEditText.getText().toString(),Calendar.getInstance().getTime());
                    returnIntent.putExtra("FactFind", factFind);
                    setResult(RESULT_OK, returnIntent);
                    finish();

                }
                else
                {
                    isInEditMode = true;
                    saveButton.setText("Save");
                    titleEditText.setEnabled(true);
                   // factFindEditText.setEnabled(true);
                }

            }
        });
    }

and my Navigation drawer is failing at the setUp method:

package XXXX;

import android.support.v4.app.FragmentActivity;

import android.app.ActionBar;

//import android.support.v7.app.ActionBar;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;

    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
   // mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(
            getActivity(),                    /* host Activity */
            mDrawerLayout,                    /* DrawerLayout object */
            R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
            R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
            R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
    ) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            if (!isAdded()) {
                return;
            }

        //    getActivity().InvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!isAdded()) {
                return;
            }

            if (!mUserLearnedDrawer) {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
            }

          //  getActivity().InvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

XML of the drawer is

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.DrawerLayout
    xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="XXXX.MainActivity">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->
    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment
        android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="XXXX.NavigationDrawerFragment"
        tools:layout="@layout/fragment_navigation_drawer" />

</android.DrawerLayout>

I'm assuming that mDrawerLayout isn't being picked up correctly and is therefore returning null but I can't figure out why that is.

Thanks.



via Chebli Mohamed

Create new worksheet if does not exist, rename based on cell value, then reference that worksheet

I have 2 workbooks one has the vba (MainWb), the other is just a template (TempWb) that the code paste values and formulas from the mainworkbook. The TempWb only has one blank sheet named graphs. The code needs to open the xltx file (TempWb), add a sheet and rename based on value in a certain cell on the MainWb (if it does not already exist) and then to reference that new sheet in the copy values process from the MainWb. I tried recording a macro but it didn't really help. I have researched and put some stuff together but not sure if it fits and works. Any suggestions would be appreciated.

This is what I have so far.

Option Explicit
Sub ExportSave()

Dim Alpha           As Workbook 'Template
Dim Omega           As Worksheet 'Template
Dim wbMain          As Workbook 'Main Export file
Dim FileTL          As String   'Test location
Dim FilePath        As String   'File save path
Dim FileProject     As String   'Project information
Dim FileTimeDate    As String   'Export Date and Time
Dim FileD           As String   'Drawing Number
Dim FileCopyPath    As String   'FileCopy save path
Dim FPATH           As String   'File Search Path
Dim Extract         As Workbook 'File Extract Data
Dim locs, loc                   'Location Search
Dim intLast         As Long     'EmptyCell Search
Dim intNext         As Long     'EmptyCell Seach
Dim rngDest         As Range    'Paste Value Range
Dim Shtname1        As String   'Part Platform
Dim Shtname2        As String   'Part Drawing Number
Dim Shtname3        As String   'Part Info
Dim rep             As Long

With Range("H30000")
            .Value = Format(Now, "mmm-dd-yy   hh-mm-ss AM/PM")
        End With

FilePath = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test"
FileCopyPath = "C:\Users\aholiday\Desktop\Backup"
FileTL = Sheets("Sheet1").Range("A1").Text
FileProject = Sheets("Sheet1").Range("E2").Text
FileTimeDate = Sheets("Sheet1").Range("H30000").Text
FileD = Sheets("Sheet1").Range("E3").Text
FPATH = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test\"
Shtname1 = wbMain.Sheets("Sheet1").Range("E2")
Shtname2 = wbMain.Sheets("Sheet1").Range("E3")
Shtname3 = wbMain.Sheets("Sheet1").Range("E4")

Select Case Range("A1").Value

    Case "Single Test Location"



    Case "Location 1"

    Application.DisplayAlerts = False
    Set wbMain = Workbooks("FRF Data Export Graphs.xlsm")
    wbMain.Sheets("Sheet1").Copy
    ActiveWorkbook.SaveAs FileName:=FileCopyPath & "\" & FileProject & Space(1) & FileD & Space(1) & FileTL & Space(1) & FileTimeDate & ".xlsx", FileFormat:=xlOpenXMLWorkbook
    ActiveWorkbook.Close False

    Set Alpha = Workbooks.Open("\\plymshare01\Public\Holiday\FRF Projects\Templates\FRF Data Graphs.xltx")




    For rep = 1 To (Worksheets.Count)
        If LCase(Sheets(rep)).Name = LCase(Shtname1 & Space(1) & Shtname2 & Space(1) & Shtname3) Then
            MsgBox "This Sheet already exists"
            Exit Sub
        End If
    Next

    Sheets.Add after:=Sheets(Sheets.Count)
    Sheets(ActiveSheet.Name).Name = Shtname1 & Space(1) & Shtname2 & Space(1) & Shtname3


            Set Omega = Workbooks(ActiveWorkbook.Name).Sheets("ActiveWorksheet.Name")

            locs = Array("FRF Data Export Graphs.xlsm")



                    'set the first data block destination
                        Set rngDest = Omega.Cells(3, 1).Resize(30000, 3)

                    For Each loc In locs

                    Set Extract = Workbooks.Open(FileName:=FPATH & loc, ReadOnly:=True)

                    rngDest.Value = Extract.Sheets("Sheet1").Range("A4:D25602").Value

                    Extract.Close False

                    Set rngDest = rngDest.Offset(0, 4) 'move over to the right 4 cols

                    Next loc

                          With ActiveWorksheet.Range("D3:D25603").Formula = "=SQRT((B3)^2+(C3)^2)"

                                ActiveWorkbook.Charts.Add
                                ActiveChart.ChartType = xlXYScatterLines
                                ActiveChart.SetSourceData Source:=Sheets("Graphs").Range("A3:D7"), PlotBy:=xlRows
                                ActiveChart.Location Where:=xlLocationAsNewSheet, Name:=Shtname2

                                With ActiveChart
                                    .HasTitle = True
                                    .ChartTitle.Characters.Text = Shtname2
                                    .Axes(xlCategory, xlPrimary).HasTitle = True
                                    .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Hz"
                                    .Axes(xlValue, xlPrimary).HasTitle = True
                                    .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Blank"
                                End With

        Application.ScreenUpdating = True

    Case "Location 2"
    Case "Location 3"
    Case "Location 4"
    Case Else

        MsgBox "Export Failed!"

    End Select


    Application.DisplayAlerts = True

 End Sub

Run-time error '91' Object variable or With block not set code lines

Shtname1 = wbMain.Sheets("Sheet1").Range("E2")
Shtname2 = wbMain.Sheets("Sheet1").Range("E3")
Shtname3 = wbMain.Sheets("Sheet1").Range("E4")

This is supposed to tell the code what to name the new created sheet

Fixed: Moved under

Set = wbMain = Workbooks("FRF Data Export Graphs.xlsm")

New Error: Object doesnt support this property or method code

   If LCase(Sheets(rep)).Name = LCase(Shtname1 & Space(1) & Shtname2 & Space(1) & Shtname3) Then  



via Chebli Mohamed

checking well formed xml and logging the error to file

I have 4,000 xml files in folders a, b, c, and d Each folder contains 1000 files each. All folders are in main folder called library I need to check if the xml files are well formed using

xmllint --noout 100.xml"

command or may be with something better. Now incase of error, log the file name plus folder name in a log file.

log "library/a/100.xml"

Below is the Pseudo code. I need to build the script to run in shell script or something faster

#program check xml format
#!/bin/bash
echo Please, get ready to process
 for i in $(cat "/home/thrinity/library/);
  do
    xmllint --noout "$i" ;
    if error
      #log filefolder & file name
      print error to errorlog.txt
    else
end do

I am looking for error where a tag is missing.. something like.. 038339 here the invoice closing tag is missing or any way I can capture this

For those who might be intrested. The code below worked for me in Ubuntu 14.04 machine

find /YourMainFolder -name '*.xml' -print | xargs -I "{}" sh -c 'File="{}";xmllint --noout "${File}" || readlink -f {} >> errorlog.txt



via Chebli Mohamed

Corona SDK While loop crash

What is wrong with this code that it crashes the simulator? I'm new to Corona SDK, but I know alot of Lua from Roblox.

local x,y,touching,active = 2,2,false,true
local background = display.newImage("Icon.png",(display.pixelWidth/2)+30,y)
background:scale(60,60)
print("Started")

function move()
    y=y+1
end

function onObjectTouch(event)
    if event.phase == "began" then
        touching = true
        while touching == true do
            timer.performWithDelay( 1000, move)
        end
    elseif event.phase == "ended" then
        touching = false
    end
    return true
end

background:addEventListener("touch",onObjectTouch)



via Chebli Mohamed

CreateDialog in BHO always fails with error 1813 (resource not found)

I'm working on a BHO written a long time ago in C++, without the use of any of the VS wizards. As a result, this project deviates from the COM conventions and the boilerplate for a COM product. I worked with COM long ago, but never really did any Windows GUI/dialog stuff...

I'm trying to add a dialog box to allow the user to set the values of some new settings:

// serverDialog will be NULL
HWND serverDialog = CreateDialog(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_PROPPAGE_SETTINGS), NULL, DialogProc);

id (!serverDialog) 
{
    int error = GetLastError(); //1813
    ...
}

....

1813 means that the resource cannot be found. The IDD used there is in resource.h, which I manually included where needed.

DialogProc is defined as:

INT_PTR CALLBACK DialogProc(HWND hWndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    return FALSE;
}

Which I know I will have to change later if I want the dialog to actually process messages, but I haven't gotten that far yet. The 1813 error suggests failure before the dialog is even created as does the NULL dialog handle returned.

To add the dialog I used the Add Resource wizard and added a small property page.

I've tried to follow advice here, but to no avail.

Thanks!



via Chebli Mohamed

How to format a US currency string using python or sed

I have numerous invoices that I sent to clients with this string at the bottom: Total: 1,000.00 or whatever the amount. Some are 2 figures, some 5 figures + the decimal part.

The thing is that the number's format is inconsistant accross all invoices. Sometimes its 1.000,00 and it keeps on switching the dot and the coma.

so with grep, awk and sed, i am able to only get the amount part from all invoices, without the dollar sign in order to sum them up to a grand total. But the dot and coma switching confuses python, obviously.

So in python (could be in sed as well), i am looking to convert the third char from the right to a dot and then from there on, every fourth char it finds, convert it to a coma.

In other words, it has to be able to separate the digits in groups of 3 from the right, add a coma in between each of them except for the first group at the far right which would be 2 digits separated by a dot.

Hope that is clear enough...



via Chebli Mohamed

Write a million records into an Excel

I tried to write data into excel with a million record using phpExcel. but it take too much time.

 

    $header=array('test1','test1','test1','test1','test1','test1','test1','test1');
    
$objPHPExcel = new PHPExcel();
// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") ->setTitle("Office 2007 XLSX Test Document") ->setSubject("Office 2007 XLSX Test Document") ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") ->setKeywords("office 2007 openxml php") ->setCategory("Test result file");
$objPHPExcel->getActiveSheet()->fromArray($header,NULL,'A1');
$sheet = $objPHPExcel->getActiveSheet();
// $final_xls_data1 is set of small records // $rowcount this variable is set of old rowcounts and set
$rowcount=$rowcount +1.
// create 8 small set of records. then add array in excel object $sheet->fromArray($final_xls_data1,NULL,'A'.$rowcount); $objPHPExcel->getActiveSheet()->setTitle('Simple'); $objPHPExcel->setActiveSheetIndex(0); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="01simple.xlsx"'); header('Cache-Control: max-age=0'); header('Cache-Control: max-age=1'); header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header ('Pragma: public'); // HTTP/1.0 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save($xls_file_path);

How can I do this?



via Chebli Mohamed

Dynamics CRM 2015 - update Opportunity Owner id via javascript

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

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

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

This is a view of the GetValue call.

enter image description here

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



via Chebli Mohamed

Bash readline history previous line before history expansion

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

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

!!:gs/20010910/20010911/



via Chebli Mohamed

Should I use sync or blocking channels?

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

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



via Chebli Mohamed

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

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

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



via Chebli Mohamed

Printing numbers

I am writing a program to display as below

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

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

my program is

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

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

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

Could someone please help how to achieve expected output.



via Chebli Mohamed

How to process data in object collection?

Now, in my object collection,obj:

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

and I print it out like this:

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

Here is my code

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

I wish to output:

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

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

I want to know how to get the output.



via Chebli Mohamed

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

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



via Chebli Mohamed

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

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

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

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

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

Scott



via Chebli Mohamed

Java 8 stream processing not fluent

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

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

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



via Chebli Mohamed

Background of user control hide the controls inside of him

http://ift.tt/1NmaMtn

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



via Chebli Mohamed

EasyMock record phase mock as argument

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

String s = 'a string';

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

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

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

EasyMock complains about:

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



via Chebli Mohamed

Regex:javascript

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

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

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

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



via Chebli Mohamed

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

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

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



via Chebli Mohamed

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

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

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



via Chebli Mohamed

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

Situation

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

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

Question

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

Is there a better way I am missing?

Other info

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

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



via Chebli Mohamed

becomeFirstResponder does not work in cellForRowAtIndexPath

When calling textView becomeFirstResponder from cellForRowAtIndexPath returns false, why?

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

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



via Chebli Mohamed

scrollView is nil when called from viewdidload

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

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

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

My ViewController viewdidload func - it works fine

@IBOutlet weak var scrollView: UIScrollView!


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



override func viewDidLoad() {

    super.viewDidLoad()



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

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

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

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


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

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

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



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

My ViewController clickEvent func - why scrollView is nil?

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


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

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

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

func clickEvent(sender: AnyObject) {

   ViewController().clickEvent()
}



via Chebli Mohamed

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

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

What is the best way to do this ?

Thanks,



via Chebli Mohamed

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

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

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



via Chebli Mohamed

Batch script for loop

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

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

i see this

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

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



via Chebli Mohamed

single web page cache prevention

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

Or

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

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



via Chebli Mohamed

Specifying a Range of Rows Based on Checkbox

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

Working in Excel 2013

Sub Insert_LL()


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


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


Application.ScreenUpdating = False


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

Application.CutCopyMode = False
Application.ScreenUpdating = True


End Sub



via Chebli Mohamed

Insert only paid account numbers into a new sheet

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

Sub Button1_Click()

  Dim t As Integer
  Dim i As Range

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

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

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

End Sub



via Chebli Mohamed

Coding array with NSCoder Swift

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

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

class MyObject: NSObject, NSCoding {

var storyPoints: [String] = []

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


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

???

}

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

}

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

Looking forward to any advices.

Thank you.



via Chebli Mohamed

Ember.js how to observe array keys changed by input

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

import Ember from 'ember';

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

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

});

Next I try to bind each setting to input

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

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

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

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

</table>

But observer doesn't work.

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



via Chebli Mohamed

AngularJS Directive Isolated Scope Issue

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

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

Code

Directives

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

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

Directive Template

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

HTML

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

    <title>ASX Watchlist and Charts</title>

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

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

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

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

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

</body>
</html>

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

Any suggestions greatly appreciated.



via Chebli Mohamed

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

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

enter image description here

I use this code and its working:

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

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

    End If
End Sub

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

enter image description here

How can i prevent this?

Thanks!



via Chebli Mohamed

spring-mvc mail not working with the ZK framework

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

When submitting the form, I get:

HTTP ERROR 404

Problem accessing /backend/sendEmail.do. Reason:

Not Found

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

The relevant entries in web.xml are:

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

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

In pom.xml:

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

In spring-mail.xml:

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

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

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

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

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

The form .zul:

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

and finally, the controller:

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

    @Autowired
    private JavaMailSender mailSender;

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

}

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

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

EDIT: As requested, the whole web.xml:

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

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

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

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

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

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

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

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

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

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

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

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

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

    <!-- End Less compiler -->

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


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




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

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



via Chebli Mohamed

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

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

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

EDIT: Sorry for bad English.



via Chebli Mohamed

pagination for a table contents in yii

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

In view,

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

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

                                    <?php


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

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


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

                            </table>

In Controller,

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

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

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



via Chebli Mohamed

UIImagePickerController with cameraOverlayView - misplaced views

I have a UIImagePickerController with a custom cameraOverlayView.

I create the imagePicker like this:

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

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

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

self.picker.delegate = self.overlay;


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

}];

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

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

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

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

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

Thank you!



via Chebli Mohamed

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

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



via Chebli Mohamed

Angular $modal scope - Passing an object to $modal

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

My modal HTML:

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

And in my Controller:

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

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

  }
});

Lastly for clarity, this is my masonry code

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

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



via Chebli Mohamed

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

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

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



via Chebli Mohamed

mardi 4 août 2015

In SQL, How to add values after add a new column in the existing table?

I created a table and inserted 3 rows. Then I added a new column using alter. How can I add values to the column without using any null values?

Verification of Result in ESQL

Here's the situation: I run a query that gives me one or many rows as a result in an array.

Like:

SET db = PASSTHRU('SELECT GUID,CONTROLNBR FROM TRANSACTION WHERE GUID > ? AND CONTROLNBR > ?' values(maxGuid,maxControlNbr);

That works fine but I want to verify the following:

Any result that has duplicate CONTROLNBR's must have the same GUID

So if my result set has something like this:

   CONTROLNBR | GUID
   --------------------
      5       | 123abc
      5       | 123abc

this is entirely valid, however this I need to return an error on:

   CONTROLNBR | GUID
   --------------------
      5       | 123abc
      5       | abc123

I'm not sure the best way to test the result like this in ESQL/SQL.

can't make a trigger update only the relevant rows

I'm working on a school project and my trigger gives me a hard time.

Its' purpose is to update the Rating field of an updated Product, but it updates all rows in Products instead.

CREATE TRIGGER Update_Rating 
ON  dbo.Reviews
FOR Insert
as
Update dbo.Products
set Rating=(Select [avarage_rating]=avg(r.Rating) 
            From dbo.Reviews as r join inserted  on r.ItemNumber = inserted.ItemNumber
            where r.ItemNumber = Inserted.ItemNumber)

Your help is much appreciated

ROW_NUMBER query

I have a table:

Trip  Stop  Time 
-----------------
1     A     1:10
1     B     1:16
1     B     1:20
1     B     1:25
1     C     1:31
1     B     1:40
2     A     2:10
2     B     2:17
2     C     2:20
2     B     2:25  

I want to add one more column to my query output:

Trip  Stop  Time Sequence
-------------------------
1     A     1:10   1
1     B     1:16   2 
1     B     1:20   2
1     B     1:25   2
1     C     1:31   3
1     B     1:40   4 
2     A     2:10   1
2     B     2:17   2
2     C     2:20   3
2     B     2:25   4  

The hard part is B, if B is next to each other I want it to be the same sequence, if not then count as a new row.

I know

row_number over (partition by trip order by time)
row_number over (partition by trip, stop order by time)

None of them will meet the condition I want. Is there a way to query this?

Sql Server Pivoting

Trying to convert the row value to column (PIVOT) of the given table.

S.No          ID    Column2 Column3
1              1    1       Firstname
2              1    2       MiddleName
3              1    14      ContactNumber
4              2    1       Firstname
5              2    14      ContactNumber
6              3    14      ContactNumber
7              3    2       MiddleName

I want like below for ID 1

Clumn2  1           2           14
Column3 FirstName   MiddleName  LastName

please help me to solve it. Thanks

how to change this sql statement so it returns one row per widget

I have the following sql query:

select O.name, O.asset_no, A.name as attr_name, AV.string_value, D.dict_value INTO OUTFILE '/tmp/networkchassis_1503_detailed.csv' FIELDS ENCLOSED BY '"' TERMINATED BY ',' ESCAPED BY '"' LINES TERMINATED BY '\r\n' 
FROM Object as O 
left join AttributeMap as AM on O.objtype_id = AM.objtype_id 
left join Attribute as A on AM.attr_id = A.id 
left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = O.id 
left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id 
left join Chapter as C on AM.chapter_id = C.id WHERE O.id IN ('5261', '5262', '5263', '5461', '5268', '5271', '22469', '5284', '14418', '5288', '5291', '5292', '5294', '5295', '20629', '20630', '5296', '5297', '5307', '5238', '22425', '22426', '5315', '5316', '22429', '22430', '5317', '22431', '22427', '22428', '5320', '5321', '5325', '5326', '13373', '5329', '14671', '14672', '22432', '22433', '8999', '648', '393', '394', '471', '395', '396', '1688', '1689', '268', '269', '5582', '5583', '5584', '5585', '5586', '5587') AND A.name in ("FQDN", "HW Type") ORDER BY O.name;

This returns two rows, per widet, one with FQDN, and the other for HW Type, like so:

+-----------+----------+-----------+--------------------------------+--------------------------------+
| name      | asset_no | attr_name | string_value                   | dict_value                         |
+-----------+----------+-----------+--------------------------------+----------------------------------------+
| widget1   | 1026857  | HW Type   | NULL                           | HP |
| widget1   | 1026857  | FQDN      | widget1.domain.net   | NULL                                   |

I'd like to change the query so that I get one row, with both attributes specified. Something like this...

+-----------+----------+-------------------+----------------+--------------------------------+
| name      | asset_no | fqdn              |  hw_type       | string_value                   | dict_value                         |
+-----------+----------+-----------+--------------------------------+----------------------------------------+
| widget1   | 1026857  | widget2.domain.net| HP             | 

Syntax error (from clause) in query expression in statement

string sqlStatement = "SELECT Orders.[ID], Orders.[Checkintime], Orders.[RoomPrice], Orders.[OrderNo], Particulars.FirstName, Particulars.LastName FROM Orders, where Checkintime between '" + dateOnly + "' and '" + endDateOnly + "', Particulars;";

I tried using this statement to select information from my database but this statement has syntax errors from the FROM clause

Oracle forms where clause with a variable from bloc item

I'm trying to populate a block using a FROM clause in oracle forms like this:

select h.no_ordre, h.marge,h.date_modification, h.utilisateur_modification from hist_marge_0alb h, simul s, simtauxvar_0alb sv, affaire a where s.id_affaire = a.id_affaire and s.id_simul_element(+) = h.id_simul_element and sv.id_simul_element = s.id_simul_element and s.id_affaire = :SIMUL.id_affaire

But i got a FRM 40505 Error. I think the problem is in :SIMUL.id_affaire but I don't find a way to do it. Is there a way I can do it? Thanks.

concatenate query result in a string

I am getting a db result as 3 rows (Please see image link below).

enter image description here

The sql statement used is

select tevmkt.ev_mkt_id, tevmkt.name, tevmkt.ev_id, tevoc.ev_oc_id, 
       tevoc.desc, tevoc.fb_result, tevoc.lp_num, tevoc.lp_den, 
       tev.start_time
from tevmkt, tev,tevoc
where tevmkt.name = '|Match Result|' and tev.ev_id=tevmkt.ev_id and 
      tevoc.ev_mkt_id=tevmkt.ev_mkt_id and tev.start_time>=Today;

I will like to use php to concatenate each of the 3 rows into string or maybe use SQL statement.

So, the first 3 rows will display as ;

632274|Match Result||Draw||Aldershot Town||Arsenal FC|

And the next 3 rows

637799|Match Result||Draw||Southend United||Oxford United|

is it possible to store ResultSet from a query into an array and use the array as search parameters for an SQL query

i have two tables WorkSkillsPlanning(WSP) and TrainingAchieved(TA). WSP hold a list of planed training and targeted number of people to be trained e.g. ISOO:90001 10 people while TA holds the actual number of people trained as well as the actual course done. Since WSP and TA are dynamic in the sense that the data they hold is not static neither is known as training plans can change is it possible to run an intersect query on these table to find similarities i.e a course in WSP which has actually be done and recorded in TA. Store the results of the intersect query in an array e.g. MyArrayList{ISO,COMMUNICATION) these being values present in both table and use MyArrayList values to run count queries on TA to establish the number of people who would have done the course i.e ISO and COMMUNICATION and use the resultant to subtract from WSP (ISO,COMMUNICATION).

here is an example, first part

"Select QUALIFICATIONGROUP from  APP.WSP intersect select COURSEBOOKED from APP.BOOKCOURSE"

which results in ISO and COMMUNICATION which i want to store in an ARRAY or variable.

second part

select count(COURSEBOOKED) from APP.BOOKCOURSE where COURSEBOOKED = Variable1
 rs.getString(Count(COURSEBOOKED))
 value returned == 5

re do the process again for COMMUNICATION and any other course in the array, of which after use the values returned from the count query to subtract to subtract WSP total minus TA total.

I hope this makes sense