How to make a static lib based on other static libs using GCC?

I want to make a static library called libXYZ.a using some existing static libraries: libX.a, libY.a, libZ.a and some object files. The command line I used to build the static library libXYZ.a is:

ld -o libXYZ.a one.o two.o -L./ -L/cygdrive/c/cygwin/lib/gcc/i686-pc-cygwin/4.8.2 -lX -lY -lZ -lstdc++

I'm using Cygwin GCC (g++) to compile one.cpp and two.cpp to get one.o and two.o before the ld command like the following:

g++ -o one.o one.cpp -c
g++ -o one.o two.cpp -c

libX.a, libY.a, libZ.a are all located in the current directory (that's why -L./). And I added the C++ standard library linker flag -lstdc++ in the ld line. But I got the following error when I make it:

one.o: one.cpp:(.text+0x32): undefined reference to `_Unwind_Resume'
ld: one.o: bad reloc address 0xd in section `.text$_ZN10ConfigC1Ev[__ZN10ConfigC1Ev]'
Makefile:22: recipe for target 'libXYZ.a' failed

So my question is: Is the ld command the right command to build the static lib from other static libs and .o files? What caused the error? I searched the forum and found that it is possible caused by some incompatible compiler. But I built all my source code using the same GCC compiler.

UPDATE:

I tried again using the following command:

ld -o libXYZ.a one.o two.o -L./ -lX -lY -lZ

But I'm still getting the following errors:

one.o:one.cpp:(.text+0x32): undefined reference to `_Unwind_Resume'
one.o:one.cpp:(.text+0x12a): undefined reference to `_Unwind_Resume'
...
./libX.a(wrapper.o):wrapper.cpp:(.text+0x7ba): undefined reference to `__chkstk_ms'
./libX.a(wrapper.o):wrapper.cpp:(.text+0x7ba): undefined reference to `_Unwind_Resume'
...

And I omitted numerous similar errors like the above _Unwind_Resume errors. Any ideas on what caused those errors?


TypeError: 'NoneType' object has no attribute '__getitem__' | total_number_messages += result["verify_counter"]

print("* Parsing users email in parallel..")
pool = Pool(processes=NUM_PROCESSES)
for result in pool.imap_unordered(worker, usernames, chunksize = 2):
    total_number_messages += result["verify_counter"]
    total_number_messages_imported += result["num_imported"]
    total_number_duplicates += result["duplicate_counter"]
    address_book[result["current_user_email"]] = result["username"]
    combined_msg_senders.append({
                                "counter": result["counter"],
                                "address": result["current_user_email"],
                                "username": result["username"]
                                })
pool.close()
pool.join()

please help me with this error getting for above, getting error below

Traceback (most recent call last):
  File "metadata.py", line 539, in <module>
    main()
  File "metadata.py", line 511, in main
    total_number_messages += result["verify_counter"]
TypeError: 'NoneType' object has no attribute '__getitem__'

that code you can check at
http://brage.bibsys.no/xmlui/handle/11250/198551


AngularJS and WordPress API display data from single post

I'm using the WordPress API as a data service to an AngularJS/Ionic app. I have a post type called programmes and have a list of programmes (posts) and the JSON looks like:

var programmes = [
 {
  id: 6,
  title: "A post",
  slug: "a-post"
 },
 {
  id: 7,
  title: "Another post",
  slug: "another-post"
 },
 {
  id: 8,
  title: "Post 123",
  slug: "post-123"
 }
]

I've got the list of programmes displaying with ngRepeat. However I'm struggling to get the data for an individual post.

I was trying to do it like so to get data for the single programme: var programme = programmes[$stateParams.programmeId]; however the issue is, for example, if I click on the first "A post" it returns 6 from the programme id but this does not match the index of the object which is 0.

How can I get data from a single programme when the id and index do not match without having to manually reset the programme id's in the database?

Here are my files so far:

app.js

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

  .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "templates/menu.html",
    controller: 'AppCtrl'
  })

  .state('app.programmes', {
    url: "/programmes",
    views: {
      'menuContent': {
        templateUrl: "templates/programmes.html",
        controller: 'ProgrammesCtrl'
      }
    }
  })

  .state('app.programme', {
    url: "/programmes/:programmeSlug",
    views: {
      'menuContent': {
        templateUrl: "templates/programme.html",
        controller: 'ProgrammeCtrl'
      }
    }
  })
  $urlRouterProvider.otherwise('/app/programmes');
});

data.js

.factory('DataFactory', function($http) {

  var urlBase = 'http://event-app.dev/wp-json/wp/v2';
  var APIdata = {};

  var currentProgramme = null;

  return {
    getProgrammes: function() {
      return $http.get(urlBase + '/programmes');
    }
  }
})

controllers.js

.controller ('ProgrammesCtrl', function ($scope, DataFactory) {
  getProgrammes();
  function getProgrammes() {
    DataFactory.getProgrammes().then(function(response) {
      $scope.programmes = response.data;
    },
    function(error) {
      $scope.status = 'Unable to load data';
    });
  }
})

.controller ('ProgrammeCtrl', function ($scope, $stateParams, DataFactory) {
  getProgrammes();
  function getProgrammes() {
    DataFactory.getProgrammes().then(function(response, id) {
      var programmes = response.data;
      $scope.programme = programmes[$stateParams.programmeId];

    },
    function(error) {
      $scope.status = 'Unable to load data';
    });
  }
})

programme.html (view to display a single programme)

<ion-view view-title="{{programme.title}}">
  <ion-content>
    <ion-list>
      <ion-item>
        {{programme.title}}
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>


Is there a better way to get list of objects in JavaFX than iteration?

I have several fields with people names and their ages. Amount of those fields are random, depending on how many people are participating. I want to select in separate list all fields with names and in another all fields with ages. What way better to select all TextFields on page and separate them by name/age?


pass a bitmap image from one activity to another

In my app i am displaying no.of images from gallery from where as soon as I select one image , the image should be sent to the new activity where the selected image will be set as background.However, I am able to get the images from gallery but as soon as I select one the application crashes.Thanks in advance

Activity-1(The images are shown in gallery and the selected image is sent to new activity)

public class Gallery extends Activity {

private static int RESULT_LOAD_IMAGE = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);

        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }

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

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {

            Uri contentUri = data.getData();
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String tmppath = cursor.getString(column_index);
            Bitmap croppedImage = BitmapFactory.decodeFile(tmppath);

            // Bitmap croppedImage = BitmapFactory.decodeFile(croppedImage);
            Intent intent = new Intent(Gallery.this,GesturesActivity.class);
            intent.putExtra("bmp",croppedImage);
            startActivity(intent);

            Log.v("sending image","sending image");

        }

    }
}

Activity-1(XML)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    >
    <ImageView
            android:id="@+id/imgView"
            android:layout_width="fill_parent"
            android:layout_weight="1" android:layout_height="wrap_content"></ImageView>
    <Button
            android:layout_height="wrap_content"
            android:text="Load Picture"
            android:layout_width="wrap_content"
            android:id="@+id/buttonLoadPicture"
            android:layout_weight="0"
            android:layout_gravity="center"></Button>
</LinearLayout>

Activity-2(The activity where the selected image should be set as background image of the screen)

  public class GesturesActivity extends Activity {

        private final int MENU_CAMERA = Menu.FIRST;

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);

            Bitmap bmp = (Bitmap)this.getIntent().getParcelableExtra("bmp");
            BitmapDrawable background = new BitmapDrawable(bmp);
            getWindow().setBackgroundDrawable(background);  //background image of the screen

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.advert);
            View view = new SandboxView(this, bitmap);

            setContentView(view);
        }

        public boolean onPrepareOptionsMenu(Menu menu) {
            menu.clear();

                menu.add(0, 11, 0, "Take Snapshot");

                    return super.onPrepareOptionsMenu(menu);
        }

        public boolean onOptionsItemSelected(MenuItem item) {

            return super.onOptionsItemSelected(item);
        }

    }


Best design for lookup-and-possibly-change method

I am designing a class that stores (caches) a set of data.  I want to lookup a value, if the class contains the value then use it and modify a property of the class.  I am concerned about the design of the public interface.

Here is how the class is going to be used:

ClassItem *pClassItem = myClass.Lookup(value);
if (pClassItem)
{ // item is found in class so modify and use it
  pClassItem->SetAttribute(something);
  ... // use myClass
}
else
{  // value doesn't exist in the class so add it
  myClass.Add(value, something);
}

However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass).
To get round that the following could be considered:

bool found = myClass.Lookup(value);
if (found)
{ // item is found in class so modify and use it
  myClass.ModifyAttribute(value, something);
  ... // use myClass
}
else
{  // value doesn't exist in the class so add it
  myClass.Add(value, something);
}

However this is inefficient as Modify will have to do the lookup again.  This would suggest a lookupAndModify type of method:

bool found = myClass.LookupAndModify(value, something);
if (found)
{ // item is found in class
  ... // use myClass
}
else
{  // value doesn't exist in the class so add it
  myClass.Add(value, something);
}

But rolling LookupAndModify into one method seems like very poor design.  It also only modifies if value is found and so the name is not only cumbersome but misleading as well.

Is there another better design that gets round this issue?  Any design patterns for this (I couldn't find anything through google)?


Tabbing to All Radio Buttons in a Group Box

I have radio buttons in a groupbox and I want to happen when each time I press TAB, the focus will be on the next radio button. How will I do that?
What's happening is that the only one that is getting the focus is the first radio button. Their TabStop is set to True and their TabIndex is in order.


Sort document collection by values total in xpages

I'm working on an xpages application in which I would like to display the top5 of the total volumes per client.

I have a list of customers who buy any number of products.I would like to classify customers according to the total volume of products purchased.
I use the "Top5" View categorized by customer.

I used a document collection to calculate the total volume by customer.

I get to classify volumes in descending order and select the top 5.But this does not allow me to retrieve the name of the product and the client from the view.

var cls3 = @DbColumn("","Top5",1);
sessionScope.put("clientsList3",cls3);
var db=session.getCurrentDatabase();
var view7=db.getView("Top5")
var dataa =[] ;
         var top =[];

         for(var r = 0; r < clientsList3.length; r++){

           var Cli = @Trim(@Text(clientsList3[r]));
           var VolumeTotal :NotesDocumentCollection =  view7.getAllDocumentsByKey(Cli);

           var vola = 0;
           var array = new Array();
           var prod = "";

 if (VolumeTotal == 0) {array = 0;}
             else{
            var doca = VolumeTotal.getFirstDocument();
                while (doca != null)
                {vola = vola + doca.getItemValueInteger("TotalVolume_Intermediate");
                    doca = VolumeTotal.getNextDocument(doca);
                    }
                array.push(vola);

            }
        dataa[r] = array;
              dataa.sort(function(a, b) {return b - a;});

   top = dataa.slice(0,5);

             }

          return  dataa;

      }


Firefox WebExtention won't load

So, I tried to load my add-on using the about:debugging page in Firefox. But, it simply wouldn't load. Is there somewhere where an error would be logged that I could find it?

Here is my manifest.JSON code:

{
    "description": "Adds a stickfigure",
    "manifest_version": 2,
    "name": "StickMan",
    "version": "1.0",
    "icons": {
        "48": "icons/StickMan-48.png"
    },
    "applications": {
        "gecko": {
          "id": "extention@stick.man",
          "strict_min_version": "45.0"
        }
    },
    "permissions": [
        "activeTab"
    ],
    "background": {
        "scripts": ["StickManUpdate.js"]
    },
    "browser_action": {
        "default_icon": {
            "48": "icons/StickManButton.png"
        },
        "default_title": "Call StickMan",
    },
}

I hope that this helps other frustrated add-on creators.

Thanks in advance


Git and multiple copies of file with difference in casing

I renamed one of the project file in Git from say My.Test to My.test. In the main repository, I am seeing both of copies of the project. Also, any changes that I am doing in My.test project are actually getting added in My.Test project in the main repository.

Scenario

1) Originally started with : My.Test
2) Renamed My.Test to My.test
3) Made changes in My.test

In main repo :

1) Both My.Test & My.test are getting listed
2) Changes done to My.test and getting listed in My.Test.

Any help in resolving this issue will be much appreciated.

Regards
Pawan Mishra


Zip upload with curl post request

I try to upload a zip-File with Curl Post Request.

But the Zip File is empty after Upload.

Here my Code:

// Add the Zip File

            $cfile = curl_file_create($dateipfad . '/bestand.zip', 'application/zip', $neuerdateiname);
            $filedata = array('file' => $cfile, ';type' => 'application/zip');

    // Set Curl Option
            curl_setopt($ch, CURLOPT_URL, $config->MOBILE_API_SERVER . $neuerdateiname);  //Set the Url (https://services.mobile.de/upload-api/upload/foobar-2016-02-09_11-11-11.zip)
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Get the response from cURL
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('POST upload-api/upload/'.$neuerdateiname.' HTTP/1.0', 'Host: services.mobile.de', 'Authorization: '.base64_encode($config->MOBILE_DE_USER . $config->MOBILE_DE_PASS) ));
            curl_setopt($ch, CURLOPT_USERPWD, $config->MOBILE_DE_USER . ':' . $config->MOBILE_DE_PASS);         // Username Password
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // --data-binary
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/zip']);        // -H
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);      // -0
            curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);        //Create a POST array with the file in it

    $response = curl_exec($ch);

// Error / Success Messages

 if($errno = curl_errno(ch)) {
        $error_message = curl_strerror($errno);
        echo "cURL error ({$errno}):\n {$error_message}";
    }

[Edit 14.12.]
If i try to use ssh - i get follow Message:

<T -X POST --data-binary @bestand.zip https://services.mobile.de/upload-api/upload/foobar-2016-02-09_11-11-11.zip
* About to connect() to services.mobile.de port 443 (#0)
* Trying 2a04:cb41:f016:1::2b...
* Connected to services.mobile.de (2a04:cb41:f016:1::2b) port 443 (#0)
* Initializing NSS with certpath: none
* Unable to initialize NSS
* Closing connection 0
curl: (77) Problem with the SSL CA cert (path? access rights?)


Linear search in c#

Hey guys I am a beginner at coding and I'm doing a linear search in c# and can't figure out how to make it show in what array the number was found when doing the search. It just makes it say that it's on the last array. Here's my code:

Random Generator = new Random();
int[] array = new int[100];
int count = 0;
for (int i = 0; i < array.Length; i++)
{
    array[i] = Generator.Next(1, 100);
    count++;
}
Console.WriteLine("Write a number between 1-100 and see if it's in a array and in what array.");
int guess = Convert.ToInt32(Console.ReadLine());

bool exists = array.Contains(guess);
if (exists)
{
    Console.WriteLine("Your number {0} is in the {1}th Array.", guess, count);
}
else
{
    Console.WriteLine("Your number {0} does not match any number in any of the Arrays.", guess);
}

Console.ReadKey();

There's something wrong with my count int, but I don't know what to do. Thanks in advance.


Unable to display out the remaining date

My program will get data from database and show it in a Listview. Now I get the date from database and compare it with my current date and count the remaining day. I successfully got the data and show it in a listview, but my remaining day code is not working. Any help will be appreciated!

    List<HashMap<String,Object>> aList = newArrayList<HashMap<String,Object>>();
    for (int i = 0; i<records.size(); i++) {
        HashMap<String, Object> hm = new HashMap<String, Object>();
        hm.put("txt", records.get(i).getAssname());
        hm.put("txt2", records.get(i).getAssTime());

        String ez = records.get(i).getAssTime();
        Calendar today = Calendar.getInstance();

        //count the remain day
        try {
            SimpleDateFormat dd = new SimpleDateFormat("dd/M/yyyy");
            Date date1= dd.parse(ez);
            Date date2 = today.getTime();
            long diff = Math.abs(date1.getTime() - date2.getTime());
            long diffDays = diff / (24 * 60 * 60 * 1000);

            hm.put("txt3", String.valueOf(diffDays));

        } catch (Exception e1) {
        }
        aList.add(hm);
    }

    // Keys used in Hashmap
    String[] from = {"txt","txt2","txt3"};

    // Ids of views in listview_layout
    int[] to = { R.id.assigment_name,R.id.assigment_ATime, R.id.assigment_remain};

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.view_assignment_entry, from, to);

What's wrong with my code ?


iPhone App Ad-hoc testing

So I am currently making an app for somebody else that lives in another state. Is there any way that I can somehow upload it (Ad-hoc?) to somewhere, and they can download it on their phone to test out themselves? I'm guessing I would have to know there ID's for their iPhone.

If this is possible, how can I do this? I currently have the $99 developer license.


Adding text from mySQL query onto canvas

In this code, I successfully get five random text strings from a mySQL database, and can echo them via PHP.

Instead of echoing them via PHP, I would rather like to display them as text in the canvas (in place of the "Hello World" text) of the attached code.

Any ideas of how I would have to go about doing this?

<HTML>
<HEAD>
    <TITLE></TITLE>
</HEAD>
<BODY>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>

<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.font = "30px Arial";
    ctx.fillText("Hello World",10,50);
</script>

<?PHP
    //CREATE CONNECTION
    $con=mysqli_connect('localhost','','');
    //select database
    if(!mysqli_select_db($con,'test')) {
        echo "database not selected";
    }
    //select query
    //select random question
    $sql=
        "select * from `general knowledge`
        order by rand()
        limit 5";
    //execute sql query
    $records= (mysqli_query($con,$sql));
        while ($row=mysqli_fetch_array($records)) {
            echo "<P>";
            echo "".$row['Question Text']."";
        }
?>


AngularJS How to initialize a select using ng-options with an object value

I would like to initialize a selection of a select field with ng-options.

Lets assume we've got the following items:

$scope.items = [{
  id: 1,
  label: 'aLabel',
  subItem: { name: 'aSubItem' }
}, {
  id: 2,
  label: 'bLabel',
  subItem: { name: 'bSubItem' }
}];

The following html:

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>

But now instead of selecting the option by the following command:

$scope.selected = $scope.items[0];

I do not have the object, I have only the information of the id so I like to initialize the select by something like that:

$scope.selected = $scope.otherRandomObject.id

My thought was that using track by item.id is somehow creating the relation between object and the id.


How to install cross compiler (on ubuntu 12.04 LTS) for microprocessor SA1100?

Can someone please tell me how to install the cross compiler (programming language C) for the SA1100 microprocessor? I have ubuntu 12.04 LTS. I´m a complete noob to Linux, I just installed Ubuntu yesterday. I need a special variant of the GCC compiler that is named "arm-unknown-linux-gnu-gcc" but don know how to do it.

Can someone please help me?


gethostbyname() sometimes could not dns forever

In one of our product(embeded platform using RTL8196e chips), sometimes the program fails to DNS forever before the program is restarted.

More investigation found that if the program starts before the network is ready(e.g.: before DHCPed by udhcpc), the following up calling for gethostbyname() would failed for ever, even at the time ping is working when network is OK.

some tests have done to illustrate:(in the simplest form, e.g.: omit print the result of gethostbyname)

The programs are started before the network is ready(e.g.: before eth0 has get the IP by DHCP)

Program 1: could not get IP for ever after network is OK(ping is ok)

while (1) {
  res_init();
  gethostbyname(...); //not work
  sleep(5);
}

Program 2: the execution of gethostbyname() in the forked process works

while (1) {
  pid = fork();
  ...
  if (pid == 0)
     res_init();
     gethostbyname(...); //works
  else
     waitpid(pid1,...);
  sleep(5);
}

Program 3: the execution of gethostbyname() both failed in child/parent process

while (1) {
  pid = fork();
  ...
  if (pid == 0)
     res_init();
     gethostbyname(...); //not work
  else
     res_init();
     gethostbyname(...); //not work
     waitpid(pid1,...);
  sleep(5);
}

I am totally blank what's the reason for this weird behavior... Is it something about glic or kernel?

Any explanation would be appreciated.


Proper way to prevent SQLAlchemy from re-running queries on expired objects?

I'm having trouble wrapping my head around how to deal with expired sqlalchemy objects in a flask request.  Let's say I do something like the following:

from models import Foo, Bar

@app.route("/page")
def page():
  foos = Foo.query.all()

  for foo in foos:
    b = Bar(foo.data)
    db.session.add(b)

  db.session.commit()

  return render_template('page.html', foos=foos)

and then in page.html:

{% for foo in foos %}
  {{ foo. name }}
{% endfor %}

SQLAlchemy will then do a select query for each foo in the template loop, because the session.commit() marked the foos collection as expired.  If I know that there is no way for foos to actually have changed, what is the right way to prevent len(foos) queries from being executed?  Similarly, if foos has changed, what is the right way to refresh the data with a single query rather than many?


cocoa circular progressbar only animated when key pressed or mouse moved?

I show the circular progressbar in NSPanel, when the panel first time opened, it works fine. When it is hidden, and opened again, the circular progressbar only animates when key pressed or mouse moved.


VB script to open and close excel file without excel

I want to open and save an excel file in sharepoint, which has no excel installed. I tried to write an vbscript but I only can find which called excel application. Please help to advise. Thank you!

Set objExcel = CreateObject("Excel.Application")

Set objWorkbook = objExcel.Workbooks.Open("D:\Roambi\Test excel\Test.xlsx")

objExcel.ActiveWorkbook.Save

objExcel.ActiveWorkbook.Close

objExcel.Application.Quit

WScript.Quit


newline after heading while using <h3> tag in android

Recently I was trying out HTML tags in android. When I tried to use the <h3> tag, it automatically creates a line space after it and before the next line. In HTML one can remove it by making padding and margin set with 0px. Can anyone tell me how can I remove this space in an android app?


How to debug the code in winform

I have a function like this in one of my classes

using MFDBAnalyser;

namespace PrimaryKeyChecker
{
    public class PrimaryKeyChecker : IMFDBAnalyserPlugin
    {
        public string RunAnalysis(string ConnectionString)
        {
            return "Srivastava";
        }
    }
}

and when I call the RunAnalysis(string ConnectionString) method in another class like this

namespace MFDBAnalyser
{
    public interface IMFDBAnalyserPlugin
    {
        string RunAnalysis(string ConnectionString);
    }
}

Then how can I check that the RunAnalysis is whether returning Srivastava or not....


tcl changing a global variable while in a child interpreter (interp)

I am trying to use a TCL program to read TCL modulefiles and translate them into another language. This has worked quite well until now.  For reasons too complicated explain I have to treat "puts stderr" differently in different parts of the modulefile.  I am asking for help in trying to figure out a way to do this.

Below is an extremely abbreviated modulefile called "modfile".  This "modfile" is translated or "sourced" by a second tcl program.

    proc ModulesHelp { } {
      puts stderr "(1) This is a help message"
    }
    puts stderr "(2) Here in modfile"

The puts statement inside ModulesHelp has to be treated differently from the second puts statement.  Note that any solution CAN NOT CHANGE "modfile".  That file is not under my control.

Here is my attempt at a solution:

    #!/usr/bin/env tclsh
    proc myPuts { stream msg } {
        global putMode
        puts stdout "putMode: $putMode"    # <====== HERE 1
        puts stdout $msg
    }

    proc report { message } {
        puts stderr "$message"
    }

    proc execute-modulefile { m } {
        global MODFILE putMode

        set putMode "normal"
        set slave   "__mod"

        interp create $slave
        interp alias  $slave puts {} myPuts
        interp alias  $slave report {} report
        interp eval   $slave {global putMode }
        interp eval   $slave [list "set" "putMode" $putMode]
        interp eval   $slave [list "set" "m"       $m]

        set errorVal [interp eval $slave {
        set sourceFailed [catch {source $m } errorMsg]
            if {[info procs "ModulesHelp"] == "ModulesHelp" } {
                set putMode "InHelp"     # <======= HERE 2
                ModulesHelp
            }
            if {$sourceFailed} {
                report $errorMsg
                return 1
            }
        }]
        interp delete $slave
        return $errorVal
    }

    eval execute-modulefile $argv

To run this I do:  $ ./try.tcl modfile where obviously the above script is "try.tcl" and the modulefile is "modfile".  I am running this on a linux system with tcl 8.4.

What I would like to have happen is that at the line labelled "HERE 2" I like to somehow change the global variable of "putMode" from "normal" to "InHelp" so that I can change the behavior at the line labelled "HERE 1".  No matter what I have tried to do I can not change the value of putMode at "HERE 1" by doing something at "HERE 2".  The puts statement at "HERE1 always says "normal".

Using a global variable seems like the easiest solution but if someone could show me how to use namespaces or some other technique, I'll be happy with that as well.

Thanks for any insight.

I greatly appreciate the time that others have looked at my question.  I am trying to use the proposed solution and I'm not quite seeing it.  Here is my new attempt at a solution (This doesn't work at all).  Can someone suggest how I modify this code to change "putMode" to inHelp where "HERE 2" is?  Also is there something special that needs to go where "HERE 1" is?

    #!/usr/bin/env tclsh
    proc myPuts { stream msg } {
        global putMode
        puts stdout "putMode: $putMode"  # <=== HERE 1
        puts stdout $msg
    }

    proc report { message } {
        puts stderr "$message"
    }

    proc PutModeTrace {childInterp operation realPutMode} {
        # Alias the main array element for the purposes of this procedure
        upvar \#0 PutMode($childInterp) realPutMode
        if {$operation eq "read"} {
            interp eval $childInterp [list set putMode $realPutMode]
        } elseif {$operation eq "write"} {
            set realPutMode [interp eval $childInterp {set putMode}]
        }
    }
    proc execute-modulefile { m } {
        global MODFILE putMode

        set putMode "normal"
        set slave   [interp create]

        interp alias  $slave puts {} myPuts
        interp alias  $slave report {} report
        interp eval   $slave {global putMode }
        interp eval   $slave [list "set" "putMode" $putMode]
        interp eval   $slave [list "set" "m"       $m]
        interp eval   $slave [list "set" "slave"   $slave]
        interp eval   $slave {trace add variable putMode {read write} PutModeTrace}
        interp alias  $slave PutModeTrace {} PutModeTrace $slave
        set errorVal [interp eval $slave {
        set sourceFailed [catch {source $m } errorMsg]
            if {[info procs "ModulesHelp"] == "ModulesHelp" } {
                set start "help(\[\["
                set end   "\]\])"
                PutModeTrace $slave "write" "inHelp"  # <=== HERE 2
                puts stdout $start
                ModulesHelp
                puts stdout $end
            }
            if {$sourceFailed} {
                report $errorMsg
                return 1
            }
        }]
        interp delete $slave
        return $errorVal
    }

    eval execute-modulefile $argv


NAudio ASIO Playback wav

I'm using NAudio and ASIO to play a sequence of wav files. I need to use ASIO because the audio card supports only that. I was able to play each wav in this way:

     waveRead = new WaveFileReader(completeStreamMS); //completeStreamMS is a memorystream
     waveRead.Position = 0;
     pcm = new WaveChannel32(waveRead);
     reductionStream = new BlockAlignReductionStream(pcm);
     reductionStream.Position = 0;
     waveOutDevice.Init(reductionStream);
     waveOutDevice.Play();

Now I need to insert 1 second of silent before the starting of the wav. The only way I found is to use an OffsetSampleProvider, but if I do like this

     ISampleProvider isp = WaveExtensionMethods.ToSampleProvider(waveRead);
     var offset = new SampleProviders.OffsetSampleProvider(isp);
     offset.DelayBy = TimeSpan.FromSeconds(1);
     var wp = new SampleProviders.SampleToWaveProvider(offset);
     waveOutDevice.Init(wp);`
     waveOutDevice.Play();

The first wav plays just fine, but as soon as I stop() the waveOutDevice or I try to reinstantiate a new one the execution of the program stops at that position with

System.ExecutionEngineException
Cannot intercept exception. Debugged program can not be continued and properties can not be evaluated.

I'm not able to understand why. Please help.
Thanks


How to make RichTextValue catalog full text search for Plone 4

I created dexterity content type with Rich Text Field - "body text". I'd like to make "body text" full text searchable for my Plone 4.0.2.

I added catalog.xml in my theme, code below

I got error message from ZMI/portal/portal_catalog "body_text RichTextValue object. (Did you mean .raw or .output?) "

How can I change catalog.xml to use .output, I tried , but it doesn't work.

Thanks.


Why webRequest.onBeforeSendHeaders doesn't provide query string while browser.webNavigation.onBeforeNavigate does?

I am trying to implement a web extension which removes redirect intermediate from links. For example, when you click any link to foreign site from vk.com (a social network), you'll be navigated to https://vk.com/away.php?to=URL_GOES_HERE.

When you listen to onBeforeNavigate events like that:

browser.webNavigation.onBeforeNavigate.addListener(
    (details) => {
        console.log('before navigate', details);
    }, {
        url: [
            {hostContains: "vk.com"}
        ]
    }
);

you'll get full URL: before navigate Object { url: "https://vk.com/away.php?to=URL_GOES_HERE", timeStamp: 1488807415002, frameId: 0, parentFrameId: -1, tabId: 2 }

But you have no option to replace that navigation action with another URL. You have that ability only for webRequest API:

browser.webRequest.onBeforeSendHeaders.addListener(
    (details) => {
        console.log('before web request', details)
    },
    {urls: [
        '*://vk.com/away.php'
    ]},
    ['blocking', 'requestHeaders']
);

but URL there doesn't contain query parameters: before web request Object { requestId: "1", url: "http://vk.com/away.php", originUrl: "https://vk.com/feed", method: "GET", type: "main_frame", timeStamp: 1488807415092, frameId: 0, parentFrameId: -1, tabId: 2, requestHeaders: Array[6] }

Why is it working so? Is it a bug or what?


Customize install.xml name in izpack

I have a problem where in my install.xml in izpack, I have few packs with conditions, and my multiple packs have common file source and targets, because of which, installer slows down and shows each file's copy and takes around 15 minutes, whereas, in reality, it should just take 3-4 minutes overall. It is pretty fast if I don't keep anything conditional in install.xml

I want a solution for the slowdown problem. If izpack offers some customization on this XML name, then I can have two separate install XML's based on my needed packs in each install XML.

Is it possible?


(libgdx/java) ArrayList won't clear/delete instance of class?

Item class:

       public class Item {
          public float x, y, speedx, speedy;
        public Rectangle container;
        public Texture texture;
       static Timer timer = new Timer();
      static  int amount;
       static int spawned;
        public int itemtype;
        //   float delay = 1; // seconds

        public void move() {
            x += speedx;
            y += speedy;

            container.x = x;
            container.y = y;

        }
  public void setTexture(int itemtype){
        switch(itemtype){
            case 1:
                texture = new Texture("items/item1.png");
                break;
            case 2:
                texture = new Texture("items/item2.png");
                break;
            case 3:
                texture = new Texture("items/item3.png");
                break;
            case 4:
                texture = new Texture("items/item4.png");
                break;
            case 5:
                texture = new Texture("items/item5.png");
                break;
            case 6:
                texture = new Texture("items/item6.png");
                break;
            case 7:
                texture = new Texture("items/item7.png");
                break;
            case 8:
                texture = new Texture("items/item8.png");
                break;
            case 9:
                texture = new Texture("items/item9.png");
                break;
            case 10:
                texture = new Texture("items/item10.png");
                break;
            default:
                texture = new Texture("items/error.png");
                break;
        }

    }
          public static void spawnItem(int amount){
            Item.amount = amount;
              mainscreen.items.clear();
                  //  for(int spawned = 0; spawned <= amount; spawned++){

                        timer.schedule(new Timer.Task() {

                            @Override
                            public void run() {
                                if (mainscreen.canclick == false) {
                                    Item item = new Item();
                                    item.x = 600;
                                    item.y = -42;
                                    item.speedx = -20;
                                    item.speedy = 0;
                                    Rectangle itemcontainer = new Rectangle();
                                    itemcontainer.x = item.x;
                                    itemcontainer.y = item.y;
                                    itemcontainer.width =                       mainscreen.container.getWidth() / 4f;
                                    itemcontainer.height = mainscreen.container.getHeight() - 15f;
                                    item.container = itemcontainer;
         item.itemtype = MathUtils.random(1, 10);
item.setTexture(item.itemtype);
                                    mainscreen.items.add(item);
                                    spawned++;
                                }
                                for (Item item : mainscreen.items) {
                                    if (item.x <= -4000) {
                                        if (spawned >= Item.amount) {
                                            mainscreen.canclick = true;

                                            timer.stop();
                                            spawned = 0;
                                        }

                                    } else {

                                    }
                                }
                           }
                        }, 0, 0.325f);

                }
    public void dispose(){
        texture.dispose();
    }
            }

Mainscreen class:

public class mainscreen implements Screen, GestureDetector.GestureListener,InputProcessor {
    @Override
    public void render(float delta) {
        this.delta = delta;
        Gdx.gl.glClearColor(115 / 255F, 115 / 255F, 115 / 255F, 1 / 255F);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(camera.combined);

      if(Gdx.input.justTouched()) {

          Vector3 touch1 = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
          camera.unproject(touch1);

          if (debug.contains(touch1.x, touch1.y)) {
              items.clear();
          }

          if (start.contains(touch1.x, touch1.y)) {
          if (canclick == true) {

                  canclick = false;

    Item.spawnItem(20);
              }

          }
      }

}

LOG:
On first click start:
(After the Timer has finished)

canclick: true
items list: [com.abc.luckyllama.Item@37237aa0, com.abc.luckyllama.Item@2de938e3, com.abc.luckyllama.Item@3cb912d5, com.abc.luckyllama.Item@2bae592c, com.abc.luckyllama.Item@774c083, com.abc.luckyllama.Item@633edeae, com.abc.luckyllama.Item@176557a6, com.abc.luckyllama.Item@4edb1b5f, com.abc.luckyllama.Item@6f8abadf, com.abc.luckyllama.Item@7a54d22e, com.abc.luckyllama.Item@473162a5, com.abc.luckyllama.Item@51a698ff, com.abc.luckyllama.Item@6bc08c56, com.abc.luckyllama.Item@37d9e6a2, com.abc.luckyllama.Item@7bb19eb6, com.abc.luckyllama.Item@1eb5805f, com.abc.luckyllama.Item@71780de3, com.abc.luckyllama.Item@9ec0998, com.abc.luckyllama.Item@7edf723d, com.abc.luckyllama.Item@4c5aa2c1]

After clicking the debug button(clears arraylist):

canclick: true
items list: []

After clicking the start button again:
(After the Timer has finished)

 canclick: true
items list: [com.abc.luckyllama.Item@7d7cb9bc, com.abc.luckyllama.Item@1435cf42, com.abc.luckyllama.Item@117e1963, com.abc.luckyllama.Item@82bfd27, com.abc.luckyllama.Item@108214c7, com.abc.luckyllama.Item@2a77864a, com.abc.luckyllama.Item@4b232766, com.abc.luckyllama.Item@1cb629e0, com.abc.luckyllama.Item@1c92229d, com.abc.luckyllama.Item@ac1b293, com.abc.luckyllama.Item@588bbcba, com.abc.luckyllama.Item@75df6762, com.abc.luckyllama.Item@78d4358e, com.abc.luckyllama.Item@7f86452d, com.abc.luckyllama.Item@7aed480b, com.abc.luckyllama.Item@7407d443, com.abc.luckyllama.Item@2da6e708, com.abc.luckyllama.Item@604470bc, com.abc.luckyllama.Item@70f9d1af, com.abc.luckyllama.Item@3a16a63f, com.abc.luckyllama.Item@201288d2, com.abc.luckyllama.Item@6310ddfc, com.abc.luckyllama.Item@5d5a1c98, com.abc.luckyllama.Item@52727e52, com.abc.luckyllama.Item@669228d6]

You see that the Items inside the ArrayList didn't get cleared. It increased. I think that's because the instances of Item created in spawnItem() are still there. How do I fix this?

I noticed that every time I click the button there aren't more items. The items are spawned faster. But how to stop this?


ExpressJS API router.get external function

I am trying to hack together two separate examples, I have them working separately but I can't wrap my head around how to combine them. I have now wasted multiple hours getting something so basic to work.

I have ExpressJS running an API. The test message works.

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'This is a test message' });
});

I want to show the output of the the below, instead of the message: This is a test message

serverClient.call('version', {}, function (err, res) {
    console.log('Server Version: %j', res.version);
});

Can anyone point me in the right direction with a clear how to option or show me the code?


problem with wpf command not executing when button clicked

I have the following xaml in a wpf application.  I would like to bind the button to an ICommand in a view model.  For some reason, I am not able to see the command from my view.
this is in a user control.

<Grid>
<Grid.DataContext>
        <Binding
            x:Name="SettingsData"
            Path="Data" />
    </Grid.DataContext>
.
.
.
<DockPanel Grid.Column="1">
            <Button x:Name="SaveButton"
                    DockPanel.Dock="Top"
                    Height="25"
                    HorizontalAlignment="Left"
                    Margin="70 0 0 0"
                    Command="{Binding Path=SaveData}"

                    >Save Changes</Button>
        </DockPanel>
</Grid>

Here is my ICommand object -

public ICommand SaveData
        {
            get
            {
                if (_saveData == null)
                {
                    _saveData = new RelayCommand(
                        param => this.saveData(),
                        param => true
                        );
                }
                return _saveData ;
            }
        }

Does anyone have any idea why I cannot bind to this command?

Thanks for any thoughts....


jQuery slider navigation gets off sync on click

I have a basic jQuery slider. The slides automatically rotate. There is also a navigation that users can click to go to a different slide. For example, if there are three slides than three circles appear for the navigation. The user can click each individual circle to go to a different slide. If the circle's associated slide is active than the circle will be filled in.

Right now, the slides are working on a timer. Every three seconds a new slide appears. The navigation will also change with each new slide to show which slide is active.

The problem is that when a user clicks any of the navigation items, the navigation gets off sync with the slides.

HTML:

  <div class="home-hero">
    <div class="hero-slide-holder">
      <div class="slide1">
        <div class="text-slide"></div>
        <p></p>
      </div>
      <div class="slide2">
        <div class="text-slide"></div>
        <p></p>
      </div>
      <div class="slide3">
        <div class="text-slide"></div>
        <p></p>
      </div>
      <div class="slide4">
        <div class="text-slide"></div>
        <p></p>
      </div>
    </div>
    <div class="hero-nav">
      <div class="active"></div>
      <div class=""></div>
      <div class=""></div>
      <div class=""></div>
    </div>
  </div>

jQuery:

$('.hero-nav div').click(function() {
    $('.hero-nav div').removeClass('active');
    $(this).addClass('active');
    $('.home-hero div[class^="slide"], .portfolio-hero div[class^="slide"]').hide();
    if ($(this).is(':nth-child(1)')) {
        $('.slide1').css('display', 'flex');
    } else if ($(this).is(':nth-child(2)')) {
        $('.slide2').css('display', 'flex');
    } else if ($(this).is(':nth-child(3)')) {
        $('.slide3').css('display', 'flex');
    } else if ($(this).is(':nth-child(4)')) {
        $('.slide4').css('display', 'flex');
    } else {
        $('.slide5').css('display', 'flex');
    }
});

var toggleSlide = function(){
  $(".hero-nav .active").removeClass().next().add(".hero-nav div:first").last().addClass("active");
  $('.hero-slide-holder > div:first').fadeOut(1000).next().css('display', 'flex').fadeIn(1000).end().appendTo('.hero-slide-holder');
}
setInterval(toggleSlide, 3000);


how to scale img by percentage of self and not percentage of its container?

I can't believe I never ran into this problem before, so I'm guessing either the standard changed, or I am doing something wrong, because I am pretty sure that back in the day, before CSS even, it was possible to scale an image like this

<img src="something.jpg" height="50%" width="50%">

but now that scales it by the container objects size, which is totally irrelevant to me.

IS there no other way than for me to start calculating pixels and such in a javascript to achieve this very simple image styling?

If I have an image 500px wide, and the user selects 50%, I want that image to show up 250px wide, I don't care one bit about the size of its container at this moment...


Android MediaRecorder stop() not being called

I have this really weird bug where some of my code is not being called, but doesn't look there is any reason why it wouldn't be called.

onFinishedRecording gets called and the tag "Finished recording." gets logged out, but the code after that does not get called at all. All the code stops being called when mMediaRecorder.stop(); is called. It also does not go into the catch block either. Why is this happening?

I thought it might have to do with different threads, but I checked all the thread names and they are all running on the same main thread.

Also, could there be something wrong with my camera preview setup? When I try to play the video back, it is corrupted and not able to playback.

In addition to the above problems, my back button doesn't do anything in the application. Not quite show why or how it is related to the code that I have implemented.

MyLibrary class (library module class)

public class MyLibrary implements PreciseCountdownTimer.PreciseCountdownTimerCallback {

    private static final String TAG = AngryOtter.class.getSimpleName();
    private static final long MAX_RECORD_TIME_MILLIS = 3000;
    private static final long INTERVAL_MILLIS = 1000;

    private static MyLibrary mInstance;

    private Activity mActivity;
    private CameraInitListener mCallback;

    private int mCameraId = -1;
    private Camera mCamera;
    private SurfaceView mCameraPreview;
    private MediaRecorder mMediaRecorder;
    private PreciseCountdownTimer mTimer;
    private File mTempVideoFile;

    public static MyLibrary getInstance() {
        if (mInstance == null) {
            mInstance = new MyLibrary();
        }
        return mInstance;
    }

    // Call this in onResume of the activity
    public void initialize(Activity activity) {
        mActivity = activity;

        try {
            mCallback = (CameraInitListener) mActivity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.getClass().getSimpleName()
                    + " must implement CameraInitListener");
        }

        if (ViewUtil.checkValidRootView(mActivity)) {
            PermissionUtil.requestPermissions(mActivity);
            prepareCamera();
            if (mCamera == null) {
                return;
            }
            addCameraPreview();
        }
    }

    // Call this in onPause of the activity
    public void release() {
        releaseMediaRecorder();
        releaseCamera();
        removeCameraPreview();
        releaseTimer();
    }

    public void startRecording() {
        if (checkPermissions()) {
            try {
                mMediaRecorder.start();
                mTimer.start();
                Log.d(TAG, "Recording started.");
            } catch (IllegalStateException e) {
                releaseMediaRecorder();
                releaseTimer();
            }
        } else {
            releaseMediaRecorder();
        }
    }

    public void stopRecording() {
        onFinishedRecording();
    }

    @Override
    public void onPreciseTimerTick(long remainingTime) {
        Log.d(TAG, "TICK: " + String.valueOf(remainingTime));
    }

    @Override
    public void onPreciseTimerFinished() {
        Log.d(TAG, "Timer Finished.");
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                onFinishedRecording();
            }
        });
    }

    private boolean checkPermissions() {
        if (PermissionUtil.checkCameraPermission(mActivity)
                && PermissionUtil.checkRecordAudioPermission(mActivity)
                && PermissionUtil.checkWriteExternalStoragePermission(mActivity)) {
            return true;
        } else {
            return false;
        }
    }

    private void prepareCamera() {
        mCameraId = CameraUtil.getFrontCameraId();
        if (mCameraId != -1) {
            try {
                Log.d(TAG, "Initializing front camera.");
                mCamera = Camera.open(mCameraId);
            } catch (Exception e) {
                Log.e(TAG, "Error initializing front camera: " + e.getMessage());
                mCamera = null;
            }
        } else {
            mCamera = null;
        }
    }

    private void releaseCamera() {
        if (mCamera != null){
            Log.d(TAG, "Releasing camera.");
            mCamera.release();
            mCamera = null;
        }
    }

    private void addCameraPreview() {
        mCameraPreview = new SurfaceView(mActivity);
        mCameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d(TAG, "Preview surface created.");
                try {
                    Log.d(TAG, "Setting preview display.");
                    mCamera.setPreviewDisplay(holder);
                    mCamera.startPreview();
                    onPreviewDisplaySet();
                } catch (IOException e) {
                    Log.e(TAG, "Error setting camera preview: " + e.getMessage());
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d(TAG, "Preview surface changed.");
                // If your preview can change or rotate, take care of those events here.
                // Make sure to stop the preview before resizing or reformatting it.

                if (mCameraPreview.getHolder().getSurface() == null) {
                    // preview surface does not exist
                    return;
                }

                // stop preview before making changes
                try {
                    mCamera.stopPreview();
                } catch (Exception e){
                    // ignore: tried to stop a non-existent preview
                }

                // Adjust orientation
                final int rotation = CameraUtil.getAdjustedDisplayOrientation(mActivity, mCameraId);
                mCamera.setDisplayOrientation(rotation);

                // set preview size and make any resize, rotate or
                // reformatting changes here

                // start preview with new settings
                try {
                    mCamera.setPreviewDisplay(mCameraPreview.getHolder());
                    mCamera.startPreview();
                } catch (Exception e){
                    Log.d(TAG, "Error starting camera preview: " + e.getMessage());
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.d(TAG, "Preview surface destroyed.");
            }
        });
        mCameraPreview.setLayoutParams(new FrameLayout.LayoutParams(100, 100, Gravity.TOP|Gravity.RIGHT));
        mCameraPreview.setBackgroundColor(ContextCompat.getColor(mActivity, android.R.color.holo_red_dark));

        final WindowManager windowManager =
                (WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE);
        final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, 0, PixelFormat.UNKNOWN);
        windowManager.addView(mCameraPreview, layoutParams);
    }

    private void removeCameraPreview() {
        if (mCameraPreview != null) {
            final ViewGroup rootView = ViewUtil.getRootView(mActivity);
            rootView.removeView(mCameraPreview);
        }
    }

    private void onPreviewDisplaySet() {
        createTempVideoFile();

        prepareMediaRecorder();
        if (mMediaRecorder == null) {
            return;
        }

        prepareTimer();
        mCallback.onCameraInitialized();
    }

    private void createTempVideoFile() {
        mTempVideoFile = FileUtil.getTempVideoFile(mActivity);
    }

    private void prepareMediaRecorder() {
        if (mCamera != null) {
            mCamera.unlock();
        }

        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setCamera(mCamera);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setProfile(CamcorderProfile.get(mCameraId, CamcorderProfile.QUALITY_HIGH));
        mMediaRecorder.setOutputFile(mTempVideoFile.getAbsolutePath());
        mMediaRecorder.setPreviewDisplay(mCameraPreview.getHolder().getSurface());
//        mMediaRecorder.setOrientationHint(90);

        try {
            Log.d(TAG, "Preparing media recorder.");
            mMediaRecorder.prepare();
        } catch (IllegalStateException|IOException e) {
            Log.e(TAG, "Error preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
        }
    }

    private void releaseMediaRecorder() {
        if (mMediaRecorder != null) {
            Log.d(TAG, "Releasing media recorder.");
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }

        if (mCamera != null) {
            mCamera.lock();
        }
    }

    private void prepareTimer() {
        mTimer = new PreciseCountdownTimer(MAX_RECORD_TIME_MILLIS, INTERVAL_MILLIS, this);
    }

    private void releaseTimer() {
        if (mTimer != null) {
            Log.d(TAG, "Stopping timer.");
            mTimer.stop();
        }
    }

    private void onFinishedRecording() {
        Log.d(TAG, "Finished recording.");
        try {
            mMediaRecorder.stop();
            Log.d(TAG, "Media recorder stopped.");
        } catch (Exception e) {
            e.printStackTrace();
        }

        releaseMediaRecorder();
        releaseTimer();
        getSignedUrl();
    }

    private void getSignedUrl() {
        new GcpSigningRequest(new NetworkCallback<String>() {
            @Override
            public void onSuccess(String response) {
                uploadVideo(response);
            }

            @Override
            public void onError() {
                Log.e(TAG, "Error getting signing request.");
            }
        }).addToQueue();
    }

    private void uploadVideo(String signedUrl) {
        new UploadToGoogleRequest(signedUrl, mTempVideoFile.getName(),
                Uri.parse(mTempVideoFile.getAbsolutePath()), new NetworkCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean response) {

            }

            @Override
            public void onError() {

            }
        }).addToQueue();
    }
}

RecordActivity

public class RecordActivity extends AppCompatActivity implements
        CameraInitListener {

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

    @Override
    protected void onResume() {
        super.onResume();
        MyLibrary.getInstance().initialize(this);
    }

    @Override
    protected void onPause() {
        MyLibrary.getInstance().release();
        super.onPause();
    }

    @Override
    public void onCameraInitialized() {
        MyLibrary.getInstance().startRecording();
    }
}

So everything works fine until this method is called:

    private void onFinishedRecording() {
        Log.d(TAG, "Finished recording.");
        try {
            mMediaRecorder.stop();
            Log.d(TAG, "Media recorder stopped.");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

        releaseMediaRecorder();
        releaseTimer();
        getSignedUrl();
    }

Full Phone Stacktrace

08-15 21:17:46.735 24660-24660/com.walintukai.heatmapdemo I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
08-15 21:17:46.735 24660-24660/com.walintukai.heatmapdemo W/dalvikvm: VFY: unable to resolve virtual method 690: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
08-15 21:17:46.735 24660-24660/com.walintukai.heatmapdemo D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
08-15 21:17:46.735 24660-24660/com.walintukai.heatmapdemo I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
08-15 21:17:46.735 24660-24660/com.walintukai.heatmapdemo W/dalvikvm: VFY: unable to resolve virtual method 692: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
08-15 21:17:46.735 24660-24660/com.walintukai.heatmapdemo D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
08-15 21:17:46.785 933-11266/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:46.785 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:46.785 731-2931/? E/EnterpriseContainerManager: ContainerPolicy Service is not yet ready!!!
08-15 21:17:46.785 731-2931/? D/EnterpriseDeviceManager: ContainerId: 0
08-15 21:17:46.785 731-2931/? W/LicenseLogService: log() failed
08-15 21:17:46.805 170-170/? E/SMD: DCD ON
08-15 21:17:46.865 933-11213/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:46.865 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:46.935 380-24718/? E/mm-camera: color_correct_apply_gain: cc_gain_adj 1.000, digital_gain_brightness 1.000 dig_gain = 1.000
08-15 21:17:47.055 731-24783/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1509 com.android.server.InputMethodManagerService$4.run:2683 java.lang.Thread.run:841 <bottom of call stack> <bottom of call stack>
08-15 21:17:47.145 174-234/? E/qdmemalloc: heap_msk=3000000 flags=1

08-15 21:17:47.165 174-234/? E/qdmemalloc: heap_msk=40000000 flags=1

08-15 21:17:47.185 933-10839/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.185 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.225 933-947/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.245 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.265 933-10842/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.275 174-940/? E/qdmemalloc: heap_msk=3000000 flags=1

08-15 21:17:47.275 174-940/? E/qdmemalloc: heap_msk=40000000 flags=1

08-15 21:17:47.285 24660-24660/com.walintukai.heatmapdemo D/RecordingService: Tick: 2000
08-15 21:17:47.295 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.305 179-24742/? W/CameraSource: Timed out waiting for incoming camera video frames: 0 us
08-15 21:17:47.375 933-11213/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.375 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.506 933-953/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.506 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.666 731-838/? D/PackageManager: [MSG] CHECK_PENDING_VERIFICATION
08-15 21:17:47.766 179-460/? D/AudioStreamOutALSA: standby
08-15 21:17:47.766 179-460/? D/ALSAModule: s_standby: handle 0xb7c24650 h 0x0
08-15 21:17:47.766 179-460/? E/ALSAModule: s_standby handle h 0xb7ceb678
08-15 21:17:47.836 933-6432/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.846 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.846 174-234/? I/SurfaceFlinger: id=833 Removed ieatmapdemo (12/17)
08-15 21:17:47.846 174-940/? I/SurfaceFlinger: id=833 Removed ieatmapdemo (-2/17)
08-15 21:17:47.896 933-11464/? D/KeyguardUpdateMonitor: sendKeyguardVisibilityChanged(true)
08-15 21:17:47.906 933-933/? D/KeyguardUpdateMonitor: handleKeyguardVisibilityChanged(1)
08-15 21:17:47.956 179-460/? D/ALSAModule: checkRunningHandle return false
08-15 21:17:47.956 179-460/? D/alsa_ucm: snd_use_case_set(): uc_mgr 0xb7bf62a0 identifier _verb value Inactive
08-15 21:17:47.956 179-460/? D/alsa_ucm: Set mixer controls for HiFi enable 0
08-15 21:17:47.956 179-460/? D/alsa_ucm: Setting mixer control: PRI_RX Audio Mixer MultiMedia1, value: 0
08-15 21:17:47.956 179-460/? E/ALSAModule: Number of modifiers 1
08-15 21:17:47.956 179-460/? E/ALSAModule: index 0 modifier Capture Music
08-15 21:17:47.956 179-460/? E/ALSAModule: use case is Capture Music
08-15 21:17:47.956 179-460/? E/ALSAModule: usecase_type is 2
08-15 21:17:47.956 179-460/? D/alsa_ucm: snd_use_case_set(): uc_mgr 0xb7bf62a0 identifier _disdev value Speaker
08-15 21:17:47.956 179-460/? D/alsa_ucm: Set mixer controls for Speaker enable 0
08-15 21:17:47.956 179-460/? D/alsa_ucm: Setting mixer control: RX5 MIX1 INP1, value: ZERO
08-15 21:17:47.966 179-460/? D/alsa_ucm: Setting mixer control: RX5 MIX1 INP2, value: ZERO
08-15 21:17:47.966 179-460/? D/alsa_ucm: Setting mixer control: LINEOUT2 Volume, value: 0
08-15 21:17:47.966 179-460/? D/alsa_ucm: Setting mixer control: LINEOUT4 Volume, value: 0
08-15 21:17:47.966 179-460/? D/alsa_ucm: Setting mixer control: RX5 Digital Volume, value: 0
08-15 21:17:48.286 24660-24660/com.walintukai.heatmapdemo D/RecordingService: Tick: 1000
08-15 21:17:48.296 731-824/? D/SensorService:   0.2 -0.0 11.0
08-15 21:17:48.647 731-824/? E/Sensors: accelHandler 0.162861 -0.044308 11.044633
08-15 21:17:48.727 179-24722/? E/mm-camera: poll type 1 returns 0
08-15 21:17:48.727 179-24723/? E/mm-camera: poll type 1 returns 0
08-15 21:17:48.727 179-24721/? E/mm-camera: poll type 1 returns 0
08-15 21:17:49.297 24660-24660/com.walintukai.heatmapdemo D/RecordingService: Tick: 0
08-15 21:17:49.297 24660-24660/com.walintukai.heatmapdemo D/RecordingService: Timer Finished
08-15 21:17:49.297 24660-24660/com.walintukai.heatmapdemo D/RecordingService: Finished recording
08-15 21:17:49.297 179-20689/? D/MPEG4Writer: Stopping Video track
08-15 21:17:49.808 170-170/? E/SMD: DCD ON
08-15 21:17:50.309 179-24742/? W/CameraSource: Timed out waiting for incoming camera video frames: 0 us
08-15 21:17:51.440 179-24720/? E/mm-camera: poll type 1 returns 0
08-15 21:17:51.570 179-24724/? E/mm-camera: poll type 0 returns 0
08-15 21:17:51.800 731-824/? D/SensorService:   0.2 -0.0 11.1
08-15 21:17:52.111 731-856/? V/AlarmManager: waitForAlarm result :4
08-15 21:17:52.121 731-856/? V/AlarmManager: trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP
08-15 21:17:52.151 731-824/? E/Sensors: accelHandler 0.129331 -0.021555 11.078163
08-15 21:17:52.151 19505-24874/? I/Finsky: [3562] com.google.android.finsky.receivers.FlushLogsReceiver$FlushLogsService.onHandleIntent(163): Flushing event logs for [wwRg65ZPhINg_7-olzSHzcWExtM]
08-15 21:17:52.161 19505-19520/? I/PlayCommon: [3510] com.google.android.play.a.al.e(730): Preparing logs for uploading
08-15 21:17:52.161 19505-20595/? I/PlayCommon: [3552] com.google.android.play.a.w.a(27553): Starting to flush logs
08-15 21:17:52.161 19505-20595/? I/PlayCommon: [3552] com.google.android.play.a.w.a(27564): Log flushed by 0 successful uploads
08-15 21:17:52.201 1184-1184/? I/Auth: [AuthDelegateWrapper] Service intent: Intent { cmp=com.google.android.gms/.auth.account.authenticator.DefaultAuthDelegateService }.
08-15 21:17:52.201 1184-1184/? I/Auth: [AuthDelegateWrapper] Service intent: Intent { cmp=com.google.android.gms/.auth.account.authenticator.DefaultAuthDelegateService }.
08-15 21:17:52.261 19505-19520/? I/PlayCommon: [3510] com.google.android.play.a.al.a(870): Connecting to server: https://play.googleapis.com/play/log?format=raw&proto_v2=true
08-15 21:17:52.441 731-826/? W/ProcessCpuTracker: Skipping unknown process pid 24877
08-15 21:17:52.451 731-826/? W/ProcessCpuTracker: Skipping unknown process pid 24879
08-15 21:17:52.451 731-826/? W/ProcessCpuTracker: Skipping unknown process pid 24880


State transition not persisited in database in integration test using Capybara on a Ruby on Rails project

I am using state_machine gem -- https://github.com/pluginaweek/state_machine

In my TEST ENVIRONMENT WITH CAPYBARA I am executing

order.good_data!

good_data in an event defined in my state machine.

state_machine :initial => :new, :use_transactions => false do

  event :good_data do
    transition [:new] => :sane
  end

end

When I check the order in my db it is still in new state.

It is working properly in my production and development environments.


I am writing the code using cocos2d.
I want to release all the memory I allocated. I have done it in dealloc method in the following way.

 All the objects I released are declared in interface file and property (assign) was set and are synthesized in implementation file.

I used alloc method to create them like

self.PlayerA = [[CCSprite alloc] initWithFile:@" PlayerImage_01.png"];

-(void)dealloc
{
 int count , i ;

 count = [self.PlayerA retainCount];
 for(i = 0; i < count; i++)
   [self.PlayerA release];

 count = [self.targetLayer retainCount];
 for(i = 0; i < count; i++)
   [self.targetLayer release];

  count = [self.playerGunSlowDrawSheet retainCount];
 for(i = 0; i < count; i++)
    [self.playerGunSlowDrawSheet release];

 count = [self.playerGunSlowDrawAnimation retainCount];
 for(i = 0; i < count; i++)
    [self.playerGunSlowDrawAnimation release];

 count = [self.numberFinishedTime retainCount];
 for(i = 0; i < count; i++)
    [self.numberFinishedTime release];

 count = [self.backGroundImage retainCount];
 for(i = 0; i < count; i++)
   [self.backGroundImage release];

 [[CCTextureCache sharedTextureCache] removeAllTextures];
 [[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFrames];

 [super dealloc];
 }

But I am getting: Program received signal: “EXC_BAD_ACCESS”.
I debugger it is showing the error at [super dealloc];

Am I totally wrong in the memory management ? Or am I missing anything in this.
Thank you.


JQuery: Change URL param without reloading?

I have a question, is it possible to change the URL via JQuery under the following conditions:

Same URL will load on browser back and on reloads

Page doesn't reload when you change the parameter


SyntaxError if executed with cron, OK if manually

I'm trying to schedule a script with cron in kubuntu. If I execute the script manually line by line, it goes just fine, but scheduled with cron it raises the following SyntaxError:

  File "/opt/django/myproject/myapp/cron/test.sh", line 4
    python manage.py mycustomcommand
                ^
SyntaxError: invalid syntax

The content of the script test.sh is as following:

#!/bin/bash
source /opt/virtualenvs/myvirtualenv/bin/activate
cd /opt/django/myproject
python manage.py mycustomcommand

Basically the script activates a virtual enviroment where django is installed, then accesses to my project path, and then executes a custom django command. As said, this works fine if I do it manually.

I tried to schedule the script in cron with normal and root permissions also ("crontab -e" and "sudo crontab -e")

Any idea? Thanks!


How to select string between two periods (SQL Server 2012)

Let's say I have a bunch of part numbers, and I want a column to return the string after the first period and before the second period.  I looked at other similar questions but couldn't figure it out

So let's say I have of list of part numbers such as:

10416.1.1.4
10416.1.1.7
10416.1.1.1
10416.2.3
10416.2.2
10416.3.1.2
10416.3.1.3
10416.4.1.1
10416.10.1
10416.10.2
10416.11.1.1

I should have my column return:

1
1
1
2
2
3
3
4
10
10
11

Using SQL Server 2012, thanks in advance

Edit: Here's my code, this returns a table but the sorting is all over the place, the PartNo column is what I'm trying to split

SELECT DISTINCT OrderDet.OrderNo, Scheduling.JobNo, OrderDet.PartNo,
OrderDet.Priority
FROM Scheduling LEFT JOIN OrderDet ON Scheduling.JobNo = OrderDet.JobNo
WHERE Scheduling.WorkCntr = 'Glazing'
ORDER BY OrderDet.Priority DESC


html entities not displaying properly

I made a function for my website that converts special characters, in case someone will try to break out the system using colon, semicolons, single quotes or double quotes. I made an array of find which is the find variable in str_replace and change which will be exchanged.

$find = array('"','\'','<3');
$change = array('&quot;','&apos;','&hearts;');
$str = "This is a test ' " <3.";

$str = str_replace($find, $change, $str);
echo $str;

It literally prints the codes like &quot and supposedly it should be echoed as double quotes ("). I refreshed the page. It is still echoing the actual code.

Any help?


React.createElement: type is invalid in simple empty app

Still struggle to just simple run simple react application (just client to play around with).

Build is ok (you can see config here, previous question )

When I run server - there is an error on client side:

Uncaught Error: Element type is invalid: expected a
  string (for built-in components) or a class/function (for composite
  components) but got: object. You likely forgot to export your
  component from the file it's defined in.

at invariant (transformed.js:304)
at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (transformed.js:11912)
at ReactCompositeComponentWrapper.performInitialMount (transformed.js:27510)
at ReactCompositeComponentWrapper.mountComponent (transformed.js:27401)
at Object.mountComponent (transformed.js:4158)
at mountComponentIntoNode (transformed.js:12676)
at ReactReconcileTransaction.perform (transformed.js:5756)
at batchedMountComponentIntoNode (transformed.js:12698)
at ReactDefaultBatchingStrategyTransaction.perform (transformed.js:5756)
at Object.batchedUpdates (transformed.js:29031)

Here is the code:

index.js

var React = require('react');
var ReactDOM = require('react-dom');
var App = require('./components/App.js');

ReactDOM.render(
    <App />,
    document.getElementById('app')
);

index.html

<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
    </head>
    <body>
        <div id='app'></div>
    </body>
</html>

App.js:

import React from 'react';
import ReactDOM from 'react-dom';
// import {render} from 'react-dom'; //didn't helped either

class App extends React.Component {
  render () {
    return (
      <div>
        <p> Hello React!</p>
      </div>
    );
  }
}

FYI:

Answer is correct, but also one thing.
Don't forget to change all require on import, like here (in index.js):

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';


Is there a Python library that allows to build user interfaces without writing much code?

I am writing editing front ends in Python since several years now, and I am fed up with micromanaging every UI detail of a window or dialog every single time.

Is there a technology that allows me to, say, specify the relations between a GTK+ Glade-designed interface and the tables and records of an SQLite database to do all the middle man work? It should spare me the work of manually writing event handlers, input evaluators and view updates.

The technologies in question are just examples, but I want to stick with Python as far as possible.


Where are the docs on how to add symbol support for a language to Visual Studio Code?

I would like to add symbol support for PowerShell to VS Code but I'm not finding any docs on the code.visualstudio.com/docs site.

Also, is it possible to do this for a language like PowerShell that, for the moment, will only work on Windows?  Is there a way to light up symbol support on Windows only?

BTW I've added a bunch of PowerShell snippets that I'm in the process of trying to get integrated into VS Code. Any help on how to get these snippets into the product would be appreciated as well?  I did submit an issue on the snippets, suggesting that the team put these into VS Code.


iOS check if a UILocalNotification condition occurs

I read a lot of documentation and code about UILocalNotification. My alert occurs when the condition (a calculated value raise) a limit.

With localNotification.repeatInterval = NSHoursCalendarUnit

My Notification is resent every hours. How can I ask LocalNotificationCenter to make a calculation BEFORE sending (or not) the notification?

For exemple:

Value == 1 -> Notification, Value is one.

Every hours recalculate Value if Value changed -> Notification, value is changed

Thanks in advance for your help,
Jacques


session value not updated within while loop in JOOMLA

I'm not very sure if this is Joomla or PHP issue in my code. Basically I've two functions, A and B that invoked on page load and onclick event respectively.
On page load, I set session value to loadA. Once click event triggered, I set session value to clickB.

Meanwhile the while loop inside function is running until the condition is met. Inside the loop, it's checking for session value. So if the value updated inside function B, it should also be updated in function A when the while loop check right?

But it's not giving the updated value. Function A still gives loadA as session value inside while loop even after click event took place. How to fix this please?

class XXY(){

        public function A()
        {

            $session = JFactory::getSession();
            //set session value on page laod
            $this->setSession('loadA');
            while (x == y)
            {
              usleep(10000);
              clearstatcache();
              $comet = $session->get('runningComet');//giving the first set value, loadA
              if($comet !== 'loadA'){
                break;
              }
            }

        }

        public function B()
        {
            $session = JFactory::getSession();

            $this->setSession('loadB');
            $comet = $session->get( 'runningComet');//giving the updated value, loadB
        }

        public function setSession($currentComet){

        $session = JFactory::getSession();
        $session->set('runningComet', $currentComet);
        }
    }


oAuth2 integration with codeigniter

I am new to codeigniter and i want to implement oAuth2 authentication in codeigniter. Please suggest me the steps to do this. Please guide me proper steps so that this would be helpful for me to implement.
Thanks.


Formatting timestamps to avoid R/TraMineR crash?

I have a sequence dataset where the timestamp is in seconds since the epoch:

id      event       time        end
1  723     opened 1356963741 1356963741
2  722     opened 1356931342 1356931342
3  721 referenced 1356988206 1356988206
4  721 referenced 1356988186 1356988186
5  721     closed 1356988186 1356988186
6  721     merged 1356988186 1356988186
7  721     closed 1356988186 1356988186
8  721     merged 1356988186 1356988186
9  721  discussed 1356966433 1356966433
10 721  discussed 1356963870 1356963870

I want to create an STS sequence object:

sequences.sts <- seqformat(data, from="SPELL", to="STS",
     begin="time", end="end", id="id", status="event", limit=slmax)
sequences.sts <- seqdef(sequences.sts)
summary(sequences.sts)

However, when I do this, RStudio crashes, and more or less freeze up my entire computer. Through comparing with other code, which runs fine, that uses single-digit numbers for the "time" column, I think I have identified the problem as being the timestamp. Could it be that R/RStudio/TraMineR simply gets overloaded from the long timestamp?


Custom nested cols in Bootstrap 3

I got a tough requirement to make a layout like this image with Bootstrap 3:

Currently I can make it like this:

Here is my sample html layout: https://jsfiddle.net/isherwood/4etczrwx/

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="container">

    <div class="row">

        <div class="col-sm-6" style="height:500px;background-color:red;">
            images
        </div>

        <div class="clearfix col-sm-6"  style="height:100px;background-color:yellow;">
            text dsgsg sdg sdgsdgtext dsgsg sdg sdgsdgtext dsgsg sdg sdgsdgtext dsgsg sdg sdgsdg
            text dsgsg sdg sdgsdgtext dsgsg sdg sdgsdgtext dsgsg sdg sdgsdgtext dsgsg sdg sdgsdg
            text dsgsg sdg sdgsdgtext dsgsg sdg sdgsdgtext dsgsg sdg sdgsdgtext dsgsg sdg sdgsdg
        </div>

        <div class="col-sm-3" style="height:200px;background-color:blue;">
            keyfeature
            <ul>
                <li>testest 1</li>
                <li>testest 2</li>
                <li>testest 3</li>
                <li>testest 4</li>
            </ul>
        </div>

        <div class="col-sm-3" style="height:600px;background-color:gray;">
            Price tab here
        </div>

        <div class="col-sm-9" style="height:800px;background-color:green;">
            Configurator here
        </div>
    </div>
</div>

I think I'am missing something to make the green col?

or should I use push/pull to make it work as my expectation?


hmm, lists, tuples, arrays, sets or dicts for this data structure?

Beginner programmer here. after a bunch of reading about 'variables' which dont exist in python, (still dont get that) Ive come to the opinion that I think I should be using lists in my data structure, but im not entirely sure.

im analysing a string which contains commands and normal words to be printed out, if the word is a command, which in this case is preceded by an '@' i want it to be in a separate list to the actual words. i will then process all this to be printed out afterwards, but i want the list to be ordered, so i can go through each element and test if it has a word in it, and if not do some action on the command.

so what i want really is a list with two indices(thankyou!) (what do you call that ?)
like this:

arglist[x][y]

so i can go through arglist and process whether or not it contains a command or a word to be printed out. i want arglist[x] to contain words and arglist[y] to contain commands.

arglist = [] # not sure how to initialise this properly.
doh="my @command string is this bunch of words @blah with some commands contained in it"
for listindex, word in enumerate(doh):
    if word.startswith('@'):
        # its a command
        arglist[listindex] = None
        arglist[listindex][listindex]=command
    else:
        # its a normal word
        arglist[listindex]=word
        rglist[listindex][listindex]=None

then i want to be able to go down the list and pick out commands,
i guess that would be something like this:

# get the number of items in the list and go through them...
for listindex, woo in enumerate(len(arglist)):
    if arglist[listindex] is None:
        # there is no word here, so print command
        print arglist[listindex][listindex]
        else:
            # just print out word
            print arglist[listindex]

so: my question is which data type/ structure should I be using and should I / how do I initialise it ? am I barking up the right tree here?

edit: i just found this gem and now im even more unsure - i want it to be the fastest lookup possible on my data but i still want it to be ordered.

dict and set are fundamentally different from lists and tuples`. They store the hash of their keys, allowing you to see if an item is in them very quickly, but requires the key be hashable. You don't get the same membership testing speed with linked lists or arrays.

many thanks as usual for any help.

edit: eg my string from above should look something like this.
doh="my @command string is this bunch of words @blah with some commands contained in it"

arglist[1] = 'my'
arglist[1][1] = None

arglist[2] = None
arglist[2][1] = command

arglist[3] = 'string'
arglist[3][1] = None

etc etc

this whole thing has left me a bit baffled i shall try and update this later.

EDIT: if anyone wanted to know what this was all about look here


Is it possible to set custom font & size for NSString?

I'm working with Swift in iOS 9. I want to customize the font for a UIAlertAction. I searched these questions for a Swift answer:

Change the Font of UIAlertAction in Swift

Is it possible to customize the font and appearance of a UIAlertController in the new XCode w/ iOS8?

And this question for an Objective-C answer:
UIAlertController custom font, size, color

But there was no solution for customizing the font for a UIAlertAction.

I believe the problem is that a UIAlertAction uses an NSString for its title property. See here:

https://github.com/nst/iOS-Runtime-Headers/blob/3dde29deb7000cfac59d3e5473a71557123f29ea/Frameworks/UIKit.framework/UIAlertAction.h

I would like to create a string like so:

let originalString: String = "OK"
let myString: NSString = originalString as NSString

And then customize the string's font & size. Then after adding my actions to the alert controller, assign the string to my actions using key-value coding:

alertController!.actions[0].setValue(myString, forKey: "title")

But as far as I can tell, there is no way to set a custom font and size for an NSString. If it used a UILabel instead, then it would be easy to customize the font. But I seem to be stuck with the limitations of strings. Does anyone know a way to assign a custom font & size to a string, or am I correct in believing there is no way to do this?


Django Rest Framework URL Mapping for multiple apps

I have a django-rest project called main and under it I have created an app called users. So, my project has the files :-

main/main/urls.py

and

main/users/urls.py

In users/urls.py I have

from django.conf.urls import url, include
from rest_framework import routers
from users import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

and in the main/main/urls.py I have

from django.conf.urls import url
from django.contrib import admin

from users import urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^users/', users.urls),
]

However, I keep getting the error NameError: name 'users' is not defined. What is the correct way to set up urls when I have multiple apps? I would like to have a urls.py file for each app that is independent of the project. And in the root urls.py would include routing to different apps.


Return xx characters before a certain string

So I have this string:

Best location using 168 cars + cleaning

The '168' is the part i'd like to extract from this string.

I have approximately 80 occurences of this string, all alternating from 'xx' cars to 'xxx' cars (so, 2 or 3 numbers). However, in each string, 'cars' comes after the number i'd like to return.

What would be the best way using PHP to achieve this?


I am attempting to print only a selected amount of Pi, it returns with an error of "Decimal has no attribute: __getitem__

def pi():
    prompt=">>> "
    print "\nWARNING: Pi may take some time to be calculated and may not always be correct beyond 100 digits."
    print "\nShow Pi to what digit?"
    n=raw_input(prompt)
    from decimal import Decimal, localcontext
    with localcontext() as ctx:
        ctx.prec = 10000
        pi = Decimal(0)
        for k in range(350):
            pi += (Decimal(4)/(Decimal(8)*k+1) - Decimal(2)/(Decimal(8)*k+4) - Decimal(1)/(Decimal(8)*k+5) - Decimal(1)/(Decimal(8)*k+6)) / Decimal(16)**k
    print pi[:int(n)]
pi()

Traceback (most recent call last):
  File "/Users/patrickcook/Documents/Pi", line 13, in <module>
    pi()
  File "/Users/patrickcook/Documents/Pi", line 12, in pi
    print pi[:int(n)]
TypeError: 'Decimal' object has no attribute '__getitem__'


Centering text in front of a horizontal rule

I'm looking to build a progress bar that I will generate programmatically. I'm a css novice, at best. Here is what I have so far; using tips from this question.

Ideally, I would style the following simple HTML, but I'm open to adding more tags:

<div id="container">
<h2><span>Goal</span></h2>
<div id="bgblock"></div>
    <h2><span>So Far</span></h2>
</div>

Two, maybe 3 issues:

Right now the "text over line" is accomplished by making the text white, on top of the line. This ends up cutting into the green background. To avoid this, I guess I need to have the text (without a background color) and lines on either side of it?

Obviously my formatting / margins / offsets are a mess, and the top of the box borders / hr alignment is not quite right (seems like the top text needs to be shifted up a couple pixels or the container down a couple pixels, but I'm having trouble doing this).

Thoughts on a cleaner solution that gets me where I want to be?


How to choose Build Configuration in Build Action in the Scheme dialog?

In Xcode 4 preview 5 every time I hit 'build', Xcode now build my Project with the debug Configuration, how can I build, for example, with release configuration? My project is a dynamic library, so scheme actions like 'Run', 'Test', 'Profile' and 'Analyze' not really make sense to me.

As of Xcode 4 preview 5 the 'Build' scheme action has changed.

Setting up a scheme with scheme actions that use particular build configurations allows me to set up a scheme that runs the product with the Debug configuration but profiles it with the Release configuration.

Every scheme action has a drop-down menu to choose a build configuration, except the build action. Where did this option go?


Java Errors Illegal Start of Expression

I'm getting errors that this has an illegal start of expression and it shows just about every line as being a problem. Any help with what I'm missing here?

public abstract class Shapes
{
public static void main(String[] args)
{
    protected final double pi=3.14;

    //varible pi is delcared as constant

     protected double radius;
     protected double height;

     public Shapes (double gRadius,double gHeight)
     {
        //sets radius, height variables to parameter values
        radius=gRadius;
        height=gHeight;
     }

          abstract public double getCircumference();
          abstract public double getTotalSurfaceArea();
          abstract public double getVolume();
}
}


Android: how can I lock SQLite database accessible with ContentProvider (or other way of executing atomic conditional operations)

I got two tables in my SQLite DB: entities and user_actions. Their approximate schemes:

The flow of the program is something like this (all DB accesses handled by ContentProvider):

The user performs some action which modifies one of the entities

The corresponding entity is updated in entities immediately. locally_modified value of this entity is set to 1

The information about user's action is stored in user_actions

At some point in future a sync session with the server is being initiated (I use SyncAdapter framework)

User's actions from user_actions are uploaded to the server one by one and removed from the DB in a background thread

When the uploading completed, I need to clear locally_modified flags in entities

At this point I encounter my atomicity issue: the synchronization with the server happens in a background thread, therefore the user can use the app and perform additional actions. As a consequence, right before I clear locally_modified flag for an entity, I must check that there are no records in user_actions corresponding to this entity. These three steps must be executed atomically for each entity having locally_modified set to 1:

Query user_actions for entries corresponding to entity's _id

Test whether the query from #1 returned an empty set

Clear locally_modified of that entity to 0

Given the above scenario, I have three questions:

Q1: Is there a way to lock SQLite DB accessed over ContentProvider in Android such that it can be accessed only by the locking thread?

Q2: If the answer to Q1 is positive, what happens if some other thread tries to access a locked DB? What precautions should I take to ensure reliable operation?

Q3: It is possible to execute atomic transactions with conditional logic using ContentProviderOperation? You can use "back-references" as described in this answer and this blog post to reference the result of a previous operations, but is there a way to use that result in some kind of if-else statement?

Thanks


When I run 'tensorflow-mnist-tutorial' and I got this: Expected int32, got list containing Tensors of type '_Message' instead

when I running the Tensorflow's official sample code: 'tensorflow-mnist-tutorial':

$python3 mnist_1.0_softmax.py

and something wrong:

Traceback (most recent call last):
  File "/Users/holmes/Desktop/untitled/gitRepository/tensorflow-mnist-tutorial/mnist_1.0_softmax.py", line 78, in <module>
    I = tensorflowvisu.tf_format_mnist_images(X, Y, Y_)  # assembles 10x10 images by default
  File "/Users/holmes/Desktop/untitled/gitRepository/tensorflow-mnist-tutorial/tensorflowvisu.py", line 42, in tf_format_mnist_images
    everything_incorrect_first = tf.concat(0, [incorrectly_recognised_indices, correctly_recognised_indices]) # images reordered with indeces of unrecognised images first
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 1047, in concat
    dtype=dtypes.int32).get_shape(
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 651, in convert_to_tensor
    as_ref=False)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 716, in internal_convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py", line 176, in _constant_tensor_conversion_function
    return constant(v, dtype=dtype, name=name)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py", line 165, in constant
    tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/tensor_util.py", line 367, in make_tensor_proto
    _AssertCompatible(values, dtype)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/tensor_util.py", line 302, in _AssertCompatible
    (dtype.name, repr(mismatch), type(mismatch).__name__))
TypeError: Expected int32, got list containing Tensors of type '_Message' instead.


Extension Library in Domino: Server or Client? Or both?

this may seem like a dumb question but im not that long into Notes/Domino.
I want to run Extension Library by openNTF. Now the question is, if i develop an application with it, can the application itself be used by other clients eventough they dont have the Ext. Lib. installed?
And when i say used i mean USED, not edited. And if not, do they need Ext.Lib.(client) too or can i just install it on the Server? Or do i have to install it on both?

Sorry for the bad english.
Thanks if you can answer :)


Issue calling swift completion handler closure

I have a function which takes a closure as a completion handler. It in turn calls a function that takes one as well. On completion, I want to take the return values from the first completion closure and call the second passing them in.

func saveUserToCloud(user: MBUser, completionHandler: (CKRecord, NSError) -> Void) {
    let userRecord = CKRecord(recordType: kMBUser)
    userRecord.setObject(user.nickname, forKey: kMBUserNickname)
    self.publicDb.saveRecord(userRecord, completionHandler: {record, error in completionHandler(record, error)})
    }
}

This func throws an exception:

fatal error: Can't unwrap Optional.None

func saveUserToCloud(user: MBUser, completionHandler: (CKRecord, NSError) -> Void) {
    let userRecord = CKRecord(recordType: kMBUser)
    userRecord.setObject(user.nickname, forKey: kMBUserNickname)
    // this line throws the exception:
    self.publicDb.saveRecord(userRecord, completionHandler: {record, error in completionHandler(record, error)})
    }
}

What am I doing wrong? I have a record, and no error in this case. I suppose it's trying to unwrap the error?

Thanks


Creating a hidden file in Common Lisp

Since hidden files on a Unix platform simply start with a period, it is trivial to create one using Common Lisp. Hidden files on Windows machines are defined differently. They have a file attribute that indicates whether they are hidden. How can one create these type of files using Common Lisp? I'm using Allegro CL on Windows.


Use alt text for linked image

For images for my website I always use 1 thumbnail and 1 full size image.

I'd very much like to apply alt text for my full size images, but I don't know how, since the full size image is linked with <a> and isn't an <img> object.

It's for SEO reasons, so that the full size images will be more easily searchable through Google image search.

How can I apply alt text for my full size images? I'm using highslide for displaying images at the moment, but perhaps there's another alternative that can give me what I'm looking for.

This is the site that I'm referring to:
http://www.easterislandtraveling.com/easter-island/gallery/


My main method can't see all public methods in a different package in java

My main method in a package by itself can only see some of the methods in the other package even though they are all public. This is an example of my code.

    package stuff.code;
    public class AObject
    {
        public AObject();
        public AObject(String str);
        public int getLength();
        public int getHeight();
    }

    package stuff.code;
    public class BObject extends AObject
    {
        public BObject();
        public BObject(String str);
    }

    package stuff.test;
    import stuff.code.AObject;
    import stuff.code.BObject;
    public class tester
    {
        AObject a = new AObject(); //no red underline
        AObject aa = new AObject("some string"); //no red underline
        BObject b = new BObject(); //no red underline
        BObject bb = new BObject("some string"); //tells me there is no such constructor
        b.getLength(); //tells me I need a getLine method in BObject too
    }

I've looked into setAccessible(boolean flag) method but I didn't understand most of it and it was still undefined after I imported java.lang.reflect.AccessibleObject.

This is not my actual code. I wanted this to be vague so that an answer would be more useful to many other people that run into this problem. My methods are all concrete with a body but the body isn't the issue. It runs fine when everything is in the same package but the tester class must be in a different package.