Showing posts with label Website Design. Show all posts
Showing posts with label Website Design. Show all posts

Monday, 9 November 2015

How Do I Create a Struct from a Hash?

How Do I Create a Struct from a Hash?

I have a hash of values and I want to create a Struct object from them, how would you do that? Structs and hashes are structurally very similar, however there's not a very simple route to get from A to B. But with a bit of magic, you can get the job done.
A Struct is a bit of an odd thing in Ruby. Ruby is all about dynamic programming. You don't have to define rigid structs as in C or C++, you just make a hash and store values indexed by keys.
The fact that some hashes only have certain keys is merely a convention. If it has more keys (such as if you implemented a new feature), it doesn't break anything. Adding new elements to a structure in C or C++ could be disastrous if any code relies of the exact offset of some elements. So why would you want to go back to rigid structs?
One word: speed. Structs can be much faster, and perhaps more importantly they have predictable performance characteristics. One struct object isn't going to be slower that another, because unlike hashes they have a set, static set of elements.
To create a struct, you use the Struct.new method while gives you a new class definition. You can also give it a block which will be class evaled to allow you to define methods that will work on this struct. Typically, you see definitions like this.

Address = Struct.new(:street, :number)

Remember that class names are in fact just constant variables in disguise. So what this is really doing is producing a Class object using the Struct.new method and assigning it to the Address constant.
Later on you can construct a new Address object like so.

a = Address.new("Nowhere Rd", 998)

So, now that you know how structs normally work, say we have a hash and we just want to make it a struct. The hash, for example, is something like this: { street:"Nowhere Rd", number:998 } and we want a hash like the above example.
Well there's two options here. First we can use the above method to create a new class and then create a new object from that new named class. Note the use of the splat operator here. We're splatting both the keys and the values of the hash to create individual method parameters.

address_hash = { street:"Nowhere Rd", number:998 } 
Address = Struct.new(*address_hash.keys) 
address = Address.new(*address_hash.values) 

Great, how you have a new address struct with the same keys and values as the hash. However, what if you don't care about the class name? What if you don't even want to come up with a name for the class at all? Well, classes don't need to be named in Ruby. Names are just a convenience for the programmer. Ruby classes can exist without names, the object simply holds a reference to the Class object so it can tell what type it is. So we'll forgo the assignment to a const. Note that you won't be able to easily create a more instances of this type of struct and struct equality relies of two structs being of the same type and having the same values. Two struct objects with the same keys and the same value are not equal unless they're both the same class as well. This method only works if the structs don't need to be compared.

address_hash = { street:"Nowhere Rd", number:998 } 
address = Struct.new(*address_hash.keys).new(*address_hash.values) 

It can seem a bit strange, chaining the new method calls like that. Just remember that to create a struct dynamically you need to first create a new class then create a new instance of that class. Struct really is an oddball in the Ruby world, but it does have its uses.

Ruby Challenge: Run Length Encoding By Michael Morin Ruby Expert

 Ruby Challenge: Run Length Encoding By Michael Morin Ruby Expert

Run-length encoding is a primitive method of data compression popular in early computing. It works by compressing long strings of the same character to a number followed by that character. For example, the string "wooooooooooah" could be compressed as "w10oh".
For the purposes of this article we'll assume that the strings to be encoded don't contain any numbers. A "real" run-length encoder would use a character to mark a run but for the sake of this article don't use any strings with numbers in them.

Encoding

The first step in encoding is to detect runs of the same character. This can be done with a loop, but Ruby has a great regular expression engine that can be used to do this. We only need to use one trick: a backreference.
To match any character in Ruby, we use the . character. For example, "test".gsub(/./, '!') will replace every character with an exclamation point.
The . regexp character matches any character in the input stream. What we need to do now is continue matching based on that first character.
Your first instinct might be to use something like /.+/, one or more of any character. However, the + sign will keep matching any character, it won't care if the following characters are different. What we need to do is place the . regexp character in a capture group (otherwise known as parentheses). So what we now have is /(.)/.
Capture groups are very interesting things. In regular expressions, capture groups are usually used to match specific groups of characters to be consumed via the MatchData object. However, capture groups can be referred to in the regexp string itself.
For example, the regular expression /(ba)\1/ will match the string "baba", the \1 is a reference to the first capture group. Capture groups are numbered by the order of their opening parentheses, and since there is only one opening parenthesis here it's capture group 1.
Now, back to matching runs of characters.
We'll put the . regular expression character into a capture group and refer to it with a backreference. So we have /(.)\1+/. In other words, we have "any character followed by 1 or more of that character" where before we erroneously had "any character followed by 1 or more other characters." This will be the core of the encoding method.
Now we just need a gsub call. A gsub call will replace all instances of a regular expression in a string with something else. In this case, we want to replace all runs of the same character with the number of times that character appears followed by that character. It's rather straightforward, we'll be using the block variant of gsub to have a dynamic output.

def rle_encode(str)
str.gsub(/(.)\1+/) {|run| "#{run.length}#{$1}" }
end
Like any code that uses regular expressions it can look a bit like line noise at first. There are some techniques to combat that, however this one is so short the reader will just have to suffer through it. Regular expressions are easily the least readable part of any Ruby program, but they're also the most powerful tool for text processing that you can find. They're always a bit unreadable, but they're very, very useful.
One thing that was used here was the $1 variable. Don't be afraid of this Perlism. This is a "global" variable only in name. This $1 variable refers to the first capture group in the most recently evaluated regular expression. It's also thread-local and method-local, so you don't have to worry about race conditions or accidentally overwriting it with a regular expression buried in a method call. We could have just gotten the first character of the run variable, but we really already extracted that first character in the regular expression and it's there waiting for you in the capture group variable.

Decoding

Now that we can run-length encode a string we should work on decoding it. This process is almost the same as far as the code goes. We want to match on any cluster of digits at least 1 character in length, as well as the following character. For ease of access we'll capture both of those in separate capture groups. So the regular expression we want here is /(\d+)(.)/. Now, putting this together following the same gsub pattern of before we get this.

def rle_decode(str)
str.gsub(/(\d+)(.)/) { $2 * $1.to_i }
end
And that's it. You can see why this was appealing to computing pioneers. When your mainframe, minicomputer or microcomputer has only a few kilobytes of RAM you generally don't have the space for a complex compression algorithm. And if you're transferring data over a 300 baud modem or storing on paper or magnetic tape then every single byte matters. Also, since programs also take memory and time it may not even be worth it to load and run a complex compression algorithm in the first place, save memory and time and use a primitive method like run-length encoding. Honestly you'll probably never see run-length encoding in a modern setting, with ready access to so many great compression algorithms it's only rarely used.

Filtering Query Results with Parameter Queries


Sometimes you run a query, and it returns more data than you can possible go through. Sometimes you actually need all of that data to get the best analytical results. More often though, you are really only looking for a small fraction of the information provided. Fortunately, Microsoft Access gives you a number of different ways to filter results so that you can narrow down the data into manageable sizes.
A parameter query is a query that has parameters to filter the information that is returned in the result. You have complete control over these kinds of queries and can update and change them to get whatever information you need at this or any other time. Access remembers your parameter queries, so when you open a parameter query, you will get a prompt for the search term.
It is an incredibly simple, but powerful way of pulling data on the fly. There are a number of things you have to do to create these queries and have them be reliable. Access also lets you add parameter queries to apps, although the process is slightly different.
How to Add a Parameter Query
Adding a parameter query is relatively simple as long as you know what it is you want to use as your filter. The best starting point is to write down the queries that you use often, such as an end date or customer ID, that way you can create all of the parameter queries you are likely to use.
First let’s go over how to add a filter.
  1. Open the query to the one you want to add the parameter query to. Make sure it is in Design View.
  1. Click on the Run icon.
  2. Enter the information you want to check, such as 1/1/15.
  3. Click the OK button.
Your results are now filtered to include information for 1/1/15.
Adding a parameter query is similar.
  1. Make sure you are in the correct query in Design View.
  2. Click on the Create tab, then the Query Design (on the Queries menu).
  1. Select the type of query you would like to add.
  • Select
  • Make Table
  • Append
  • Update
  • Crosstab
The rest of the steps should work for any query, but let’s click Select for now.
  1. Click on the criteria row (in the bottom frame).
  2. Type [ ] and enter what you want the query to filter, such as [Enter the Employee ID]. The information you entered is your parameter, or the identifier.
  3. Highlight the text between the brackets and copy it (do not copy the brackets).
  4. Click on Parameters from the ribbon (under Show/Hide).
  5. Paste the text in the first column.
  6. Click on the drop down arrow in the Data Type column and select the type of data. This should match the type used in the table field.
  7. Click OK.
  8. Run the query.
Now when you want to use a filter, you can use this parameter as the filter. It ensures that users will enter the right type of data, and when a user enters the wrong data type an error message will pop up. Users will have to enter a full, valid value for it to work. For example, if there are no employees with the entered ID or if they don’t enter all of the numbers for the ID (such as entering 26 instead of 00000026), it will not pull the results.
All of the parameter types listed in step three work the same way.
Union Queries
You can also add query parameters to Union queries.
  1. Open the query in SQL View (right click on the query tab and scroll down).
  2. Look at the second bracket after the first SELECT statement. That will be the first thing to add in the WHERE statement.
  3. Enter a line after the first FROM statement.
  4. Type the following
WHERE [second bracket name] = [text you want to appear]
  1. Repeat steps 2 through 4 in the second SELECT statement.
Here’s an example.
SELECT [Item ID], [Date of Order], [Customer], [Item], [Quantity]
FROM [Product Order]
WHERE [Date of Order] = [Enter date]
SELECT [Item ID], [Date Created], [Customer], [Item], [Quantity]
FROM [Product Purchases]
WHERE [Date Created] = [Enter date]
ORDER BY [Order Date] DESC
Once you do that, you can run the query and it will act just like the other parameter queries.
Using Wildcards and Logical Operators
If you want to give users more flexibility in their entries, you can make use of wildcards and logical operators.

Wildcards

Wildcards are incredibly handy tools for users, so you want to make them available as much as possible. It makes it easier to enter long strings of repetitive date (like Employee ID 00000026 can be entered as *26) or to cover all necessary data when a user doesn’t know the exact value.
  1. Go to the query and open it in Design View.
  2. On the Criteria row enter Like “*” and & for the areas where you want users to be able to use the wildcard. . For example, Like “*” & [Enter Employee ID].
  3. Click on Parameters on the ribbon.
  4. Enter the bracketed text exactly as you entered them into the Criteria row, omitting all of the wildcard information. So under the Parameter column you add Enter Employee ID. Like, *, and & are not necessary for this because it is showing the text that displays when the user runs the query.
  5. Enter the data type.
  6. Click on OK.
Always make sure to add quotation marks around the *. The & appends the user entered information to all existing entries. For example, 26 is appended at the end of all entries that end in 0026. So the resulting query will include 00000126, 00000226, 00001126, and so on. Anything Employee ID ending with 26 will be included in the final query. You can also add the “*” & combination at the end of the query as well – Like “*” & {Enter Employee ID} & “*” so that all instances of 26 are returned, no matter where it appears in the Employee ID.

Logical Operators

Logical operators let users enter a range for their searches, which is particularly useful for things like dates and numeric range values. Two of the most common are Between and And.
  1. Go to the query and open it in Design View.
  2. On the Criteria row enter Between [text] And [text]. For example, Between [Enter start date] And [Enter end date].
  3. Click on Parameters on the ribbon.
  4. Enter the bracketed text exactly as you entered them into the Criteria row.
  5. Enter the data types for both identifiers.
  6. Click on OK.
Now you can run the query and see how the parameters work for the user. You now get to enter two sets of dates so that you get more data with the filter.

Databases for Retail Shops

Databese for retails shops

If you are a shop owner or manager, you already know exactly how important it is to have the right database. From inventory and shipping to employees and customers, you know that even a slow day involves a lot of data maintenance. The real question is what kind of database do you need? Hopefully you haven’t tried to maintain this information in Microsoft Excel. If you have, you may want to consider starting with a basic database, like Microsoft Access, so that you can easily transfer the data into the database.
The kind and size of the shop you run makes a big difference in what kind of database makes the most sense. If your shop is set up periodically at farmer’s markets, then you have very different needs than a brick and mortar shop. If you sell food, you will need to track expiration dates as part of the inventory.
If your retail shop is online, then you will have to track fees, shipping, and review information. However, there are a number of things that all shops have in common, such as inventory and cash flow. To help you determine the best database for your specific needs, here are a few things you should consider.
Information to Track in the Database
Running a retail shop entails tracking a lot of different aspects. Not only do you have to keep an eye on the inventory, you have to make sure you have enough ways to display the goods (such as bins, hangers, stands, and cases), supplies to show the price of the goods, bills, sales information, and client information. There is a lot to track, and databases make managing your shop much easier.
Online shops can be difficult to manage because there is so much more you have to track, such as shipping. A database makes it considerably easier to handle all of these different aspects without having to constantly refer to your client or sales history. You can even export information, such as reports, and upload them into your database so that you don’t have to contend with the problems of manual entry.
Deciding Whether to Buy or Build
Whether you should buy or build a database is the big question, and it depends entirely on the size of your business and where you want to take it. If you are just getting started and you have time on your hands (but a very limited amount of cash), building your own database is a great way to make it specific to your unique needs. This is particularly true if you are just starting an online shop. If you start the database just before opening your online retail shop, you will have a much better grasp on your inventory and your beginning point. This is fantastic data to have readily accessible come tax season and it helps you stay on top of your inventory, as well as client data.
If you have a larger business, especially something like a franchise, buying a database is going to work better for you. It will help you through all of the things you might otherwise forget. Odds are, you won’t have time to create and manage the database, so it is best to have all of the bases covered. You can always make your own modifications as you go.
Finding the Right Database Program
If you decide to buy a database program, you are going to need to spend a large amount of time researching the different options. There are a wide range in types of retail shops, and the database market tailors to the unique needs of those different types. If you are working with produce and food stuff, you clearly need something that helps you track perishable items. If you have a jewelry store, you will need to be able to track insurance on the valuable pieces. For shops that have an online presence and a brick and mortar facility, you definitely need something that covers a lot of different angles for your inventory, fees, taxes, and administrative aspects of the business. If you sell out of a particular item, you will need to know early on so that you can immediately mark it sold out for the online portion of the shop.
Before you begin, think about everything you will need to track, then make sure that the databases you consider have those items as a minimum. There are a lot of databases on the market, so you should be able to get everything you need for a very reasonable rate.
Creating Your Own Database
If you plan to create your own database, you will need to determine what program you want to use. Microsoft Access tends to be the go to program because it is powerful and relatively inexpensive. You can import and export data from your other Microsoft software (which is incredibly helpful if you have been tracking information in Excel). You can also load your emails, sales letters, and other documentation (both from Word and Outlook) into the database and make them templates. Access has the added advantage of having a considerable number of free templates and files so that you don’t have to start entirely from scratch. You can pick up a free template, then make the necessary modifications so that your database includes everything you need.
The Importance of Maintenance
No matter how you acquire your database, you will have to maintain it for the database to continue to be useful to you. If you don’t keep up with things like inventory, addresses, changes in billing, or sales totals, the database ends up just being another fixture with no purpose. Think of your data in the same way you think of your bookkeeping. If you don’t keep up with all of the transactions and changes, it is going to get you into trouble. You don’t have to have an IT person to manage it in the beginning, although it can be extremely helpful. However, the bigger your shop gets, the more time you will need to dedicate to maintaining and managing your data.

More PHP in 2015

More PHP in 2015

January
- This January you can start off the year by doing something very simple to get started with PHP.  You can change all the footers on your website to have the current year in the copyright.  No, I don't mean typing in 2015, I mean updating them for the last time ever
February - Your site would be more stimulating if you had a blog!  This month you should install yourself a Wordpress blog...
of if you already have one, your goal this month should be to install a mod to add new features to your blog!  Or maybe try installing a new theme, to change the look of your website.
March -  You know what would be fun this month?  A throwback style counter!  You can make one really simply using PHP.
 Every site you visited in 1995 had one of these, and now they are regaining popularity!  Remember, retro is cool!
April - Let people get in touch with you more easily by adding a contact form to your website.  Not only can you ask specific questions of your users trying to contact you, you also hide your e-mail address form bots that might be farming it to spam you.  Learn how now!  This is an easy and very useful way to work more PHP into your website this month.
May - Remember that blog we added back in February, well now we are going to get a bit more social.  This is a great month to add Facebook to your website.  Or Twitter.  Or Pintrest.  Adding social media to your website will increase it's traffic and requires very little work on your part.
 You can read more about how to add different types of social media
June - This is a good month to add a tool to your website.  What tool?  Well that depends on your website.  If it is a website about Kansas, maybe add a local weather forecast.  If it is a website about style, maybe a person could input their measurements and you could tell them their size.
 People love to keep coming back to use tools on website, so dream something up!
July - Are we to July already?  Let's count down to the end of the year using PHP.  You can add a php countdown to your site to count down to 2016, or a special sale, or an important event happening in your town.  It's easy to do, just look at
August - With everyone getting ready to go back to school, maybe you should brush up on your math.  Your goal this month is to try to figure out how to work some PHP math into your website.  Help preform calculations for your users!
September - Maybe your website needs a search feature!  You can add one this month to help users find content on your site.  Google offers a service to do just this, but if you'd rather write your own code you can learn how to do it by looking at this tutorial.
October - Bad code can be scary!  Boo!  For this halloween season you should clean up and comment your code.
November - Time to understand your computer better!  You know how you think, you for the most part understand other people... but how does your computer think?  It's totally different than you!  In fact a computer can only think in terms of yes and no.  Learn more.
December - It's the end of the year!  Sounds like a good time to reassess your choice of hosting company!  If you decide it's not really doing the job you'd like, you can get some tips on making a transition to a new hosting company less painful in this article. 

Changing Hosting Companies

Changing Hosting Companies

Sometimes you will have to move your website from one hosting company to another.  Perhaps your current host is preforming badly, or overpriced.  Or maybe they are going out of business and leave you know choice.   Regardless of the reason most people hate the process and often stick around at a bad host just to avoid it.  I know I certainly have, transferring always seems like a lot of work.
Even after working with websites for over a decade, and transferring hundreds of sites before...
when it was my own very large and custom sites, I dreaded the process. Every piece of software I was using was modded and then modded more.  I had lots of content I didn't want to lose, and databases that had been hacked together in maybe not the best way.  Still, I had to get everything moved, ideally with as little down time as possible!
Here are some tips for your transfer go smoothly and be a success!
  1. Backup Everything - Obviously you're going to download everything from your current hosting... but make sure that it really is everything. If your site is backed by a database (WordPress, Joomla, phpBB, etc) you're going also need to backup the database. Also, depending on how your website's e-mail is setup, you may need to back that up too. 
  2. Pay Double - Don't try to end your hosting on one day and start your new hosting on the next. I recommend overlapping for a month. You can have everything setup at the new place and simply change the DNS. If all is working fine, you can cancel your old hosting. If something goes wrong, you still have the old site waiting, to temporarily go back to, or to help you troubleshoot what's wrong with the new one.  Sure paying more money sucks, but I believe it's probably worth it in this case.  If you hit snags, having this backup in place is a life saver!
  1. Don't Panic - When you transfer your site and it doesn't work, don't panic. It's usually something very simple. Make sure there wasn't a default index you needed to delete. Check that files that need to be writable are CHMODed correctly. If you had modified your .htaccess, make sure you re-modify your new one, a lot of FTP programs hide this file and it may not have gotten transfered.
  1. Walk Away - If all else fails, walk away from it. Often what is an obviously mistake can be impossible to spot if you've been looking at it to long. Go AFK, relax for 15 mins, and come back. The problem might jump right out at you!
  2. Ask Questions - If you are trying to move something that you didn't create, it can hit snags.  Don't be afraid to ask questions.  Ask the designer, ask the hosting company, ask on a forum.  There is always people who can help!  If you are having a problem, chances are someone else on the internet has had the very same issue and can help you!
Moving your hosting is never going to be a fun process, but it is something you can do.  I always dread doing it, but am usually surprised and how painless it really was when I'm done.  It's never as bad as you think it's going to be!  Just be sure to go in prepared, and everything will be fine!  Really.