Thursday, April 28, 2011

Postgres functions

I need to make a select query with joins. This should be written in a function. My approach didn't work:

CREATE OR REPLACE FUNCTION test2()
RETURNS SETOF record AS'
DECLARE
    r record;
BEGIN
    for r in SELECT * FROM messages_wall INNER JOIN location ON
         messages_wall.id = location.id
         loop
    return next r;
    end loop;
end; '
LANGUAGE 'plpgsql'

ERROR: a column definition list is required for functions returning "record"

I should call this function from a .net application. How should I proceed?

From stackoverflow
  • Instead joining table into your function, you may use view.

    RETURNS SETOF your_view;

    You probably have to define r with the appropriate datatype too:

    r your_view%ROWTYPE;
    

    or

    You have to specify the fields and datatype.

    SELECT * FROM test2() AS fields_1 as INTEGER, fields_2 AS ... ;
    
    Markus : Ok, how can I do this using Npgsql, in ado.net?
    Markus : RETURNS SETOFF messages_wall - doesn't work
    Luc M : Sorry, RETURNS SETOF should work.
    Barry Brown : You can't use SETOF messages_wall because that table is joined with the location table, resulting in a table with more columns than messages_wall. You'll need to define a new type that has the appropriate fields in it.
    Markus : It works indeed with r messages_wall%ROWTYPE. But what if I want to return the values from different tables: for r in SELECT messages_wall.id, location.name FROM messages_wall INNER JOIN location ON messages_wall.id = location.id
    Markus : In this case that approach does not work.
    Luc M : @Barry, I didn't remark the JOIN... Only specifying fields and datatypes works.
    Markus : Ok, as I understand, if I specify fields and datatypes, I cannot use ExecuteReader() with command type stored procedure?
  • For your example wrapping a join in a (PL/pgSQL) function is unnecessary. As Luc M has mentioned a view would be simplest and fastest.

    If you insist on having a function though your next choice should be an SQL function - more info here and here.

Which .NET library / wrapper do you recommend for sniffing packets ?

As far as I understand all sniffing libraries in .NET just a wrapper around WinpCap, which is OK. If you know any other better option please write as answer.

Have you used any of them? Which one is the best according to your experience?

I'm only looking for libraries which have commercial friendly licenses, Also commercial libraries are OK as soon as they got a decent price tag

From stackoverflow
  • Why not use Microsoft Network Monitor? It's free, supported, and has an API you can use, in addition to a set of parsers available on CodePlex.

    dr. evil : Apparently redistribution is not allowed for MS Network Monitor, which doesn't work for me, but thanks for the answer.
    John Saunders : @Slough: I hadn't realized that. OTOH, you might ask MS on their blog if there's a way around that for your purposed. Maybe if your installer were to prompt the user to accept the MS EULA, MS would allow you to include the binaries or their installer. Ask, and find out.
    dr. evil : Thanks for the recommendation, I'll look around a little bit more. The problem is that also I didn't see any sample application using it which might be a problem and turn out to be an immature or quite complicated stuff. Played with some Winpcap stuff, they are quite straight forward.
    John Saunders : @Slough: Good luck, but FYI: Network Monitor has been around for a while, improving with every release. See https://connect.microsoft.com/Downloads/DownloadDetails.aspx?SiteID=216&DownloadID=4547, about version 3.0, in Nov 2006. Agree on samples, but do ask.

using strongly typed datasets with textboxes on web forms

I would like to use a strongly typed dataset with textboxes on a web form. How can i do this? Cheers Mick

From stackoverflow
  • i am really confused about the question, but if you are using linq, you can query the DB and then call Singleordefault() function to return single record, then you just simply can do like this

    TextBox1.Text = SingleRecordQuery().YourDBField;

    hope this helps.

Where is Prolog used for traffic control systems?

The user Laurent had an interesting reply to the question [Why hasn’t logic programming caught on?]:

If you look at the influence logic-programming has had in the field of -- air traffic control -- I don't think it can be said logic-programming has not caught on.

A question arises:

Where is prolog used for traffic control systems on the roads? Why is it used instead of languages, such as C or Python, in such environments?

From stackoverflow
  • This paper 'Commercial Applications of large Prolog Knowledge Bases' may be of interest. Another such read is (freely available as opposed to the former which requires Springer-Verlag membership) Finite State Grammatical Model and Parser for Air Traffic Controller's Commands.

    anon : the second paper you reference is entirely theoretical and I believe unpublished
  • I don't think it is being used in air traffic control - the post you quoted from gave no such references. And it is certainly not being used in road traffic control systems because there are no road traffic oontrol systems - do you call a controller before you make a left turn in your car?

    Masi : The first paper says in dirkgently's reply that Prolog has been used to create systems "which create legal documents, assembly documents for jet aircraft, and work schedules in hospitals --" Perhaps, the writer meant something similar in his reply.
    anon : Thatb makes no sense - I see no mention of ATC.
    Masi : @Neil Butterworth Please, read the abstract. Why does it not make sense?
    Masi : air traffic control = ATC?
    Masi : and what actually does not make sense?
    dbr : "because there are no road traffic oontrol systems" erm, traffic lights?
    anon : ATC is a well known acronym for air traffic control, at least in the UK
    anon : traffic lights at least in the UK have no central control system comparable with ATC
    Masi : Depending on the definition of traffic control system, it can include signals, speed limits, different signs, design of roads, junctions, etc -- there is a great amount of engineering to be done. I am feeling that one could use Prolog there, hence the question.
    Pete Kirkham : Have you never seen the Italian Job? More seriously, motorway signs and variable speed limits are controlled as a system.
  • Prolog is useful at implementing Expert Systems. So if you can think of an expert system useful in controlling traffic, you can use Prolog. I'm not an expert in traffic control and I'm sure it's a very interesting science(as I'm sure any driver sitting at a traffic light can tell you :D), but I think you can create such an expert system that can control traffic light times and synchronization based on statistical data collected over time, of cars passing through an intersection at different times of day.

    I have no ideea of any such implemented systems, I'm just saying where I think Prolog might be useful to use.

    Masi : +1 thank you for the key word :)
  • Coming soon...

    http://www.adesproject.com

document.ready not executing on every load

Hello!

I have a strange problem. I have a jQuery document.ready function executing some script on the page. When I was testing it through opening the file with firefox/opera it worked. When I uploaded it to the server (I tried both my home apache and my shared hosting) it only works once in 10 loads maybe.

What could be the problem?

Thanks beforehand

Edit:

Here is the code. It configures the correct size of side panels according to central panel.

    <script type="text/javascript">
   $(document).ready(function(){
     // Get natural heights
     var cHeight = $("#content").height(); 
     var nHeight = $("#left").height() - $("#footer").height() - $("#header").height() - 10; 

    // Assign maximum height to all columns
    $("#leftcontent").height(nHeight);
    $("#rightcontent").height(nHeight);
     $("#left").height(cHeight);
    $("#right").height(cHeight);
    });   
 </script>
From stackoverflow
  • Check that you have no JS syntax errors first (firebug or simply the error console).

    If not have you considered just putting a simple alert in the ready function. If that still fails you know its something to do with the JQuery library itself (unlikely).

    If you consistently get alerts you know its a problem with your own code. Further help with that will require sight of your code.

    freiksenet : Firebug reports no problems in code, but on server code just does not execute - if I set a breakpoint it never fires. It DOES fire when I do it outside the server. I'll post the code in second comment.
    AnthonyWJones : I don't under stand "on server code", what does that mean.
    AnthonyWJones : Did you do the simple alert test, does that work?
    freiksenet : I mean that it works when I just move to the folder and open with mozzila. When I put it into www folder of Apache server and open it through localhost - it stops working.
    freiksenet : Anyhow - it works pretty stable after I moved css links above js links in . I have no idea why it works now :(

Something wrong with my GridView code...

this code never fills the grid view I know that somthing is wrong here the code

Imports System.Data
Imports ZidduDataSetTableAdapters
Partial Class _Default
    Inherits System.Web.UI.Page
    Dim filesAdp As New FilesTableAdapter
    Dim filestable As New ZidduDataSet.FilesDataTable
    Protected Sub btnfill_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnfill.Click
        Me.GridView1.DataSource = filesAdp.GetData
        Me.GridView1.DataBind()
    End Sub
End Class

and I already created the dataset with wizard called ZidduDataSet.xsd and the adapter name is FilesTableAdapter

can any one help?

From stackoverflow
  • i am not a VB coder, but i think you should call Databind() function on Page Load event too.

    hope this helps.

  • the only thing wrong with the code is that filestable is never used. If your gridview isn't showing up then you have a problem else where i think.

    1. btnfill_Click isn't getting called. Check the .aspx markup to make sure the event handler is referenced.
    2. filesAdp.GetData doesn't return any data.
    3. GridView1 isn't visible on the page.

Image Recognition Library

I wonder whether there is any competent image recognition library ( preferably open source) in .Net? I have an application that scans pages and documents in batches. In order to separate one document from another ( for these documents could have multiple pages), I plan to ask users to put a page, with a say, polar bear image on it to separate between the documents. So my applications will take all the scanning, checks whether the page contain the polar bear, if yes, then call it the end of the first document.

I know about OCR, where the application will recognize the text, but what about the equivalent in images?

From stackoverflow
  • I don't have an answer to the general question about image recognition, but given your specific requirement, might it not be easier to substitute a simpler recognition domain?

    Specifically, on the page that you ask users to put between documents, you could include a nice chunky bar code as well as the polar bear (or whatever) image. Then you could check for the barcode -- which is easily recognisable -- rather than having to recognise the polar bear image per se.

  • I am not sure I exactly understand what you are trying to do, but you might check out these questions:

    If you are looking to implement something yourself to compare an image to a segment of another image. You can do that by using template matching. You can use OpenCV which also has a .NET wrapper

  • Perhaps worth looking at QR Codes?

  • Image recognition is hard mainly because every different application requires a different solution. For example, trying to identify a single black symbol on a white background requires an entirely different technique than trying to identify all the people in a colour photograph where some people are overlapping and there is scenery in the background. Some factors that would influence what method to use would be:

    • Type of image: symbols/characters, everyday photographs, medical images, shapes, etc.
    • Colour: Black and white, grayscale, colour
    • Object of interest: faces, people, shapes, symbols, general objects, fingerprints, irises, tumors, etc.
    • Training: Do you have a training set of data?

    So really what you need to do is tell us more information about the types of images you are trying to recognize so that we can tell you what libraries and what methods would be best to try.

    Ngu Soon Hui : The image I have in mind is just a printed image. Meaning I plan to let user prints a polar bear image from the computer and uses it as the document delimiter.
  • Maybe this framework could be of help:

    AForge.NET Framework

Qt Tutorials?

Does anyone know of a great Qt tutorial for using the designer, I'm new to Qt but I'm intermediate in C++.

From stackoverflow
  • Although not a free tutorial, this book from O'reilly is amazing. It will get you completely up to speed with programming Trolltech's Qt and using the Designer.

    Trolltech themselves also offer very extensive and great documentation. In particular check out the Qt Designer manual here. Another useful page is their class reference here.

    Also consider follwoing through their 14 tutorials by example here. Athough these tutorials do not work directly with the Designer, you will learn how to use it as you follow them through.

    Lucas McCoy : I'm thinking about getting the book for my B-Day! Thanks :-)
    Brian R. Bondy : Checkout the reviews on this book too, its a little more updated than the one I mentioned: http://oreilly.com/catalog/9781593271473/?CMP=AFC-ak_book&ATT=The+Book+of+Qt+4 But the one I mentioned is still good too
  • Qt (4) comes with an absolute mountain of documentation, so you might find what you want there.

    If you've got a full installation you should have Qt Assistant available (run the assistant command) which has a few starter tutorials. If that's not enough then have a look in the qt-demo module, which contains a few (fairly substantial) example programs and full source code.

  • See http://doc.trolltech.com/4.4/tutorials.html for the online tutorials,
    The official book is

    C++ programming QT4

    Another tutorial site http://qt4.digitalfanatics.org/tiqt/ has been published as a book Foundations of Qt Development it's a bit more introductory

  • The "official" book on Qt3 is available for free. It is outdated but could get you up to speed. Be warned that many many things have changed in Qt4. In any case the "C++ GUI Programming with Qtx" series is IMHO the best resource available for Qt new comers.

    Available online is also the book Introduction to Design Patterns in C++ with Qt 4 which could serve both teaching you C++ and Qt4. I wouldn't call it my favorite book in any of both subjects though.

    Lucas McCoy : Anything thats free is good, right?
    Yorgos Pagles : Not necessarily but C++ GUI Programming with Qt are good books. I don't know if the book on Qt3 would serve you good though.
    Lucas McCoy : I downloaded a PDF of C++ GUI Programming with Qt and it's been really helpful!
    Yorgos Pagles : Cool, I 'm glad it helped. Just keep in mind of the differences between Qt 3 and 4. Although this book is almost enough to get you going.

Where is source code for a Linux/Unix application most appropriately kept?

As a developer, I've often downloaded and run

./configure
./make
./make install

to install apps onto my Linux system. But I've never been quite clear on the best place to keep the downloaded directory. My local Desktop is the default location, but I'd like to know what the best "official" place to keep it is. Also, does it vary by distro?

I'm running Ubuntu for now. I know apt-get install can do this for you, but sometimes the app I'm interested in simply isn't available on those lists.

From stackoverflow
  • Perhaps "/usr/local/src" ? ;-)

  • Take a look at the FileSystem Hierarchy Standard: it's /usr/local/src. However, this is a contentious issue as you will find here.

    Jack BeNimble : Thanks for the links. I've never been clear on just where to put these, and that helps to put things in perspective.
  • If you use a package manager, allow it to use the default for managed packages. If you administer the box, put unmanaged third party tools under /usr/local as Steel Plume suggests (though there are some who prefer /opt). If installing as a unprivileged user, unpack and compile in $(HOME)/src, and install into $(HOME)/bin, $(HOME)/etc, and so on.

    George Jempty : I asked this question a couple of years ago on some other forum when developing a Python app on a Linux box. I knew about the standard linked to by dirkgently, but I went with /opt. Nobody communicated to me that this was necessarily a bad idea.
    dmckee : I wouldn't call it bad. Just unusual. The best argument *for* /opt that I know, it that it can be mounted without first mounting /usr. This is a small but real bonus. However, /usr/local has a *long* history.
  • @dirkgently and @dmckee are completely spot on. I would add that since it is can be a contentious issue, I would mimic what the distribution provider (in your case) Ubuntu does for its major packages.

  • for personal use: ~/src

    for sharing across a system: /usr/local/src

Renaming LINQ 2 SQL Entity Properties Through Partial Classes

Hi,

Can I use partial classes to create properties that points to an association property generated by the L2S designer. Also, will I be able to use the new property in queries?

How can I achieve this?

From stackoverflow
  • If you just want to give a different name to the association property, just use the Property page for the association and rename the parent and/or child property. That will change the name of the EntityRef/EntitySet in the class.

    EDIT: The downside of using a separate property in a partial class is that LINQ won't be able to use it when generating queries -- essentially you'll be forced to always get the entities before you can use the related properties on the object. By renaming you allow LINQ to use the related properties in constructing the query which can result in a more efficient query. For example, if you want to get entities where a related entity has a particular property value, using the attribute decorated entity will allow LINQ to generate the SQL to pull just those matching values from the database. With the naive property implementation (that simply references the underlying relation property, in effect renaming it), you will be forced to first get all entities, then do the filtering in your application.

    Ali Kazmi : This is not a practical approach. The changes are overridden when I regenerate the model :(
    eglasius : +1 it is a practical approach. Linq2sql doesn't have a regenerate model button, doing changes in the designer is part of working with it. That said will add an answer for more info on your question.
    tvanfosson : By regenerate, do you mean remove the table and add it back in? Yes, that is a problem, but surely that doesn't happen very often. Or are you using an external mapping file? I don't have any experience with that.
    tvanfosson : You can reference the loaded properties, but if you attempt to select on a value of one of the properties in the indirect reference, it won't be able to translate it directly to SQL.
    eglasius : see my update on one of the tests I ran.
    tvanfosson : Try adding a where clause "where d.MyTestData.ID == 1" or something like that.
    tvanfosson : ...sorry wrong wording in my comment. I didn't mean "selection" I meant the where predicate that does the selection based on the child/parent property.
  • Yes you can, but you have to apply the same attributes as the linq2sql generated property i.e.

     [Association(Name="Test_TestData", Storage="_TestDatas", ThisKey="SomeId", OtherKey="OtherId")]
        public System.Data.Linq.EntitySet<TestData> MyTestDatas
        {
            get
            {
                return this.TestDatas;
            }
        }
    

    TestDatas being the original relation.

    Update: A sample query I ran:

            var context = new DataClasses1DataContext();
            var tests =
                from d in context.Tests
                where d.MyTestDatas.Any(md=>md.MyId == 2)
                select new
                {
                    SomeId = d.SomeId,
                    SomeData = d.SomeData,
                    Tests = d.MyTestDatas
                };
            foreach (var test in tests)
            {
                var data = test.Tests.ToList();
            }
    
    tvanfosson : This won't work the same way if the parent/child relation is used in queries since the indirect property won't be supported for expression translation.
    eglasius : I just ran 2 sample queries :)
    tvanfosson : @Freddy -- you can reference the loaded properties, but I don't think it will work for selection's. Without the attribute decoration I don't think it has the hints required to generate the expression.
    tvanfosson : @Freddy -- see my correction on my answer -- I mean in the where clause.
    eglasius : Correct, it won't work for where clauses, in which case the only way would be to replicate the attributes.
    eglasius : @tvanfosson thx, updated my answer based on that. In the samples I ran the extra pieces were run after the initial query, which doesn't happen with normal relation properties. Somehow I though it had to do with entity sets or something special ... back on the right track now :)

Set a hidden buffer as 'nobuflisted'

How may I set a hidden buffer as 'nolisted' from a vim script?
I tried:
call setbufvar(2, 'buflisted', 1)

From stackoverflow
  • You have to add ampersand sign to 'buflisted' to show to Vim that it is the option:

    call setbufvar(2, '&buflisted', 1)
    
    Ricardo : To set the value of an option, should be like this? setbufvar(2, '&buftype', 'nofile')
    Mykola Golubyev : or if the buffer is already opened let &optionname = value; or set optionname=value

Java socket question

I'm trying to write a simple server-client program, but I have a problem: I can send data from client to server, but I can't send data from the server (I can't recive it in the client) :(
So how to send data from the server, and recive it in the client?

Server:

//this is in a thread
try {
    server = new ServerSocket(1365);
} catch (IOException e) {
    e.printStackTrace();
}
while (!exit) {
    try {
     clientSocket = server.accept();
     is = new DataInputStream(clientSocket.getInputStream());
     os = new PrintStream(clientSocket.getOutputStream());
     while ((line = is.readLine()) != null) {
      System.out.println("Message from client: " + line);
      //if (line.equals("exit")) {
      // exit = true;
      //}
      if (line.equals("say something")) {
       os.write("something".getBytes());
      }
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
    try {
     is.close();
    } catch (IOException ex) {
     ex.printStackTrace();
    }
os.close();
}

Client:

try {
    socket = new Socket(host, 1365);
    os = new DataOutputStream(socket.getOutputStream());
    is = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {}
if (socket != null && os != null && is != null) {
    try {
     os.writeBytes("say something");
     //get the answer from server
     os.close();
     is.close();
     socket.close();
    } catch (IOException e) {}
}

(sorry for the long code)
Thank you in advance.

From stackoverflow
  • Your server's OutputStream is a PrintStream, but your client's InputStream is a DataInputStream. Try changing the server to use a DataOutputStream like your client.

    Even better might be to change both to use PrintWriter and BufferedReader, like the example client/server pair in Sun's Socket Tutorial.


    Just to explain a little about why your code didn't work: You can think of Stream objects as filters that your data passes through. The filter changes your data, formatting it so that the matching filter at the other end can understand it. When you send data through one type of OutputStream, you should receive it at the other end with the matching InputStream.

    Just as you can't store a String object in a double, or a double in a String (not without converting it), you can't send data from one type of OutputStream (in this case a PrintStream) to a different type of InputStream.

    Jani : The program "freezed", but I read Sun's Socket Tutorial and now it's working! :)
    Bill the Lizard : Great, I'm glad it helped. Those are some of the best programming tutorials on the 'Net (not just the Socket Tutorials, but all of Sun's Java tutorials in general).
  • I think an other problem was that I didn't send "\n" after the text, but I used readLine() method.

  • After your os.write() do os.flush(); the message is very small and maybe it's not being sent because it didn't fill the buffer.

How does Tortoise SVN store repository files?

I have been told that the best SVN client for Microsoft Windows is Tortoise SVN.

However, when I install it, adds only items to my shell, i.e. the right-click options when I click on folders.

When I try to check out a folder, it tries to create a repository inside the folder I am working on.

I would prefer my repository to be outside of my work. Is this possible?

From stackoverflow
  • I am not sure what problem you're having, but here you can find a nice tutorial to get started with SVN.

  • Creating a repository and using it are two different things.

    The "Create repository here" action creates a repository which you can access locally via file://.. syntax or via the svnserve daemon.

    The "Checkout" action can be done in any other place. You can either use a local repository, access a repository via http(s) or svnserve.

  • Ollifant's answer is correct, but as you are about to create your first repository, I just wanted to add that file:// is not at all a recommended method of accessing the repository in a production environment. In fact, according to the svn book it should not really be regarded as an option at all:

    Do not be seduced by the simple idea of having all of your users access a repository directly via file:// URLs. Even if the repository is readily available to everyone via a network share, this is a bad idea. It removes any layers of protection between the users and the repository: users can accidentally (or intentionally) corrupt the repository database, it becomes hard to take the repository offline for inspection or upgrade, and it can lead to a mess of file permission problems (see the section called “Supporting Multiple Repository Access Methods”). Note that this is also one of the reasons we warn against accessing repositories via svn+ssh:// URLs—from a security standpoint, it's effectively the same as local users accessing via file://, and it can entail all the same problems if the administrator isn't careful.

    svnserve is almost always better then file:// access and it really is almost no additional effort to set up.

  • If you're trying to run an SVN server of your own that you can then check files into, try VisualSVN. I use it with Tortoise and AnkSVN (all free) and it works great.

  • Start here: TortoiseSVN Documentation & Subversion Documentation.

Why SS generated all Int data type to bool ?

Hi,

My Db have some fields using Integer data type, but after SS generated them, all of them 're Boolean db type.

Please tell me how to fix it !

Thanks !

From stackoverflow
  • Tinyint will be flagged as boolean since many databases use that for true/false. It's a choice we had to make for MySQL which I understand could cause issues.

    If you use SubSonic 3, you can change this in the templates.

Is there a way to distinct more than 1 field

I need a report that has office, date and order count. I need the total count of orders per month, but only 1 order count per day.

e.g.

West 1/1/2009 1 order

West 1/1/2009 1 order

West 1/2/2009 1 order

on my report I would see

West 1/1/2009 1 order

West 1/2/2009 1 order

and my total orders would be 2.

This would be really easy with SQL, I know, but I do not have access.

From stackoverflow
  • You can create three groups, one for office, one for date, and one for order. Then put the fields in the day group footer and suppress the other sections. This will cause the report to show a new section for each day, but only show one row for each order. Then you can add your running total to the section. Set the running total up to sum the field you want, evaluate on change of day group and then reset on change of month (you'll need to set a formula up for this one to evaluate the month).

    This should group and order the report like you are looking for and will have a running total that will run along side which will reset per month. Hope this helps.

  • Are you just looking for this?

    SELECT DISTINCT Office, Date, OrderCount FROM YourTable
    

    This would duplicate your results, but the data set is too small to know for sure if this is what you're trying to accomplish. Using the DISTINCT clause would return only unique combinations of Office, Date, and OrderCount - in this case, one line per day/office.

    UPDATE: Ah - I didn't read the part where you don't have SQL access. You still have two choices:

    1. In Crystal Reports Designer, in the "Database" menu, check the "Select Distinct Records" option at the bottom of the menu.
    2. Edit the SQL query directly - Database menu -> Database Expert -> Under "Current Connections", click "Add new command" and type your SQL command. Modify the one I provided above to meet your needs, and it should do the trick.

regex to match any UTF character excluding punctuation

Hello,

I'm preparing a function in PHP to automatically convert a string to be used as a filename in a URL (*.html). Although ASCII should be use to be on the safe side, for SEO needs I need to allow the filename to be in any language but I don't want it to include punctuation other than a dash (-) and underscore (_), chars like *%$#@"' shouldn't be allowed.

Spaces should be converted to dashes.

I think that using Regex will be the easiest way, but I'm not sure it how to handle UTF8 strings.

My ASCII functions looks like this:

function convertToPath($string)
{
    $string = strtolower(trim($string));
    $string = preg_replace('/[^a-z0-9-]/', '-', $string);
    $string = preg_replace('/-+/', "-", $string);
    return $string;
}

Thanks,

Roy.

From stackoverflow
  • If UTF-8 mode is selected you can select all non-Letters (according to the Unicode general category - please refer to the PHP documentation Regular Expression Details) by using

    /\P{L}+/
    

    so I'd try the following (untested):

    function convertToPath($string)
    {
        $string = mb_strtolower(trim($string), 'UTF-8');
        $string = preg_replace('/\P{L}+/', '-', $string);
        $string = preg_replace('/-+/', "-", $string);
        return $string;
    }
    

    Be aware that you'll get prolems with strtolower() on UTF-8 strings as it'll mess with you multi-byte characters - use mb_strtolower() instead.

    Jacco : This will also replace things like accents (that normally are non-spacing) with a '-'. So 'Aït Ben Haddou' will become 'Ai-t Ben Haddou'.
  • I think that for SEO needs you should stick to ASCII characters in the URL.

    In theory, many more characters are allowed in URLs. In practice most systems only parse ASCII reliable.

    Also, many automagically-parse-the-link scripts choke on non-ASCII characters. So allowing URLs with non-ASCII characters in your URLs drastically reduces the change of your link showing up (correctly) in user generated content. (if you want an example of such a script, take a look at the stackoverflow script, it chokes on parenthesis for example)

    You could also take a look at: How to handle diacritics (accents) when rewriting ‘pretty URLs’

    The accepted solution there is to transiterate the non-ASCII characters:

    <?php
      $text = iconv('UTF-8', 'US-ASCII//TRANSLIT', $text);
    ?>
    

    Hope this helps

    Stefan Gehrig : You're right on this one - leaving non-ASCII characters in a URL will cause problems as you have to track the URL encoding of the client's browser (which is not very consistent). But please note, that iconv-transliteration requires the correct locale to be set (UTF-8 encoding) - using Windows this
    Stefan Gehrig : is a show-stopper.

How does splint know my function isn't used in another file?

Splint gives me the following warning:

encrypt.c:4:8: Function exported but not used outside encrypt: flip
  A declaration is exported, but not used outside this module. Declaration can
  use static qualifier. (Use -exportlocal to inhibit warning)
   encrypt.c:10:1: Definition of flip

Since I called splint only on this file how does it know that?

#include        <stdio.h>
#include        <stdlib.h>

int    flip( int a)
{
        int b;
        b = a;
        b ^= 0x000C;
        return b;
}

int     blah(int argc, char    *argv[]) {

        FILE    *fp = NULL, *fpOut=NULL;
        int             ch;
        ch = 20; flip(20); return (ERROR_SUCCESS);
}

I even got rid of main so that it could not figure out that the file is complete in any way. I am totally stumped!

From stackoverflow
  • It can only report on what it sees. Ignore the warning or follow the instructions to inhibit it if you know better than what it says. Don't assume that a tool like this necessarily knows your program better than you do.

    If it really is not intended to be used outside of the file, you can declare it static and it should correct the problem, but it will be inaccessible from other files.

    ojblass : But thats the point... if I put it into another file the warning goes away!?!?!?!??!
    Volte : splint's diagnosis is correct, within the context of its input (i.e. the only possible kind of correct for a computer program). The problem is that you are interpreting it as a dire warning rather than an observation that has been generated given the parameters given to it. You can ignore it safely.
  • Since I called splint only on this file how does it know that?

    You have answered your question. You've fed in one file to lint, so lint knows there is only file to be taken care of (apart from the standard header includes, of course).

  • int flip() is not declared as static, so it can be potentially used externally. Since you invoked splint with only one source file, it correctly says that your function, if not used externally, must be declared static

  • You might find that if you included a header that declared flip() - as you should, of course - then splint would not complain. You should also declare blah() in the header as well.

    I'm not wholly convinced that this is the explanation because blah() is not used at all (though it uses flip()) and you don't mention splint complaining about that.

    However, it is a good practice to make every function (in C) static until you can demonstrate that it is needed outside its source file, and then you ensure that there is a header that declares the function, and that header is used in the file that defines the function and in every file that uses the function.

    In C++, the 'every function should be static' advice becomes 'every function should be defined in the anonymous namespace'.

    Bastien Léonard : +1, if a function is public it should be declared in a header, otherwise it should be static.
    ojblass : And you are right... forward declaring it in a header file shuts it up and it was complaining about blah as well.

Replacing multiple array contents with a single object?

I have a mutable array with contents I want to replace with NSNull objects. This is what I do:

NSMutableArray* nulls = [NSMutableArray array];
  for (NSInteger i = 0; i < myIndexes.count; i++)
   [nulls addObject:[NSNull null]];

[stageMap replaceObjectsAtIndexes:myIndexes withObjects:nulls];

How can I do this more efficiently? Is there a way to enumerate an NSIndexSet, so I can replace the array content one by one?

Solved

Suggested method turns out to be 2x faster (avg 0.000565s vs 0.001210s):

if (myIndex.count > 0)
  {
   NSInteger index = [myIndex firstIndex];

   for (NSInteger i = 0; i < myIndex.count; i++)
   {
    [stageMap replaceObjectAtIndex:index withObject:[NSNull null]];
    index = [myIndex indexGreaterThanIndex:index];
   }
  }
From stackoverflow
  • You can use a for loop. Start with the first index, use indexGreaterThanIndex: to get the next index, and stop after you hit the last index.

    Don't forget to account for an empty index set. Both the first and last index will be NSNotFound in that case. The easiest way is to test the index set's count; if it's zero, don't loop.

    Also, what Jason Coco said about profiling. Don't worry too much about efficiency until your program works, and don't go optimizing things until you have run Shark (or Instruments, if that's your thing) and found exactly what is slow.

    hyn : Thanks for the tip. I will try to benchmark this and see if the new approach is any faster.

Insert Update trigger how to determine if insert or update

I need to write an Insert, Update Trigger on table A which will delete all rows from table B whose one column (say Desc) has values like the value inserted/updated in the table A's column (say Col1). How would I go around writing it so that I can handle both Update and Insert cases. How would I determine if the trigger is executed for an update or insert.

From stackoverflow
  • If it's MS SQL Server, then IF EXISTS (SELECT * FROM DELETED) tells you if it's an update. You only have rows in DELETED on update, bt there are always rows in INSERTED.

    Look for "inserted" in CREATE TRIGGER

    MSIL : Thanks for the reply - Got everything I needed to know. I agree I must have added that I need to do it for SQL Server.

How do you simply add new custom rewrites to the .htaccess of a wordpress without fail?

I've added some extra functionality to my wordpress so that I can visit it with a variable and do extra stuff.

The problem is, when I turn my ugly dynamic link into lovely permlink formatting in the .htaccess file, wordpress overrides it / ignores it. I've heard there's a way to do it, but the ways I try to do it based off what people have said still returns a 404 page regardless. I know that the file its pointing to works.

2 ways ppl say works but I've had no joy with:

1) insert the rules above the #BEGIN wordpress part 2) use add_rewrite_rule() wordpress function somewhere

Has anybody had any success with these methods? or other methods?

Here's what my .htaccess file looks like

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^/ref/(.*)$ /index.php?ref=1&sid=$1 [NC]
</IfModule>


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


</IfModule>

In my themes function.php I've also tried adding:

add_rewrite_rule('/ref/(.*)$', 'index.php?ref=1&sid=$matches[1]','top');

With no success.

I've also tried the solutions over @ http://stackoverflow.com/questions/723283/wordpress-modrewrite with no joy.

Please help! :)

any ideas?

From stackoverflow
  • a new rule will always override the old ones

    try the following

    <IfModule mod_rewrite.c>
    RewriteEngine On
    #wp
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    
    RewriteRule ^/ref/(.*)$ /index.php?ref=1&sid=$1 [NC]
    
    
    </IfModule>
    
    cosmicbdog : That makes sense. Elsewhere I've read that the custom rules need to be added before the Wordpress begins. On the linked examples above theirs are before. I tried putting it below just now but it doesn't like me :( Thanks anyways !
  • In .htaccess files you have to leave the leading slash in the patterns of the RewriteRule directive away. So try this:

    RewriteRule ^ref/(.*)$ index.php?ref=1&sid=$1 [NC]
    
    cosmicbdog : Tried this with fingers crossed and no cigar :| Thanks anyways Gumbo.
    Gumbo : Did you try it with a relative path?
  • I wound up doing the following in php since the above solutions seemed to not work. Wordpress rulership over the .htaccess file is supreme:

    if(strstr($_SERVER['REQUEST_URI'], '/ref/')) {
    

    And from that have been able to do fairly much the same stuff. A pretty url that translates into something else.

  • This works - I just tested it - Note I added an L to the end of the RewriteRule

    <IfModule mod_rewrite.c>
    RewriteEngine On
    
    RewriteRule ^/ref/(.*)$ /index.php?ref=1&sid=$1 [NC,L]
    
    #wp
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    
    cosmicbdog : THANKS chris very helpful.

Using ereg_replace in PHP?

How do I replace using the following code?

ereg_replace("%Data_Index\[.\]%", $this->resultGData[$key ][\\1], $var)

I want to replace the number in [] %Data_Index
to $this->resultGData[$key ][\\1] same %Data_Index
and how ex %Data_Index[1] = $this->resultGData[$key][1], $var);

replace number in %Data_Index[...........] in []
to $this->resultGData[$key ][............] same number

From stackoverflow
  • hello monkey_boys

    your question is a little bit hard to understand

    the smartest way to replace what you are asking I believe would be using a cycle

    for example if you know that $this->resultGData[$key ][] has 10 elements on them you could simply do this, asuming %Data_Index[1] (are you sure it isn't $Data_Index? i'll asume that) you can try the following

    $total = count($this->resultGData[$key ]);  //we get the total of elements in that key
    
    for($i=0;$i<$total;$i++)
    {
      $Data_Index[$i] = $this->resultGData[$key][$i];
    }
    

    now if the $key changes, you'd need to do this for every $key :)

    keep practicing your english, it's a really useful tool in the IT field :) (not that i'm very a good at it either :P)

    monkey_boys : no that string not array
  • Try the preg_replace() function with the e modifier instead:

    preg_replace('/%Data_Index\[(\d+)\]%/e', '$this->resultGData[$key][\1]', $var);
    

    Note that this function uses Perl-compatible regular expressions instead of POSIX-extended regular expression.

    monkey_boys : it work great thank

MYSQL one to many JOIN

I have this query and I need to include another join on a table called "likes" where updates.id = likes.update_id. There will be 0 or more matches on this join.

"SELECT * FROM users 
INNER JOIN updates ON users.remote_id=updates.owner_id 
ORDER BY updates.status_time DESC LIMIT 50"

This is probably fairly simple, but I haven't been able to find any examples for this kind of query.

The situation is basically that I'm displaying a list of items. I do a join on the users table to grab the user who created each item. I also need to do a join on the "likes" tables to display the 0+ people who liked each item.


EDIT: My Solution

Ok, here's the successful join and combining of duplicate results (due to the fact that there are multiple "likes" for each update) using GROUP_CONCAT.

"SELECT   users.*,updates.update_id,updates.content,updates.status_time,
GROUP_CONCAT(likes.liker SEPARATOR ',') AS liked_by 
FROM updates 
LEFT OUTER JOIN likes ON updates.update_id = likes.update_id 
JOIN users ON users.remote_id = updates.owner_id 
GROUP BY updates.update_id 
ORDER BY updates.status_time DESC 
LIMIT 200"
From stackoverflow
  • SELECT * FROM users 
    LEFT OUTER JOIN updates ON users.remote_id=updates.owner_id
    INNER JOIN likes ON <join condition here>
    ORDER BY updates.time DESC LIMIT 50
    

    Will that work?

    If not, can you clarify what exactly your question is? Does the query you have not work?

    le dorfier : If there are zero or more matches, think "LEFT OUTER JOIN".
    Kalium : Ah. That makes more sense, then.
    makeee : See my edit in the main post. Let me know if that is unclear. I'm a bit tired..
    apphacker : A left join in mysql is always an outer join, and just a join is always an inner join. No need to use 'outer' or 'inner' iirc.
    Kalium : No need, but it makes the behavior more explicit.
  • if you have a 1 to n relation the you should use a LEFT JOIN , i mean if there's only 1 user and many likes.user_id you should doit with the following way

    "SELECT * FROM users LEFT JOIN updates ON (users.remote_id=updates.owner_id) ORDER BY updates.time DESC LIMIT 50"

    this way you'd get all the updates from a certain user :)

    cheers