Thursday, February 10, 2011

Unknown error on pause()

Hi,

I get the following error

12-15 16:54:37.125: ERROR/MediaPlayer(6032): error (-2147483648, 0)

when trying to execute this code in a service:

MediaPlayer mp = null;

@Override
public void onCreate() {
 if (mp == null) {
  mp = new MediaPlayer();
 }
}

@Override
public void onStart(Intent intent, int startId) {
 if (!mp.isPlaying()) {
  Log.d(DEBUG_TAG, "Not playing, starting stream...");
  try {
   mp.setDataSource(getString(R.string.address_p3));
   mp.prepare(); 
  } catch (IOException e) {}

  mp.start();
 } else { 
  Log.d(DEBUG_TAG, "Playing, pausing stream...");
  try { mp.pause(); } 
  catch (Exception e) {} 
 }
}

When the service is first called and no MediaPlayer-object exists, the stream is started correctly. But when the onStart()-method is called again (with the player streaming) I get the above error code. I can't find any information about this error code, so I turn to you for help. Replacing mp.pause() with mp.stop() makes it work. Could it be that the stream does not support pausing? It's an online radio stream (RTSP) in the SDP format.

Thanks,

Linus

  • I have read this tutorial about the bloggers custom StreamingMediaPlayer class for Android, in the tutorial he talks about how he accomplishes pausing a stream.

    This could be helpful for you, if it doesn't solve what you need at least it gives you another perspective on how to achieve such a task.

    aspartame : I'll check it out!

Children Controls Are Inaccessible Due to Access Modifier

When I create a user control in WPF it would appear that all the children of this control are declared as internal? I've not been able to verify this, nor finding any resources discussing this matter at all.

I can access the controls in the same assembly, but not in a project referencing the assembly where the user control is located. Is there a way to override the default access modifier of child controls in XAML so I don't manually have to expose the controls via properties in the user control?

  • Have you tried to set the x:FieldModifier attribute of your children controls to "public"?

    Qua : Worked like a charm.
  • However, just making them public, is no good idea - its really bad design.

    You should expose their real data through properties of your UserControl. The best thing would be introducing an interface.

    Another solution (more the "WPF-way") would be using the data-context as the only property which is accessed from outside: The controls could bind to the properties they need.

    From winSharp93

Displaying single-instance business object data on SSRS

I have a SQL Server Reporting Services local (i.e. RDLC) report displayed in a ReportViewer, with two subreports. I am using business objects to populate the datasets. What is the best way to populate single-instance data on my report, e.g. a dynamic title, or a text box that lists a calculated value, not based on the report data?

I am currently displaying data using the following style:

public class MyRecordList
{
   string Name { get; set; }
   List<MyRecord> Records { get; set;}
}

public MyRecord
{
   string Description { get; set;}
   string Value { get; set;}
}

I set the datasource to the Records in an instance of MyRecordsList, and they print out find in a table. But adding a textbox and and referring to Name displays nothing. I also tried turning Name into a List, and referring to the first in the list, using:

=First(Fields!Name.Value, "Report1_MyRecordList")

but still nothing is printed on the report.

  • This would be easiest to do with a parameter to the report. Load the report in the report designer and select the Report menu and go to Parameters. Add a string parameter and give it a good name. You can then refer to the parameter in the body of the report with =Parameters.nameOfParameter.Value

    Then add this code before loading the report:

    myReportViewer.LocalReport.SetParameters(new ReportParameter[] { new ReportParameter("nameOfParameter", "parameter's value") });

    From Matt Greer

Dynamic Pageflip 3.5 - help needed changing a page

Hi,

I have purchased a dynamic pageflip script from http://pageflip.hu/.

Has anyone used it before? I have setup all the pages and all is well, however, I am having trouble changing the very first left hand page. (see image -http://img687.imageshack.us/img687/3350/pageflip.jpg).

I have looked in both the .fla files and pagedate35.xml for an instance but had no look.

Can someone who has used the script point me in the direction, all I want to do is replace the page with my own instructions as an image.

Thanks for any help.

  • Although I have never used the pageflip engine from pageflip.hu I am familiar with other very similar implementations (mainly Megazine) and I think that part is not "the first left hand page", it is outside the book so it must be just some textfieds on the stage. Look in the .fla files on the main timeline and remove them (or replace them with whatever you need).

    From danii
  • Not a pro so can't tell you about how to do that in flash but i needed a digital page flip version of my ebook recently and ended up having one in almost no time at this website http://www.createmagazines.com/ very cheaply. I had mine up in few mins.

    From mark mc

form builders for mobile devices

hi all,

We're going to build survey apps for rural development(in India) using cellphones, including some Nokia and Android devices. For building and capturing user info, we're looking at OpenXdata( which is open source J2ME solution) and exZact, (which works on iPhone/iPod Touch). We're also looking at ODK.

What tools/framework have other users used for the same ? Did you use cellphones or custom devices ? What phones worked for you ? What are the pros and cons of each ?

P.S : We're looking to develop for devices in the $100 category so that a big number of such devices can be deployed in the field cost effectively.

Thank you,

BR,
~A

JAX-RS, Map<String,String> to JSON without the overhead?

Hi!

I'm using JAX-RS to create restful webservices in Java. I am getting to much overhead in the produced JSON.

Data class:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Test {

    private Map<String,String> data;

    Test() {}

    public Test(Map<String,String> data) {
        this.data = data;
    }

    public Map<String, String> getData() {
        return data;
    }
}

Service:

@GET
@Path("/test")
@Produces("application/json; charset=UTF-8;")
public Test test() {
   Map<String,String> map = new HashMap<String,String>();
   map.put("foo", "bar");
   map.put("bingo", "bongo");
   return new Test(map);
}

Produces:

{"data":{"entry":[{"key":"foo","value":"bar"},{"key":"bingo","value":"bongo"}]}}

I would like it to produce:

{"data":{"foo":"bar","bingo":"bongo"}}

What is the simplest way to achive this? I am free to redifine my data class but I can't know in advance the keys or size of the map.

in what conditions we can use css * selector?

in what conditions we can use css * selector? how much * selector is useful?

is it only to make css reset or hack

* { margin: 0; padding: 0; }

or it has other valid useful uses? is there a ways to use * selector to optimize css using * selector?

Is it supported in all browsers?

  • It's supported in pretty much everything modern...

    • is useful when you are selecting any child element. So if I want to add some margin to all elements inside an element with an id of "fudge", the selector would be:

      #fudge > * { margin-left:5px; }

    Tatu Ulmanen : The asterisk selector *does* work in IE6.
    bobince : It is of course the `>` child selector that doesn't.
    Dave Markle : sigh... IE6 kills me.
    bobince : Never mind, it'll be gone in [checks watch] oh, 2026. Joy!
  • It's mainly useful where you want to express that there's an element present, but you don't care what it is. For example:

    #mything * span { color: red; }
    

    selects spans inside mything, but not spans directly inside mything.

    You should be sparing about when you use * as a global match. As it could hit every one of the (potentially thousands of) elements on your page it's certainly no optimisation; in particular when it's the last thing in a selector (eg. .thing * or just * alone) it makes most browser selector engines work much harder than an simpler selector like .thing. You can get away with one * rule for resets, but using loads of them isn't a good idea.

    (Personally I'm somewhat against the * { margin: 0; padding: 0; } fix. It affects way more elements than it actually needs to; the real ‘problem margin elements’ are just the list elements and <form> really. Some form controls also look wrong with the padding removed.)

    metal-gear-solid : but we can define css for form elements after reset
    Felipe Alsacreations : Here is an example where it's useful : http://ghettocooler.net/2005/11/13/image-floats-without-the-text-wrap/ (second example: left margin on every child, no left margin on '* *' to avoid doubled margins).
    bobince : `* *` here is a hack to get around IE6's lack of support for `>`, but performance isn't going to be great as the trailing `*`​s require the browser to select every element on the page, twice, before narrowing it down. I'm loath to serve that hack to other browsers. It would seem simpler to me to put a `padding-left: 115px` on the callout and set the background image there instead of on the `h3`, which you might simply `display: none` instead. No extra floats or child-selectors required.
    From bobince

What will be best strategy for designing database for a magazine online?

Hello;

I have design a magazine online and worry that is it the best approch or at least a good approch or no,the magazine contains articles+news in all subjects, i have one table for both articles+news ,but i would like to know that is this good or i must separate articles and news (it is clear that beside the main table there are several tables for categories ,tags,and photos and tables for relation between these tables)?

Thanks

  • I would say, that depends on your schema for the articles and news and how you create new ones.

    If articles and news share the same columns (or the have most columns in common) you can use one table and just have a column that distinguishes between article and news.

    For creating new entries: Do you have a single form in your backend where the author can decide wether the entry should be an article or a news entry?

    If you have different forms because articles and news have different properties, you should consider to create separate tables.

    Do you consider articles and news to be basically the same or do they have even different business logic?


    Edit after comment:
    I meant if you do something different with them like e.g. there is email notification if a new article is created. I assume you don't have that.
    If they have the same properties, then there is no need to create an extra table.
    Nevertheless, having two different tables might be a better choice if you make changes to your system in the future (e.g. one day you realize that you need other properties for articles that don't make sense for news).

  • See very similar question-answer here.

  • the best way to design a database schema is to think not in terms of tables, columns and rows, but in terms of sets and boolean functions. the sql terminology is hopelessly confusing.

Convert Flex Builder 3 project to Flash Builder 4

Hi,

I just upgraded to Flash Builder 4 (beta 2) from Flex Builder 3 which I have been using since it came out. Problem: All the projects that were in my workspace from Flex Builder 3 did not carry over into Flash Builder 4 (e.g. in the "Flex Navigator" view if FB3). Flash Builder 4 now uses the .FXP format to manage projects, but Flex Builder 3 did not. Is there an easy way to get all my projects back into Flash Builder 4?

  • Use File->Import->Other In the dialog, select General->Existing Projects into Workspace Point the root directory to your workspace, check all the projects you want to import and that's it. Worked just fine for me.

    Jonathan Dumaine : Thanks. That's a good solution.
    From sharvey
  • Sharvey's answer was correct, but I also wanted to correct something from the original question, the part about .fxp files. Flash Builder 4 has not changed the format in which it stores projects; it still stores them as a directory with a .project file, a .actionScriptProperties file, and so on, just as Flex Builder 3 did. Where .fxp files come in is, they provide an easy way to package up a project into a single file and share it -- not only with other Flash Builder users, but also with users of Catalyst.

    Catalyst is different from Flash Builder: .fxp files are its "native" format. So, suppose a designer created a project in Catalyst; you, the developer, could then import that .fxp file into Flash Builder using the "import FXP" command. When you do that, it unpacks the fxp into a traditional project format on disk.

    Hope this helps clarify things! - Mike Morearty, Flash Builder team

How should I arrange my projects/classes in .NET to avoid circular dependecies.

My program is attempting to draw grammars in C# & WPF. I have:

1 DataStructure project which describes a tree structure of how it should be visualised. Each node in the tree relates to a symbol in the grammar. Nodes at the top define the rule for that nonterminal symbol.

1 Drawer project which describes the user controls in WPF.

I need to reference drawer in my datastructure as when i traverse the tree, I call DataStructure.draw(); on each node. I also need to reference the datastructure in my drawer project so I can respond to a user clicking on my GUI, it will update the data structure.

This creates a circular depedency, I have tried to use a controller class but I have no idea :/

  • You should look at the Visitor pattern, described here:

    http://en.wikipedia.org/wiki/Visitor%5Fpattern

    This will allow your datastructure project to accept a visitor of any type, including a drawer, but the implementatin of the actual visitor (in your case the drawing logic) to live separately with no dependency in the way you don't want.

    From David M
  • Extract common functionality out of your objects until a third layer of abstraction. You may also want to look at MVC where your grammer would be the Model, your drawer would be the View, and you still need the controller.

PYTHONPATH vs. sys.path

Another developer and I disagree about whether PYTHONPATH or sys.path should be used to allow Python to find a Python package in a user (e.g., development) directory.

We have a Python project with a typical directory structure:

Project
    setup.py
    package
        __init__.py
        lib.py
        script.py

In script.py, we need to do import package.lib. When the package is installed in site-packages, script.py can find package.lib.

When working from a user directory, however, something else needs to be done. My solution is to set my PYTHONPATH to include "~/Project". Another developer wants to put this line of code in the beginning of script.py:

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

So that Python can find the local copy of package.lib.

I think this is a bad idea, as this line is only useful for developers or people running from a local copy, but I can't give a good reason why it is a bad idea.

Should we use PYTOHNPATH, sys.path, or is either fine?

  • If the only reason to modify the path is for developers working from their working tree, then you should use an installation tool to set up your environment for you. virtualenv is very popular, and if you are using setuptools, you can simply run setup.py develop to semi-install the working tree in your current Python installation.

  • I think, that in this case using PYTHONPATH is a better thing, mostly because it doesn't introduce (questionable) unneccessary code.

    After all, if you think of it, your user doesn't need that sys.path thing, because your package will get installed into site-packages, because you will be using a packaging system.

    If the user chooses to run from a "local copy", as you call it, then I've observed, that the usual practice is to state, that the package needs to be added to PYTHONPATH manually, if used outside the site-packages.

    From shylent
  • I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path in the invoke scripts for standalone projects.

    However sys.path.append isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth files. Better (and more readable): site.addsitedir.

    And script.py wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path-frobbing.

    From bobince
  • Along with the many other reasons mentioned already, you could also point outh that hard-coding

    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.

    From unutbu
  • In general I would consider setting up of an environment variable (like PYTHONPATH) to be a bad practice. While this might be fine for a one off debugging but using this as
    a regular practice might not be a good idea.

    Usage of environment variable leads to situations like "it works for me" when some one
    else reports problems in the code base. Also one might carry the same practice with the test environment as well, leading to situations like the tests running fine for a particular developer but probably failing when some one launches the tests.

    From sateesh

Fortran - problem with double precision.

I have a small program that read some data from binary file and stores it into normal (unformatted) files. Here is the source:

  Program calki2e
  IMPLICIT NONE
!
       DOUBLE PRECISION VAL
      INTEGER P,Q,R,S
    INTEGER  IREC2C
      PARAMETER( IREC2C=15000)
      INTEGER  AND,RSHIFT,LABEL,IMBABS,NX,IB,NFT77
      INTEGER  IND
      DIMENSION IND(IREC2C)
    DOUBLE PRECISION  XP
      DIMENSION XP(IREC2C)
      CHARACTER(LEN=12) :: FN77 = 'input08'
    CONTINUE
    NFT77=77
!----------------------------------------------------------------------
2   CONTINUE
c
    open(unit=NFT77,file=FN77,STATUS='OLD',
     +ACCESS='SEQUENTIAL',FORM='UNFORMATTED')
    open(unit=13,file='calki2e.txt')
    REWIND(77)
4100    continue
     READ(77) NX,IND,XP
       IMBABS=IABS(NX)
       DO 100 IB=1,IMBABS
            LABEL=IND(IB)
            P= AND(RSHIFT(LABEL, 24),255)
            Q= AND(RSHIFT(LABEL, 16),255)
            R= AND(RSHIFT(LABEL,  8),255)
            S= AND(       LABEL     ,255)
      VAL=XP(ib) 
            IF(P.EQ. Q) VAL=VAL+VAL                               
            IF(R .EQ. S)  VAL=VAL+VAL                                    
            IF((P .EQ. R).AND.(Q .EQ. S)) VAL=VAL+VAL 
    write(13,*)P,Q,R,S,val
100 CONTINUE
    IF (NX.GT.0) GOTO 4100
CRB
      CLOSE(UNIT=NFT77)
!
    END

When I compile it using gfortran I obtain double precision in output file but with g77 I get only single precision. What it wrong and how to change it?

  • your numbers are double precision but you are printing them in free format. You have to specify an explicit format

  • Hi

    I would be tempted to set the format on your write statement to something explicit, rather than use * in write(13,*)P,Q,R,S,val.

    Regards

    Mark

  • Do you mean the "write (13, *) statement. This is "list directed" output. It is a convenience I/O with few rules -- what you get will depend upon the compiler -- it is best used for debugging and "quick and dirty" programs. To reliably get all the digits of double precision, change to a formatted output statement, specifying the number of digits that you need. (It is probably best to switch to gfortran anyway, as g77 is no longer under development.)

    From M. S. B.
  • Thanks all, problem was solved.

    From Michał

Resizing an image in c# without losing lower an right pixel-parts

I have a c#-class that looks roughly like this:

 class ImageContainer
 {
  Image image;
  internal ImageContainer getResized(int width, int height)
  {
   Bitmap bmp = new Bitmap(width, height);
   //Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image
   System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
   //Set the System.Drawing.Graphics object property SmoothingMode to HighQuality
   gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
   //Set the System.Drawing.Graphics object property CompositingQuality to HighQuality
   gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
   //Set the System.Drawing.Graphics object property InterpolationMode to High
   gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
   //Draw the original image into the target Graphics object scaling to the desired width and height
   System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, width, height);
   gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
   //dispose / release  resources

   ImageContainer ic = new ImageContainer();
   ic.image = bmp;

   return ic;
  }
 }

The resizing works fine, but DrawImage doesn't draw the most right an lower pixel-fragments when scaling down an image.

  • the problem is solved by

    gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
    

    :)

Prevent double click on a row divider triggering celldoubleclick event

In a datagridview with rowheaders visibility set to false and allowusertoresizerow set to true, i need to prevent the celldoubleclick event to trigger if doubleclicked on the rowdivider (Toublearrow of the row resize is visible when the cursor is on the divider).

Thanks

  • I guess the easiest way would be checking the clicked area of the grid on the CellDoubleClick event itself; the logic would be to return in case rowresizetop or rowresizebottom areas are clicked and continue processing if not. Please check an example below for more details:

    private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        // get mouse coordinates
        Point mousePoint = dataGridView1.PointToClient(Cursor.Position);
        DataGridView.HitTestInfo hitTestInfo = dataGridView1.HitTest(mousePoint.X, mousePoint.Y);
        // need to use reflection here to get access to the typeInternal field value which is declared as internal
        FieldInfo fieldInfo = hitTestInfo.GetType().GetField("typeInternal", 
            BindingFlags.Instance | BindingFlags.NonPublic);
        string value = fieldInfo.GetValue(hitTestInfo).ToString();
        if (value.Equals("RowResizeTop") || value.Equals("RowResizeBottom"))
        {
            // one of resize areas is double clicked; stop processing here      
            return;
        }
        else
        {
            // continue normal processing of the cell double click event
        }
    }
    

    hope this helps, regards

    Marco Bettiolo : Thanks, your code works very well.

textBox1.Tag equivalent in Web Forms?

What is the equivalent to textBox1.Tag in Webforms?

  • Inherit from the base control and add a strongly-typed property.

Flash AS3 tweening at an angle

Hi I have a as3 file (listed below) that simply moves a box along the X axis when a mouse is over it (using Tweenlight) . What I want to do though is put the box on a 30 degree angle and have the box move along this angle. Can anybody tell me what I am doing wrong please ?

import com.greensock.*;
import com.greensock.easing.* ;


cont.addEventListener(MouseEvent.ROLL_OVER, onOver);
cont.addEventListener(MouseEvent.ROLL_OUT, onOut);
var stx:Number;

function onOver(e:MouseEvent):void
{
 var stx:Number = cont.x +20 ;

 TweenLite.to(cont, 1, { x:stx });
}

function onOut(e:MouseEvent):void
{
 stx = cont.x - 20 
 TweenLite.to(cont, 1, { x:stx } );
}

Here is live example: http://img42.imageshack.us/i/box.swf/

  • The hardest thing is to move your box on a line at a 30 degree angle. You'll have to use Trigonometry...remember SOHCAHTOA?

    So basically you'll need to move in the x and the y direction.

    In you onOver handler...

    you want to move x to 20*Math.cos(30*Math.PI/180)

    you want to move y to 20*Math.sin(30*Math.PI/180)

    The cos and sin gives you the x and y steps to keep your objects moving along 30 degrees.

    If you want your object to move more change the 20 parameter.

    From milesmeow

XPath + Firebug +XML/HTML +HTML AgilityPack C#

Hi! When using Firebug or some of the bookmarklets:

javascript:(function(){var a=document.createElement("script");a.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js");if(typeof jQuery=="undefined"){document.getElementsByTagName("head")[0].appendChild(a)}(function(){if(typeof jQuery=="undefined"){setTimeout(arguments.callee,100)}else{jQuery("*").one("click",function(d){jQuery(this)[0].scrollIntoView();for(var e="",c=jQuery(this)[0];c&&c.nodeType==1;c=c.parentNode){var b=jQuery(c.parentNode).children(c.tagName).index(c)+1;b>1?(b="["+b+"]"):(b="");e="/"+c.tagName.toLowerCase()+b+e}window.location.hash="#xpath:"+e;prompt('Twoje wyrazenie:',e);d.preventDefault();d.stopPropagation();jQuery("*").unbind("click",arguments.callee)})}})()})();

I receive a HTML's XPath. In order to parse HTML via HTML Agility Pack or Sgml, i need to convert it to XHTML (XML). But the problem is (i think) that XHTML's XPath is different from HTML's XPath. That's why Firebug's "XPath Copy" feature doesn't work when using it with

HtmlNode valueNode = doc.DocumentNode.SelectSingleNode(Firebugs_XPath);

For example, firebug/bookmarklet gives (if I remove tbody it won't help):

/html/body/div[2]/table/tbody/tr/td[2]/table/tbody/tr[2]/td[2]/form/table/tbody/tr[2]/td/div/table/tbody/tr/td[2]/table/tbody/tr[2]/td[2]/u

and proper code is (give or take):

/html/body/div/table/tr[1]/td[2]/table/tr[1]//td[2]/table[2]/tr[1]//td[2]/table/tr/tr/td[2]/u

My question is - how to fix that behavior, in order to make firebugXpath->HtmlAgilityPack work. And - is this possible, to use bookmarklet with built in C# WebBrowser component.

I will really appreciate your help.

  • Firebug's representation of your markup might be different from the actual XHTML because it tries to normalise the markup, and that's what the XPath queries are generated against rather than the actual underlying XHTML. I'm not sure it's possible to change this behaviour, you might just need to tweak the XPaths by hand.

    : I don't think that hand tweaking is possible, just take a look at these two Xpath's, they're really different. Maybe there's an another solution ?
    From cxfx

how to capture the result of `git status` in a Rails action?

If you run this code in a controller action (notice the backticks)

def index
  …
  `pwd >> tc.log` 
  `git status >> tc.log`
  `ls >> tc.log`
  …
end

, only the 1st and 3rd command will pipe their output to the tc.log file.

I'm trying to get the output of git status (f.ex) in a controller action and have tried many variations (capturing stdout, piping to a file, open3, ..) to no avail.

Any idea?

  • This is a total shot in the dark, but git status might not be writing to stdout.

    Try doing something like:

    `git status >> tc.log 2>&1`
    
    Alain Ravet : thanks, it worked. I didn't know about 2>&1.
    jonnii : No problem. Just so you know, 2>&1 will pipe both the stdout and stderr streams.
    jonnii : Also, it's good etiquette to mark the correct answer.
    From jonnii
  • Dude check out ruby-git. Wraps up git commands in Ruby objects!

Bash Script on a Mac creates a info popup

Is there a way in bash on a mac to draw a pretty info box that displays a simple message like "please save all files to /Users/......"

  • You can run fragments of applescript from you bash scripts. A simple popup would look like this:

    #!/bin/bash
    /usr/bin/osascript <<-EOF
    
        tell application "System Events"
            activate
            display dialog "Hello world"
        end tell
    
    EOF
    

    This will feed the applescript between the EOF tags to osascript and execute it
    (resulting in a Hello World popup).

    From Shirkrin

How to populate sqlite3 in django?

My plan is to collect data from websites in batches (lawyer bios from each firm's website; since they are all different, I will use a modified spider for each site) and convert each batch into a csv file; then to json; and then load it to database. So I will need to append each new file to the existing database. Please let me know how to achieve this task the best way. Thanks.

  • Just load the database directly. Collect data from websites in batches, loading the SQlite3 directly. Just write simple batch applications that use the Django ORM. Collect data from websites and load SQLite3 immediately. Do not create CSV. Do not create JSON. Do not create intermediate results. Do not do any extra work.


    Edit.

    from myapp.models import MyModel
    import urllib2
    
    with open("sourceListOfURLs.txt", "r" ) as source:
        for aLine in source:
            for this, the, the_other in someGenerator( aLine ):
                object= MyModel.objects.create( field1=this, field2=that, field3=the_other )
                object.save()
    
    def someGenerator( url ):
        # open the URL with urllib2
        # parse the data with BeautifulSoup
        yield this, that, the_other
    
    Zeynel : Thank you. This sounds good. But can you give me some more detail to start from. A search for "Django ORM" did not lead to any basic stuff that I can use.
    Zeynel : What do you mean by "load the SQLite3 directly?"
    S.Lott : @Zeynel: Your question says you're using Django. Are you actually using Django? If you are, then you already know about the Django ORM. http://stackoverflow.com/questions/1884694/how-to-populate-sqlite3-in-django/1885417#1885417 If you're not actually using Django, please update the question to say what you *are* using.
    From S.Lott

What are some alternatives to PersistentPerl or SpeedyCGI?

I like PersistentPerl quite a bit for both web and command-line use. The only problem is it keeps me tied down to Perl 5.8.x, as it's apparently no longer maintained. I'm aware of mod_perl and FastCGI, but these don't appear to have CLI functionality (correct me if I'm wrong!). So is there a suitable replacement for PersistentPerl?

  • App::Persistent is the modern alternative. It is kind of beta and requires a Haskell compiler, but it is very fast and very non-magical. It tends to Just Work.

    Example persistent application: http://github.com/jrockway/app-persistent/blob/master/repl.pl

    From jrockway
  • Although I don't know I would recommend FastCGI for your problem, it's just a process that sits there handling requests. You don't have to put a web front-end on it. mod_perl would be the same sort of thing. Your script turns into a service around which you have a thin wrapper. Again, it depends on what you are doing.

Accessing Excel.ComboBox from C#

Hi,

I have a combobox (the drop down list control) in a pre-existing Excel template. I can reference this combobox in VBA with Sheet10.ComboBox1.

How can I reference this through Excel Interop in C#?

What I am trying to do is populate this combobox/dropdown with C# and have it positioned where I want with the template.

Thanks in advance.

  • The VBA code to do it is below. Basically you need to access the Worksheet.Shapes collection to find the item that corresponds to your ComboBox (either by index or more realistically by name). Then traverse the properties OLEFormat -> Object -> Object, casting as appropriate. The C# code is very similar.

    Dim wks As Worksheet
    Dim objShape As Shape
    Dim objComboBox As ComboBox
    Dim objOleObject As Excel.OleObject
    
    Set wks = Sheet1
    Set objShape = wks.Shapes(1)
    ' or Set objShape = wks.Shapes("ComboBox1")
    Set objOleObject = objShape.OLEFormat.Object
    Set objComboBox = objOleObject.Object
    
    From Joe

How to change custom component height programatically

Hi,

I've prepared custom component based on LinearLayout. Whole component is defined in XML. Currently to use it you have to write:

<com.xxx.android.components.TopMenu 
    android:layout_width="fill_parent"
    android:layout_height="44dp"
/>

Is it possible to set width and height in the java constructor? So it would be possible to write just:

<com.xxx.android.components.TopMenu />

I've tried to modify and set LayoutParams, but it didn't work for me.

  • Not in the constructor, but in the onFinishInflate() callback to your custom widget, I this might work.

    Michal Dymel : Thanks! It works fine!

ASP.NET URL redirection

I want, when I type http://localhost/Admin, to take me to the page http://localhost/Something/Login.aspx. How can I do this?

  • What you are looking for is called Forms Authentication. A very short introduction follows.

    You need to create a login page that makes a call like this, after verifying the identity of the user:

    FormsAuthentication.RedirectFromLoginPage(userName);
    

    Then you need to wire up the login page in the web.config file:

    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="~/Something/Login.aspx" />
      </authentication>
    </system.web>
    

    Furthermore, you will need to tell the framework that all URLs below ~/Admin/ requires the user to be authenticaticated. This can be done by adding an another web.config file within that folder:

    <system.web>
      <authorization>
        <deny users="?" />
        <allow users="*" />
      </authorization>
    </system.web>
    

    Read the article linked above, or search the web for "ASP.NET forms authentication" and you will soon be on the right track.


    EDIT 1 - If all you want to do is really to "make a redirect to a specific URL", then this is sufficient:

    Response.Redirect("~/Something/Login.aspx")
    

    From the URLs you mention in the your questions, it seems that you are trying to enforce some kind of authentication/authorization scheme. If this is true, forms authentication is a better answer.


    EDIT 2 - If you want to rewrite, not redirect, requests from ~/Admin to ~/Something/Login.aspx you can do so by mapping a URL mapping in your root web.config file

    <system.web>
        <urlMappings>
            <add url="~/Admin/Default.aspx" mappedUrl="~/Something/Login.aspx"/>
        </urlMappings>
    </system.web>
    

    In most setups, the web server will only pass the request to ASP.NET if the requested URL ends with a known suffix, such as .aspx. On approach to trick the web server to pass requests for ~/Admin to ASP.NET, is to use the "default document" feature in the web server. For this to work, you must add an empty file named Default.aspx in the ~/Admin folder.

  • If you want to know about URL rewriting in .NET (and aren't using ASP.NET MVC or Routing which is new in .NET 3.5 SP1) then this blog has an excellent explanation on using the UrlRewriter.Net component... although your question does tend to lead to Jørn's response.

    From Kane
  • You should read this:

    http://msdn.microsoft.com/en-us/library/ms972974.aspx

Why ParameterizableWebPart get returned as an ErrorWebPart?

Hi All,

I'm using WSS3.0 API to get all the webparts in an ASPX page.
The following is my code:

                SPFile page = web.GetFile(pageGuid);

                SPLimitedWebPartManager wpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
                WebPartFactory factory = new WebPartFactory();
                foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in wpm.WebParts)
                {
                    //Some other logic
                }

This code works fine for most of the web part. But for ParameterizableWebPart, it always returns an ErrorWebPart.

The page is correctly configured, because I can view all the reports in explorer.

Have you ever encounter this problem? Or there is something wrong with my code?

Any comments are appreciated. Thanks.

  • PerformancePoint web parts are different animals than regular web parts. There's a great post on technet talking about this, with links to more information. They were built from the ground-up chock full of AJAXy goodness. This might be why you're getting an error when you hit that web part.

Most efficient way to convert an HTMLCollection to an Array

Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?

  • var arr = Array.prototype.slice.call( htmlCollection )
    

    will have the same effect using "native" code.

    Joel Anair : This made my day.
    KooiInc : This doesn't work in IE
    Heath Borders : This fails in IE6.
    From harpo
  • For a cross browser implementation I'd sugguest you look at prototype.js $A function

    copyed from 1.6.1:

    function $A(iterable) {
      if (!iterable) return [];
      if ('toArray' in Object(iterable)) return iterable.toArray();
      var length = iterable.length || 0, results = new Array(length);
      while (length--) results[length] = iterable[length];
      return results;
    }
    

    It doesn't use Array.prototype.slice probably because it isn't available on every browser. I'm afraid the performance is pretty bad as there a the fall back is a javascript loop over the iterable.