id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_opensource.1025
In some cases I have noticed that some people say GNU/Linux instead of just Linux. Why is that so? Do both terms mean the same or is there a subtle difference?
Why do some people refer to Linux as GNU/Linux?
terminology;gnu;linux distribution
The GNU project was created to produce a free software alternative to Unix. They were able to produce most of the programs an operating system would provide, but their kernel, the GNU Hurd, was not stable enough to rely upon.Linux is a kernel, the most base level of an operating system, and was created and published under the GNU GPL, a free license. It came to be adopted as the kernel of the GNU OS while the Hurd continued to be developed, but it remains an external project and is not officially part of GNU.It is entirely reasonable to call the combination GNU/Linux as they are two distinct projects paired together. Strictly speaking, Linux by itself is not very useful without all the other software in GNU. But GNU is awkward to pronounce and is a nerdy acronym (but not nearly so nerdy as the double-recursive acronym of Hurd/Hird). Linux is easier to pronounce and is a more conventionally marketable name (being a short word with no previous meaning.)For better or worse, Linux is now a metonym for the whole GNU/Linux OS and greater ecosystem. While it's not ideal that so many people only know the name Linux and not the GNU project which provides most of what they use, the reality is that language is incredibly hard to shift once it has settled, and I personally don't anticipate the situation ever changing. Let's educate people about the GNU OS, but let's not make a fuss if our grandparents (or grandchildren, depending on who you are) don't get the distinction.
_webapps.76703
I would like to assign the size of an image in Google Slides. I don't want to do it with the mouse because it is not letting me put the size I really want. I want to enter a number and that the software respects the number I enter, like in Microsoft Power Point. Is it possible? How?
Assign size to image in Google Slides
google presentations
As far as I can tell, Google Slides does not yet allow you to specify an exact size for an image.One workaround I've used successfully is toCreate a separate, blank drawing in Google Drawings.Within Drawings, select File -> Page Setup... from the menu and set the page size to the exact size you want your image to be in Slides. (Note you can specify the size in either print units or pixels.)Insert the image into the drawing and, if necessary, resize it so it fills the page.Copy the image from Drawings (Ctrl+A, Ctrl+C) and paste it into Slides (Ctrl+V).You should find Slides retains the size of the image, and now you have it in your presentation at the exact size you wanted.
_unix.22740
I quite like the Vi mode of bash. Is there any way to make it work in other programs (gnuplot for instance)?EDIT: As Shawn suggested below, configuring .inputrc and using rlwrap -a -c gnuplot gives Vi mode for gnuplot.
Vi mode in other console programs
terminal;vi
You can use this mode in any program that uses the readline library by adding set editing-mode vi to ~/.inputrc.You can also use rlwrap to make other programs use readline.
_unix.125513
I am using the following code to first split an array into 2 and then search if 2 elements Alchemist and Axe are present in each of the two split arrays.tempifs=$IFS IFS=, match=($i) IFS=$tempifs team1=( ${match[@]:0:5} ) team2=( ${match[@]:5:5} ) if [ array_contains2 $team1 Alchemist Axe ] then echo team1 contains fi if [ array_contains2 $team2 Alchemist Axe ] then echo team2 contains fi array_contains2 () { local array=$1[@] local seeking=$2 local seeking1=$3 local in=0 for element in ${array[@]}; do if [[ $element == $seeking && $element == $seeking1]] then in=1 break fi done return $in}But I am getting the following error - /home/ashwin/bin/re: line 18: [: Alchemist: binary operator expected/home/ashwin/bin/re: line 14: [: too many argumentsLines 14 and 18 are if [ array_contains2 $team1 Alchemist Axe ] and if [ array_contains2 $team2 Alchemist Axe ] respectively.Is the error because of IFS. If not what is the cause for the error?
Finding an elements in an array in bash
bash
null
_cs.62349
I've been trying to solve an interesting problem created by one of my friends. The following is the problem statement:There are $n$ types of chocolates. $\langle a_1,a_2,a_3....a_n \rangle$ are positive integers which represent the number of chocolates of each type. These chocolates must be packed into boxes of capacity $k$ i.e. each box can contain at most $k$ chocolates. Also no box can contain two chocolates of the same type i.e. the chocolates in every box must be of distinct types. What is the minimum number of boxes needed to pack all the chocolates?A greedy approach would be to iteratively fill boxes by picking chocolates from the top $k$ types (in terms of number of remaining chocolates). However this is not of polynomial time complexity. I also tried to solve the decision version of the problem. (can the chocolates be packed using $m$ boxes ?). I was able to model it as a max flow problem but the number of vertices was not polynomial in the input size.Is this problem NP-Complete? If not what would be a good polynomial time algorithm to solve it?
Packing chocolate boxes
algorithms;complexity theory;optimization;time complexity;packing
null
_webapps.30452
I have quite a lot contacts whom I chat with.I already installed lab in Gmail which puts the chat list to the right side to have more space.Now I'd like to group the contacts in the online list in any grouping, best would be the same as Gmail contact groups (or less relevantly maybe Circles), actually anything semantic (i.e. not grouped by first letter or similarly useless).Can anyone point me a Lab, Greasemonkey script or something similar to achieve this?Edit: use cases (may be imaginary) (as suggested by @OnenOnlyWalter)The general idea is that everywhere you can group stuff to organize and work more effectively, easily: think about Contact Groups, Circles, Facebook friend groups (lately even created automatically (Smart lists) for your convenience), Skype contact groups, MSN contact groups, ... I think you get the idea.Now let's see some scenarios:At work we use Google Apps hence Gmail, Talk, Drive, ... I work for support and I support at least 5 customers at time. Each customer has it's own team within the company. I added them to my Contacts and grouped them by team. I want to be able to see who is online from a given team because I need to ask a quick question / remember the client may be on the line...I have my family, friends, colleagues, sport-mates and I want to have see their statuses, but when I want to see if someone is online to ask to go play Squash I don't want to filter my family members/colleagues with my eye if I could just close those groups.Remember a time when the Labels in Gmail were flat, i.e. no hierarchy? What about now? Different [custom] colors, infinite nesting, all out of the box. There were Labs and scripts making it possible then it got integrated. I know there are workarounds for everything, for example on Skype I renamed all my contacts to include prefixes in their names, because it has contact groups, but you can only see one group at a time.Of course when I know who I want to talk to I can filter by typing, however most people like clicking more.In the end it all comes down to convenience, effectiveness, customization.As a strong example: you can use telnet to send Emails through SMTP with hand-written XHTML and Base64 encoded image attachments, why do you use a modern browser, Gmail and its rich text editor then?Few examples of the missing feature
How to group chat contacts in Gmail side chat list?
gmail;google contacts;google talk;contacts group
null
_datascience.596
There are several classic datasets for machine learning classification/regression tasks. The most popular are:Iris Flower Data Set;Titanic Data Set;Motor Trend Cars;etc.But does anyone know similar datasets for networks analysis / graph theory? More concrete - I'm looking for Gold standard datasets for comparing/evaluating/learning:centrality measures;network clustering algorithms.I don't need a huge list of publicly available networks/graphs, but a couple of actually must-know datasets.EDIT:It's quite difficult to provide exact features for gold standard dataset, but here are some thoughts. I think, real classic dataset should satisfy these criteria:Multiple references in articles and textbooks;Inclusion in well-known network analysis software packages;Sufficient time of existence;Usage in a number of courses on graph analysis.Concerning my field of interest, I also need labeled classes for vertices and/or precomputed (or predefined) authority scores (i.e. centrality estimates). After asking this question I continued searching, and here are some suitable examples:Zachary's Karate Club: introduced in 1977, cited more than 1.5k times (according to Google Scholar), vertexes have attribute Faction (which can be used for clustering).Erdos Collaboration Network: unfortunately, I haven't find this network in form of data-file, but it's rather famous, and if someone will enrich network with mathematicians' specialisations data, it also could be used for testing clustering algorithms.
Network analysis classic datasets
dataset;graphs
What you are looking for can be found in KONECT (the website is down as I'm writing this but it should be fixed soon!). It's almost the most comprehensive data collection for network analysis. But the question is which one is more standard to use?Well, there is no clear answer except of Zachary's Karate Club!If you do a literature review in Community Detection algorithms you'll see that almost all shining papers use different networks. My suggestion is going through what Andrea Lancichinetti and Santo Fortunato did for benchmarking graphs. They proposed some benchmark graph generation algorithms e.g. this one. Hope it helps :)
_vi.2136
In Vim's built-in help system, how do Isearch for topics that I want help on?follow hyperlinks?browse around for related material?
How do I navigate to topics in Vim's documentation?
cursor movement;help system;search;tags
Vim comes with an exhaustive and fully indexed documentation that contains the answers to most of the questions you may have on using Vim.But the documentation is huge and may look to the neophyte as an impenetrable maze. Here are a few guidelines to help you find what you needThe :help command is your gateway to Vim's documentation. Read the first screen now.:helpLet's go meta::help helpYou can complete the arguments with <Tab> and display the list of possible completions with <C-d>.:help buf<Tab>:help :w<C-d>By the way, here is an explanation of key notation::help key-notationMost Ex commands can be shortened to a few characters. That's true for :help too::hThe :help command and its tab-completion are case-insensitive so the two commands below will get you to the same section::h BufWritePost:h bufwritepostNote that a and A are both legitimate commands so case-insensitivity doesn't apply.If you only have a generic keyword to search for, use :helpgrep and open the quickfix window::helpgrep quickfix:copenUse <C-]> on the highlighted words to jump to the corresponding tag, use <C-t> to come back.See :help tags for more.Scroll around to see if there's a related option or command that better suits your needs. That's a great way to learn new tricks, too.Use the right syntax to search more efficiently::h :command help for ex-command 'command':h 'option' help for option 'option':h function() help for function 'function':h modifier-key help for 'modifier'-'key' in normal mode:h mode_modifier-key help for 'modifier'-'key' in 'mode':h mode_modifier-key_modifier-key help for 'modifier'-'key' 'modifier'-'key' in 'mode'Examples::h :sort:h 'ai only one quote needed:h bufnr( no need for both parenthesis:h v_ctrl-g:h i_ctrl-x_ctrl-o:h ctrl-w no mode required for normal modeAnatomy of a :help section::help ballooneval'The words highlighted in red are the tags associated with that option.The words in green are the long form and the short form of the option name.The first line in white says that it's a boolean option and that it's off by default, see :help options.The second line in white says that the option is global, see :help option-summary.The purple lines are self-explanatory.Then comes the description of the option.The turquoise words are tags that let you jump to another part of the documentation. Don't be afraid to follow them.Use your brain, find logical patterns that will help you for future searches.Once you have found the handy :help list-functions, where to look for string-related functions?Once you have found :help i_ctrl-x_ctrl-o, how can you find help for <C-x><C-l> in insert mode?RTFM is not an insult. You will learn a lot more by reading the documentation than by asking short-sighted questions to random strangers so make sure you at least tried to Read The Fantastic Manual before asking.
_softwareengineering.340854
I have below constructor, where it creates a workbook in constructor. I read that, ideally, we should not create objects in Constructor, instead, we should have just assignments which are passed. public ExcelWriter() { workbook = new HSSFWorkbook(); //other code }Is it okay to create fixed objects like above?What is ideal alternative solution? and from Unit Testing perspective?If to pass workbook from calling method code in other class, we have to create the workbook object even there also.Is later is better approach? How it is better or matters compared to constructor approach?
Initializing objects in Constructor
java;constructors
null
_softwareengineering.307076
In a project we have a rather formal code review, which is currently done manually and documented in Excel sheets and Word docs.We would like to improve the current code review process by integrating it into a Git workflow (utilizing tools like Bitbucket Server, which we already have, Gerrit, etc.).The current idea is that each developer implements features and bugfixes and creates a pull request. This pull request is reviewed by other developers and then merged into our main development branch or not.We would like to export all pull requests (which are now the code reviews) to formally document them in an offline document. This code review document is a delivery item for our customer.Is this a feasible approach at all?
Documentation of code review
git;code reviews;gerrit
null
_webmaster.2062
I have adsense for content set up for my site running on my blog.It shows up below the post content on each single post (like this one): http://engineercreativity.com/blog/learning-xhtml-and-css-day-12-of-30/However, instead of this showing up:Ads by Google Ad1 Ad2 Ad3 ...THIS SHOWS UP:Ads by Google View ads about: [textbox] [button]Does anyone please have any idea on how to fix this?Thanks!Amit
Adsense for content not working
google;google adsense
That is bizarre, I've never seen anything like that before. First, you should go back and check the code to make sure the code that is output on your page is exactly the same as the code generated from the adsense Ad Manager section.If you edited the code yourself, such as changing the size, there may be a conflict between the settings in the Ad Manager and what you're telling the ads to display. The code may change if you're using a helpful WYSIWYG editor in a CMS, for example, so check against your browser's view source function.Make sure you are using the right settings, i.e. Adsense for Content, Link Unit, and the right size from the drop down (468x15 in your case).
_softwareengineering.86974
At the company I work, we are really wanting to get into the agile methodology for developing software. One thing that I'm not excited about is the fact that management wants us to build a custom project management feature inside the company's Intranet.I think this is a total waste of time. There are many great third party tools available (e.g. Axosoft OnTime) that can do everything we need, and more. For how much development time it would cost us to build our own project management module, we could buy numerous licenses for a third party product.One concern is that, whilst we are writing code for a client, and using our custom Intranet project management module, we find bugs in the module that need fixing ASAP. That means having to stop work on the client code to fix the Intranet. That just puts shivers down my spine.Another worry I have is lack of functionality. This custom module is going to be so basic, that it will just feel really crap to use. That might sound a bit snooty, but for goodness sake, many third party tools are so feature rich, that the idea of having to write our own tool makes feel very uneasy. In fact, I can't be bothered.What do you guys think?I'm going to raise this issue with my boss, since I feel it's such an important topic to talk about.EDIT:Thanks for the great responses, much appreciated. To summarize some of them:MoneyNaturally my boss does want to save money, by not forking out a few hundred 's for licenses. However, for us to write a custom tool, it will take x number of days, multiplied by approx 500, which is our costs. I don't see the business value in this.Management have mentioned that they want to sell the Intranet as a product in the future, but it's so custom to our needs (and downright basic), that in order to give it to another client, I can see us having to fork a version of the code and rebuild the majority of it anyway. So it's not like we're gaining anything there in reuse.FeaturesHaving our own custom module means not feature bloat - only the functionality we require will be in the product. My issue is that there are plenty of free, open-source project management tools out there with minimal features already. So even if cost is an issue, we could look into open-source. Again it all boils down to the fact that I don't see the point in writing a project management tool in this day and age. It's a bit like writing your own web browser - why?, what's the point?Although management are asking for this tool, just because they are, it does not mean I'm going to please them and do it just because they asked for it. If something does not make sense, then I will raise it as a concern.At the end of the day, it's the developers who write the code, it's the developers who make money for a business. Thus, as far I'm concerned, the devs have a very big role in deciding how a company should manage projects and what tools are used. I am Spartan, argh! :)Hmm, I've not been able to make this question a wiki for some reason, thus I'm going to have to pick an answer to accept.Edit:I had a meeting with my boss today. I told about my concerns on us writing a custom tool from scratch. I even showed him OnTime 2010, plus I ran an OnTime SDK example project which showed we could write our own custom code to interact with the data and do whatever we want. I showed all the lists, features, I could think of.But he wasn't convinced. Un-f@king-believable! :(So we will have to write everything from scratch, knowing full well that we could just buy a tool of the shelf to do the job. There's a lot of swear words I could use right now to describe how I'm feeling!EDIT:Responding to recent comments:1) A developer who says he can't be bothered.There were three devs in the team, including myself. One dev was full time on a client project, myself and the remaining dev were working on a big client project. That means myself and the other dev would have to work on the client project, as well as the custom management module - at the same time.The end result was that we ended up a management module, written in ASP.NET MVC by a dev with minimal MVC experience (I was only able to provide a small chunk of time to this module, as I was full time on the big client project). It wouldn't be unfair to say it was pretty crap (no fault of the dev). So yeah, I've no shame in saying I couldn't be bothered to split my time writing a pointless management module, whilst trying to also write a system for a client that were actually going to pay us.2) A developer who doesn't have confidence in his team to build even a simple application to be relatively polished and free of significant bugs (and this is a shop that accepts contract work?The company did great work, we delivered good software to clients - the devs were capable, as a team, to deliver good work. You've put words in my mouth there. I did have confidence in the team, but I wasn't confident they could build client systems on time, and to quality, whilst being distracted with this custom waste of time.3) The one everyone picked up on already, dictatorial management.Our director was pretty set in ways - he wanted the custom module regardless of the fact there were better options. It felt like a lost situation for us. Didn't feel great knowing that he didn't care what alternatives were available.EDIT:To put more context on the situation at the time - our boss wanted us to write the client app and the management module at the same time. They also wanted us to actually use the management module (user stories, tasks, etc) whilst it was being built i.e. dog fooding, with tasks related to the client project.So imagine building TFS, and developing a new version of Visual Studio, but using the in-development TFS to store your work items, user stories, notes, etc relating to the Visual Studio development project. Not cool.
Company wants to write custom project management tool, rather than use third party product
project management
Well, I've seen similar efforts before, and in general, they didn't turn out too bad. A custom-made tool comes with exactly the features your company needs, no bloat added. They are more flexible than any off-the-shelf product could ever be.Sure, it looks like a waste of time, and it probably is, but installing, configuring and getting used to a third-party-tool also takes some time.My take on the situation: If management wants it, do it. It's their responsibility to decided wether or not it is worth the effort.
_cs.20186
I have an algorithm and I determined the asymptotic worst-case runtime, represented by Landau notation. Let's say $T(n) = O(n^2)$; this is measured in number of operations.But this is the worst case, how about in average? I tried to run my algorithm 1000 times for each $n$ from $1$ to $1000$.I get another graph which is the average running time against $n$ but measured in real seconds.Is there any possible way to compare these figures?
Compare asymptotic WC runtime with measured AC runtime
algorithm analysis;asymptotics;runtime analysis;average case
null
_softwareengineering.273818
Suppose I have a class like this:class Foo(object): # some code hereAs it happens, Foo is a singleton. There are numerous ways to write singletons in Python, but most of them don't really feel very Pythonic to me. If someone else has a particularly strong reason for instantiating or subclassing my class, I see no reason to go out of my way to make things unreasonably difficult for them (beyond a minimal this is not part of the public API and might break everything hint).So I hit upon this idea:def singleton(cls): return cls()@singletonclass foo_instance(object): # note lower case # some code hereI had to write singleton() myself because operator.call() isn't a thing for some strange reason.Obviously, you can still just do type(foo_instance) and instantiate by hand, but the lack of a publicly visible class makes it obvious (to me) that you're not really supposed to do that (in much the same way as you're not supposed to mess around with type(enum.Enum) in 3.4+), and I think it looks cleaner than an underscore-prefixed private class such as class _Foo.Is this a reasonable way to go about making a class singular?
Is it reasonable to use a decorator to instantiate a singleton in Python?
python;singleton
null
_unix.344419
I'm trying to write a bash script that makes it easier to use rtmpdump for downloading Flash lecture videos. I've gotten pretty much everything else to work except for using cURL to grab the necessary mp4 URL from the XML page.When I run the following command in my terminal, I get what I want:curl -s http://amps-web.amps.ms.mit.edu/courses/6/6.046/2017spring/L01/MIT-6.046-lec-mit-0000-2017feb09-1103-L01/settings-flash.xml | grep rtmp:yields: rtmp://flashsvr1.amps.ms.mit.edu/6.046/mp4:2017spring/MIT-6.046-lec-mit-0000-2017feb09-1103-L01.mp4</url> (I'm aware of the trailing header, it's taken care of in my bash script)However, when I try to run the same command in my bash script and save the output to a variable, I get nothing. Running just xml=$(curl -s $url) and echoing that out results in a bunch of (but not all) headers, nothing else:<camera id=2 cameraX=960 cameraY=0 thumbnailX=960 thumbnailY=0 name=CAM2 selectedName=LIVE 2 <camera id=3 cameraX=0 cameraY=540 thumbnailX=0 thumbnailY=540 name=CAM3 selectedName=LIVE 3 <camera id=4 cameraX=960 cameraY=540 thumbnailX=960 thumbnailY=540 name=CAM4 selectedName=LI <fullscreenOutButtonImageOver>fallback/assets/btn_fullscreenOff_selected.png</fullscreenOutButtonImageOve <fullscreenOutButtonImageDown>fallback/assets/btn_fullscreenOff_selected.png</fullscreenOutButtonImageDow <communityRealOutButtonImageNormal>fallback/assets/buttons/community_selected_up.png</communityRealOutBut <communityRealOutButtonImageOver>fallback/assets/buttons/community_over.png</communityRealOutButtonImageO <communityRealOutButtonImageDown>fallback/assets/buttons/community_down.png</communityRealOutButtonImageD <thumbspositionTopButtonImageNormal>fallback/assets/btn_thumbnailPositionTop.png</thumbspositionTopButton <thumbspositionBottomButtonImageNormal>fallback/assets/btn_thumbnailPositionBottom.png</thumbspositionBot </settings>ge>fallback/assets/affiche.png</landingImage>>ng</thumbnailActive>Progress>geDown>Down>Does anyone know what might be happening with this? It's quite frustrating. Thanks!
cURL response not showing body of XML
shell script;curl;xml
Your data has carriage-returns in it. Filter them out:curl ... | tr -d '\r'Also, quote your variable when you echo it:$ echo $xmlOr even better:$ printf '%s\n' $xmlQuoting prevents word-splitting. Word-splitting happen on all unquoted variables on the command line and involves splitting them line into words based on the value of $IFS. $IFS is by default a tab-character and a space-character and a new-line character. See Word Splitting or Field Splitting in the manual for your shell.
_unix.299640
I just bought an Intel NUC6i3SYH and I installed Debian Jessie on it. I couldn't get the WiFi working. I already tried installing firmware-iwlwifi by following this tutorial, but it still doesn't work. I also tried installing with the Debian non-free installer, but it also doesn't work. It also doesn't work with Lubuntu, but it works with Linux Mint. How can I get it working with Debian?
WiFi on Intel NUC6i3SYH
debian;wifi;iwlwifi
According to wireles-wiki-kernel Intel Wireless 8260 is supported by Kernel version > 4.1. To get wifi working you need to install the required firmware from backport (the easy way) or Upgrade your current kernel version.First you need to enable backport echo deb http://ftp.debian.org/debian jessie-backports main contrib non-free | sudo tee /etc/apt/sources.list.d/jessie-backports.listThen install the required firmware through the following command: sudo apt-get update && sudo apt-get install -t jessie-backports firmware-iwlwifi
_codereview.131645
In my office, we use a software called Blue Prism, a Robotic Process Automation System. The idea is to allocate tasks for the robots to perform thereby simulating users. The system enables you to use a code stage ( with an option of C# with dotnet framework 2.0) and to import some objects in C#, you require a DataTable. My problem is Currently, The datatable has one row with ID, FirstName, Initial and LastName as a columns but the chances are thousands of rows will be added subsequently.The row contains values such as table.Rows.Add(new object[] { 1, Mary;Josh;Sam, K;;, Edward;Rashidi;Martha });but what i want isFirstName Initial LastNameMary K EdwardJosh RashidiSam GrunuaP.S I have never had to use so many nested loops until now because Linq existed and it's currently not available in .net 2.0Based on my research of DataTable, when you are aiming at retrieving data faster you use DataTableReader. Hence I used it here. I defined four methodsPrintColumns(DataTableReader reader) - to print out all the cells ofthe datatableTransformDataTble(Datatable datatable) - which generates the newdatatable i am aiming forGetCustomers() - returns an input datatable containing required dataTestCreateDataReader(Datatable dt) - to check if the datatable hasrows before attempting to print. Hence this calls printColumns() public static DataTable TransformDataTable(DataTable dataTable) { DataRow row; int counter = 0; DataTable newTable = new DataTable(FormattedTable); // Gives the newtable the same column Names as the oldtabble foreach (DataColumn column in dataTable.Columns) { newTable.Columns.Add(column.ColumnName); } using (System.Data.DataTableReader reader = dataTable.CreateDataReader()) { while (reader.Read()) { if (reader.HasRows) { for (int i = 0; i < reader.FieldCount; i++) { if (Convert.ToString(reader[i]).Contains(;) { String[] splitString = Convert.ToString(reader[i]).Split(Convert.ToChar(;)); foreach (string item2 in splitString) { if (newTable.Rows.Count != splitString.Length) { row = newTable.NewRow(); row[reader.GetName(i)] = item2; newTable.Rows.Add(row); } else { for (int j = counter; j < newTable.Rows.Count;) { newTable.Rows[j][reader.GetName(i)] = item2; break; } counter++; } } counter = 0; } } } } return newTable; } }private static void PrintColumns(DataTableReader reader) { // Loop through all the rows in the DataTableReader while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { Console.Write(reader[i] + ); var b = reader[i]; } Console.WriteLine(); } } private static void TestCreateDataReader(DataTable dt) { // Given a DataTable, retrieve a DataTableReader // allowing access to all the tables' data: using (DataTableReader reader = dt.CreateDataReader()) { do { if (!reader.HasRows) { Console.WriteLine(Empty DataTableReader); } else { PrintColumns(reader); } Console.WriteLine(========================); } while (reader.NextResult()); } } private static DataTable GetCustomers() { // Create sample Customers table, in order // to demonstrate the behavior of the DataTableReader. DataTable table = new DataTable(); // Create two columns, ID and Name. DataColumn idColumn = table.Columns.Add(ID, typeof(int)); table.Columns.Add(FirstName, typeof(string)); table.Columns.Add(Initial, typeof(string)); table.Columns.Add(LastName, typeof(string)); //table.Columns.Add(DOB, typeof(string)); //table.Columns.Add(Member, typeof(string)); //table.Columns.Add(Number, typeof(string)); // Set the ID column as the primary key column. table.PrimaryKey = new DataColumn[] { idColumn }; table.Rows.Add(new object[] { 1, Mary;Josh;Sam, k;;, Edward;rashidi;Grunua }); return table; } } while (reader.NextResult()); } }So far this code works, but i know his can be improved . Any suggestions would be helpfulP.S kindly comment on other forms of implemetations asides Linq as Linq is non existent in the .net 2.0 framework
How to generate Datarows based on a delimiter in a Datacolumn from a DataTable in C#
c#;.net datatable
Move code to methods. By the time you hit for (int j = counter; j < newTable.Rows.Count;) you're nearly ten levels deep. Not only are you losing valuable screen estate, it also doesn't help the clarity of your code.You could also use continue; to reduce indentation:if (!reader.HasRows){ continue;}And:if (!Convert.ToString(reader[i]).Contains(;){ continue;}I don't see the point of defining DataRow row; at the top, considering row is only used inside if (newTable.Rows.Count != splitString.Length).Why don't you simply Clone() the DataTable instead of doing foreach (DataColumn column in dataTable.Columns)?Convert.ToString(reader[i]) is used twice, so perhaps it would be beneficial to store its results. Same for reader.GetName(i), and in that case it is even more important considering it is used inside a loop.The name of item2 doesn't tell me anything about what it contains.Avoid negative logic like if (newTable.Rows.Count != splitString.Length) ... else; instead do it the other way around: if (newTable.Rows.Count == splitString.Length).; should be defined as a private const char, and that variable should be used in IndexOf instead of Contains(;); that way you can also avoid Convert.ToChar(;).
_unix.313886
QuestionSuppose I have some non-directory (file, named pipe/socket, whatever) at the pathname /tmp/foo and some other non-directory at the pathname /tmp/bar. Then two (or more) processes start executing concurrently:Process one does:unlink('/tmp/foo') /* or rename('/tmp/foo', '/tmp/removed') */unlink('/tmp/bar') /* or rename('/tmp/bar', '/tmp/removed') */Process two (and so on) does:link('/tmp/foo', '/tmp/bar')As I understand it, there is no way process two could possibly succeed (either the link(2) is attempted while /tmp/foo is still present, in which case /tmp/bar is also present so it must fail with EEXIST, or /tmp/foo is gone so is must fail with ENOENT).But this intuition relies on the assumption that the unlink(2) and/or rename(2) system calls are inherently sequential in their unlinking effects, so I am looking for verification of my understanding: Is there any *nix-like system out there whose kernel allows the two unlink(2) and/or rename(2) calls to succeed, but simultaneously causes link(2) to succeed as well (whether due to re-order the unlinking of /tmp/foo and /tmp/bar and not abstracting/hiding that from the process calling link(2), or through through some other quirky race condition/bug)?Current UnderstandingI have read the manpages for unlink(2), rename(2), and link(2) for Linux and a few BSDs, and the POSIX specification for these functions. But I don't think they actually contain anything reassuring on this matter, upon careful consideration. At least with rename(2), we're promised that the destination is atomically replaced if it's already present (bugs in the OS itself aside), but nothing else.I have seen claims that multiple simultaneous executions of rename(foo, qux) will atomically and portably have all but one rename fail with ENOENT - so that's promising! I am just uncertain if that can be extended to having a link(foo, bar) fail with ENOENT under the same circumstances as well.Preferred AnswersI realize that this is one of those can't prove a negative situations - we can at best only note that there is no evidence that a *nix-like system which will allow process two's link(2) to succeed exists.So what I'm looking for is answers covering as many *nix-like systems as possible (at least Linux, OS X, and the various BSDs, but ideally also the proprietary still-in-some-use systems like Solaris 10) - from people who have sufficient familiarity with these systems and this narrow set of problems (atomic/well-ordered file system operations) that they're confident (as much as one realistically can be) that they'd know of issues like the aforementioned Mac OS X rename(2)-not-actually-atomic bug if they existed on the platforms they're familiar with. That would give me enough confidence that this works the way I think it does in a portable-enough manner to rely on.Final NoteThis isn't an X/Y problem question - there's no underlying problem that can be answered by referring me to the various locking/IPC mechanisms or something else that works around the uncertainty about how these particular system calls interact: I specifically want to know if one can rely on the above system calls portably interacting as expected across *nix-like systems in practical use today.
Will an `unlink` or `rename` portably and atomically make a `link` fail?
files;rename;portability;concurrency
null
_softwareengineering.328502
When designing a system that displays information about an entity (but where modification of the data is rare or restricted to few users - such as a user profile), would it make sense to have two separate classes to do this?One for management of a user profile (logging in, changing password, modifying profile content) and another purely for the consumption of this data (a UserProfile/UserView) which can only retrieve the displayed data for the user. Is this a sensible choice to make?Would there be any security reasons in this style of architecture?Would this violate the concept of modelling an entity as a single class? (and are there instances where this is acceptable/expected?)Are there any common patterns or best practices for modelling an entity in this way?Let's work on the assumption that this is a social media profile.
Would it be good practice to separate a user entity and a user profile entity?
object oriented;object oriented design;single responsibility
To answer your question, there are several aspects to think about.Depending on how you see the user, the user-Information could be modeled as part of the userprofile or the other way around:user = { lastname: Doe, firstname: John, id: a972f435-5263-401a-a03b-950e9e0e29c1, birthday: 1970-01-01 }There is nothing wrong with this kind of data. If you use a backend capable of dealing with JSON, you could store it right away.On the other hand, depending on how detailed your user is, it makes sense to separate user-data from profile-data; or perhaps you have the need to use different databases for different purposes: say, you have a login-service which serves the only purpose to log in users - in such a scenario it makes perfectly sense to have your user in one place and the profile in another (perhaps you are using MongoDB or something like that).Is this a sensible choice to make?There is no general solution to that. It is a rather philosophical question without context. A nice topic for a scholastic discussion about architecture.Would there be any security reasons in this style of architecture?Unfortunately I am no security expert to give you a detailed answer to that. You have to secure your system anyways. From a security perspective it could make sense to split between user and profile or better: user, profile, creditcard-data in three different databases. But that is a naive guess. There are people who are better at security than me ;)Would this violate the concept of modelling an entity as a single class? (and are there instances where this is acceptable/expected?)Are there any common patterns or best practices for modelling an entity in this way?As said from the above: there are reason to handle it one way or the other. I would go with as long as you have no reason to really split the data, keep it all together. Look for simple solutions in the first place and evolve your system alongside with your needs.
_cogsci.9671
Many people online seem to claim that: When a group of people laugh, people will instinctively look at the person they feel closest to in that group.You can find the claim in 31 Psychological Life Hacks That You Can Exploit To Give Yourself An Advantage In Social Settings by thoughtcatalog.com.Thoughtcatalog.com wrote under the claim:Read: wanna know who wants to bone who? Look at who they look at when everyone laughs.It seems they were referring to a book, but I couldn't find it online.The claim is also found by distracity in a post showing psychological life hacks that'll make you more successful.The claim is widely and internationaly believed, a simple google query will show you.Is it true? If so, I'm looking for a reference or some explanation for this.
When a group of people laugh, people will instinctively look at the person they feel closest to in that group
social psychology
null
_opensource.1675
The Panton Principles stateMany widely recognized licenses are not intended for, and are not appropriate for, data or collections of data. A variety of waivers and licenses that are designed for and appropriate for the treatment of data are described here. Creative Commons licenses (apart from CCZero), GFDL, GPL, BSD, etc are NOT appropriate for data and their use is STRONGLY discouraged.Why is this? What is wrong with using Creative Commons licenses for data?
Why aren't Creative Commons licenses appropriate for data?
creative commons
Well, this gets complicated and legal. (Caveat: I am not a lawyer.) According to Creative Commons, their licenses:give everyone from individual creators to large companies and institutions a simple, standardized way to grant copyright permissions to their creative work.In short, CC licenses apply to creative works and are meant to relax or waive the copyright protections automatically guaranteed to authors (e.g., by common law tradition in Commonwealth countries).The applicability of CC licenses to data depends on whether data can be copyrighted. If data cannot be copyrighted, then there is no point to putting a CC license on them because those licenses waive rights that the data creators do not have.So what kinds of works are protected by copyright? Though laws vary across jurisdictions (and thus make this question difficult to answer), two important principles are the Idea-Expression divide and the threshold of originality. In the former, only expressions of ideas can be copyrighted, while ideas themselves cannot be. In the latter, among expressions, only those that are original are protected (thus reproductions of works do not earn copyright protection de novo).Thus data only have copyright protection if they are an expression of an idea rather than idea itself and if they are not simply facts (i.e., they are something sufficiently original). In the United States, this almost universally means that data cannot be copyrighted. A classic legal case here is Feist Publications, Inc., v. Rural Telephone Service Co., which ruled that telephone number listings in a phonebook are not protected by copyright. Importantly, nothing produced by the federal government has copyright protection (all federal government works are in the public domain, but this does not necessarily apply to other levels of government).In Europe, however, databases do have copyright-like protection. Not all databases are protected; protection comes from qualitatively and/or quantitatively a substantial investment in either the obtaining, verification or presentation of the contents. Such rights extend for 15 years.Thus, one has to determine whether the data being discussed merit copyright on their own. It may be that data refer to works that are themselves copyrighted (e.g., original written works, such as newspaper articles). Those data are protected but not because they are data, rather because they are creative works. Someone who has compiled those works into a database in the United States has no copyright protection for the works (unless they have obtained those rights for each data point from the original author(s)). In Europe, however, the compilation of those data into a database may entitle the compiler to a limited database right.In conclusion, CC licenses make sense if one has copyright protections to give away. If not, then CC licenses make no sense because the data are probably free to use anyway. If the data do merit protection (due to either satisfying European-style threshold of investment, or American-style threshold of originality, or some other national standard), then I believe the argument made in the linked webpage is purely made on the opinion that CC0/(or Public Domain, where that principle exists) are preferable to more restricted waivers of rights.
_hardwarecs.6803
I am looking for a capture card that will capture RGB signal from retro consoles on my desktop machine. The consoles I would be capturing (SNES, PS2 and the likes) have a Scart RGB-able cable and for best video quality I would like to be able to capture the RGB signal as directly as possible.My operating system is Ubuntu (current LTS version) and I would like to use OBS for streaming and the likes.Since Scart connectors are rather large, if you suggest a card which accepts a different type of cable thats fine (but please at least leave a hint on how to connect Scart to the card).I have ample USB ports (2.0 and 3.0), PCI and PCIE x1 slots available.In summary:RGB-supportingAccepts Scart or with an idea how to input from ScartUbuntu and OBS compatibleUSB/PCI/PCIEx1 connectedBonus would be if VGA input from another PC is also accepted.
Linux-compatible RGB-supporting video capture card
linux;video capture
null
_unix.198720
I have a stubborn file on an NTFS partition which refuses to be deleted. A little background on the problem...Problem happened when I was running Zim on my Linux and the system froze due to some reason. Now, Zim had a page open at that time which was being edited. Zim is a notebook wiki which stores its data in plain text files. Each page of zim is stored in a text file. Hence there was some file which was open at that time on the filesystem. I rebooted using the power switch, and when I opened Zim and tried editing the page it was unable to save that page and instead created a backup file for that page by the name myNote.txt.zim-new~. Now, when I try to delete this file, it says: rm: cannot remove myNote.txt.zim-new~: No such file or directoryMy hunch is that Zim moved the original file being edited to this backup file and created a new file. So, this backup file is the original which got corrupt. The thing is that I can read this file perfectly fine, but renaming it or deleting it or even moving to trash is not working. I also tried deleting with root. So far after researching a bit, I found that it might have got something to do with the special character in the name of this file. Or maybe the file has just got corrupted in some weird way. And the solutions people are suggesting is using chkdsk in Windows. But the problem is that I don't have Windows. So, how are people fixing such errors? UPDATE-1I tried using ntfsfix and testdisk but they reported the partition to be okay. UPDATE-2I created a new file with very similar name and it gets deleted/renamed/moved to trash very easily. UPDATE-3That folder is synchronized with Dropbox, if that's any help. PS: I have an ntfs partition on a Linux-only box because I was thinking of installing Windows later. And this partition would act as the common for both.
How to fix ntfs file problem when there is now windows?
files;ntfs;corruption
null
_unix.302416
I'm trying to write a C program that goes through all USB devices and extracts some information from them. When I run ls /sys/bus/usb/devices from the terminal, I get this output:1-0:1.0 1-1.1 1-1.2 1-1.2:1.1 usb11-1 1-1.1:1.0 1-1.2:1.0 1-1:1.0However, running ls within a system() call in C only shows the following devices:1-0:1.0 1-1 1-1.1 1-1.1:1.0 1-1:1.0 usb1I can't think of a reason why the rest of the devices aren't showing, maybe something to do with permissions? Is there anyway to get all of them to display?
USB devices not showing
usb device;system programming
null
_unix.9099
I ran these commands:VBoxManage clonehd d6b9f0a5-98df-48ca-83c8-91a0809ec349 --format RAW Debian.rawsudo dd if=~/.VirtualBox/HardDisks/Debian.raw of=/dev/sda5When I try to mount the partition, I get this complaint:EXT4-fs (sda5): VFS: Can't find ext4 filesystemNow I know that the VM had an ext4 partition. What did I do wrong?
Reading a filesystem from a whole disk image
linux;partition;virtual machine;file transfer
null
_codereview.41734
Is this bad practice? Also, how can it be improved?#!/usr/bin/env bashRUBY_VERSION=2.1.0printf Installing Ruby $RUBY_VERSION\\nif [ -d ruby_build ]; then rm -Rf ruby_buildfiif [[ `command -v ruby` && `ruby --version | colrm 11` == ruby $RUBY_VERSION ]] ; then echo You already have this version of Ruby: $RUBY_VERSION exit 113fisudo apt-get build-dep -y ruby1.9.1mkdir ruby_build && cd ruby_buildcurl -O http://ftp.ruby-lang.org/pub/ruby/2.1/ruby-$RUBY_VERSION.tar.gztar xf ruby-$RUBY_VERSION.tar.gzcd ruby-$RUBY_VERSION./configuremakesudo checkinstall -y --pkgversion $RUBY_VERSION --provides ruby-interpreter --replaces=ruby-1.9.2cd ../.. && rm -Rf ruby_build
Ruby install script; packages+installs as a .deb or .rpm from source
bash;installer
First,I would like to point out that not all .deb-based distributions are as fond of sudo as Ubuntu is. For example, Debian doesn't use sudo out of the box.It appears that you're trying to build a newer version of Ruby than is available in the stock package repository. In that case, why not make a proper .deb package with its .dsc and publish it in a private APT repository? Then, everything integrates properly into the distribution the way package management is supposed to work, including the build process and subsequent updates. Everyone will have a better experience when you work with the system instead of against it.
_cs.63823
BFS and DFS can be achieved in O(|V| + |E|). I understand the proof but it seems a bit lengthy. Can I argue O(|V| + |E|) in a very simply way? e.g. checking each edge at most once? Also what does O(|V| + |E|) imply?I know Dijstrka algorithm and many other algorithm is somewhat like BFS. Does it imply automatically they can be run in |V| + |E| is the lower bound?
What simple arguments and insights can I observe that running both BFS and DFS can be achieved in O(|V| + |E|)?
graphs;algorithm analysis;runtime analysis;graph traversal
null
_softwareengineering.211878
I'm rereading this http://docs.python.org/2/howto/functional.html document and hit this line, '...Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe theres an error in it, and you wrongly believe youve proved the program correct.'/Emphasis mine on the Python interpreter part/What does that mean that the Python Interpreter cannot be proven correct? Is that because it would be a long proof or that it in principal can't be proven correct, ala Godel like theorem? Is using the Interpreter then a useful fiction that all the while we use it, it could be wrong all the while, and what would being wrong mean? I mean, the interpreter has given me correct answers on integral arithmetic, so far...Clarification much appreciated.
Clarification of Python Functional document
python
It can be done (theoretically) but you'd need a full formal specification of the Python language and the Python interpreter internals. After that you'd need to prove the implementation matches the specification and you'd need to prove the specification adheres to all desired properties (e.g., all possible executions behave in certain ways).As you can see, that's a massive task and not practical. It also involves updating the specification with every commit, patch or configuration change related to the interpreter. So when you've finally proved a version of the Python interpreter correct it would already be out of date.
_cstheory.3167
I'm reading this paper, A simple NP-hard problem by Demontis, where he defines an interesting $NP$-hard set and finally he conclude with this theorem:Theorem: $P=NP$ if and only if it is possible to calculate in polynomial time all the fundamental elements of any formula.The paper does not have an abstract and I'm kind of lost because of the new terminology used in the paper.Could you explain the significance of this paper? Do the fundamental elements of a formula represent the variables that have true value in every satisfying assignment? Does this theorem represent a new result? What are the insights into the $P$ vs $NP$ problem presented in the paper? ACM SIGACT News, Volume 40 Issue 2, June 2009
A simple NP-hard problem
cc.complexity theory
null
_cs.22939
If someone (off-topic) asks a question (on-topic) like this:Suppose that he claims that $\mathcal{P=NP}$. Suppose that someone else (on-topic) gives him an instance of an NP-complete problem that cannot be solved by any computer optimally, i.e., to get the optimal solution, one must run an algorithm for very long time (the age of the universe for example).If this someone (off-topic) solves this instance very fast optimally. Because the problem is NP-complete, we know that it can be easily verified. Can we verify easily that it is the optimal solution or we can only verify that it is just a solution?In the other hand, if this someone (off-topic) solves every instance (hard instances) of an NP-hard problem very fast. Can we claim that he proved that $\mathcal{P=NP}$?I want an answer, not a vote up/down or on/off-topic.
If I solve hard instance, therefore I prove NP=P?
complexity theory;p vs np
$\mathrm{P}$ and $\mathrm{NP}$ are both sets of languages. A language $A \subseteq \Sigma^{\star}$ is in $\mathrm{P}$ ($\mathrm{NP}$), if and only if there exists a deterministic (nondeterministic) turing machine $M$, that can decide in polynomial time for all $x \in \Sigma^\star$, whether $x \in A$.There is an alternative definition of $\mathrm{NP}$: $A \subseteq \Sigma^\star$ is in $NP$, if there is an language $L_0 \in \mathrm{P}$ and an polynom $p(x)$, such that $A = \left\{ x \mid \exists y \text{ with } |y| \leq p(|x|) \text{ and } x\#y \in L_0 \right\}$ That $y$ is called proof (or witness) that $x$ is in $A$. For example, the satisfiability problem is to check whether a given boolean formula is satisfiable or not. $\mathrm{SAT}$ is the language of all satisfiable boolean formula. Given a boolean formula $\phi$ (a instance of the satisfiability problem), we want to check whether $\phi$ is satisfiable (if $\phi \in \mathrm{SAT}$). A witness for $\phi$ is an interpretation. We can determine in polynomial time, whether the interpretation of that formula is true or false.Suppose that someone else (on-topic) gives him an instance of an NP-complete problem that cannot be solved by any computer optimally, i.e., to get the optimal solution, one must run an algorithm for very long time (the age of the universe for example)For descition problems, there no such thing as an optimal solution. The answer is yes or no (since the question is whether a string over an alphabet is in the language or not). Also, just because an algorithm runs for a very long time does not imply that the problem is in $\mathrm{NP}$: Consider the worst case time complexity of something like $n^{100}$, which is even for small input sizes very high, but in $\mathrm{P}$.But lets consider we give him an instance of an $\mathrm{NP}$-complete problem, for example of the satisfiability problem:If this someone (off-topic) solves this instance very fast optimally. Because the problem is NP-complete, we know that it can be easily verified.Can we verify easily that it is the optimal solution or we can only verify that it is just a solution?Again, for descition problems there is no such thing as an optimal solution. Therefore, we can verify an solution in polynomial time.In the other hand, if this someone (off-topic) solves every instance (hard instances) of an NP-hard problem very fast. Can we claim that he proved that P=NP?If he presents us an (correct) deterministic polynomial time algorithm, the answer is yes. Theoretically, he could just got lucky everytime and guess a correct solution, or own a non-deterministic turing machine. Since there is an infinite amount of $\mathrm{NP}$-complete problems and only limited time, there is no way of solving all instances. Also, for only a finite amount of instances, one could use an (huge) lookup table.For futher information regarding the $\mathrm{P}$ vs $\mathrm{NP}$ problem, you could look at the official problem description of the Clay Mathematics Institute.
_unix.158679
Trying to do a mass convert from M4A to OGG in a large music collection, I have:#!/bin/shfor i in `find /home/family/Music -name *.m4a -print0` #do ffmpeg -i $i -acodec libvorbis -aq 6 -vn -ac 2 $i.ogg; do echo $idoneAll of the files will have spaces in their names, the output for the above shows a single file like this:/home/family/Music/TheKooks/InsideIn_InsideOut/06YouDon'tLoveMe.m4aEvery space marks a new line, I thought -print0 would fix this?
Find and for loop
shell script;find;for
null
_unix.66262
I have a confusion to choose the best way for upgrading the OpenSSL on my Linux machine.1*Through the yum Update.*# yum updateI know this will update the entire packages. But If I want to specifically update OpenSSL Can I use # yum update OpenSSL2. Through the commands$ openssl version$ wget http://www.openssl.org/source/openssl-1.0.0i.tar.gz$ tar xzvf openssl-1.0.0i.tar.gz$ cd openssl-1.0.0i$ make clean$ ./config --prefix=/usr/local --openssldir=/usr/local/openssl$ make$ make test$ make installPlease suggest me the best approach.Thanks.
Best way of updating Openssl on Linux machine
linux;yum;linux kernel;openssl
null
_codereview.156147
BackgroundI have process tons of DataFrames with shapes of ~230 columns x ~2000-50000+ rows. Here is an extremely simplified example; numbers colors0 0.03620894806802 1xYellow ; 2xRed 1 0.7641262315308163 2xYellow ; 1xOrange 2 0.5607449770945651 3xYellow ; 2xGreen 3 0.6714547913365702 1xYellow ; 1xRed 4 0.8646309438322237 2xYellow ; 1xRed ProblemI need to break the colors column down to a set that looks like this;{'Green', 'Orange', 'Red', 'Yellow'}. The example code below can do this but it is painfully slow on huge DataFrames.import reimport pandas as pdimport numpy as np# Generating example datacolor = [1xYellow ; 2xRed , 2xYellow ; 1xOrange , 3xYellow ; 2xGreen , 1xYellow ; 1xRed , 2xYellow ; 1xRed ]numbers = np.random.rand(len(color))ex_df = pd.DataFrame(np.array([numbers,color]).T, columns = [numbers,colors])# Compile the regex to apply with findallrx = re.compile(x(\w+)\s)just_colors = ex_df.colors.apply(rx.findall)# Below is the painfully slow operation that needs optimization. present_colors = set(sum(just_colors,[]))QuestionIs there a better method out there for pulling unique terms out of a pandas series?
Extract unique terms from a PANDAS series
python;performance;regex;numpy;pandas
It doesn't look like you really need regular expressions. This construct just using basic string operations is about 10x faster than the construct with the regular expressions:present_colors = set()for value in ex_df['colors'].values: for color in [x.strip() for x in value.split(';')]: present_colors.add(color.split('x')[-1])And a bit faster yet, go with the same code as a generator using itertools:import itertools as itpresent_colors = set(it.chain.from_iterable( ([color.split('x')[-1].strip() for color in value.split(';')] for value in ex_df['colors'].values)))
_unix.303422
My os is debian8.cat /etc/group |grep 'debian8'root:x:0:debian8debian8:x:1000:debian8 is the member of root group.cat /etc/sudoersroot ALL=(ALL:ALL) ALL%sudo ALL=(ALL:ALL) ALLdebian8 ALL=(ALL:ALL)ALLdebian8 can execute any commands as root.root@hwy:/home/debian8# find / -name 'vimrc'/home/debian8/openwrt/feeds/packages/utils/vim/files/vimrc/root/openwrt/feeds/packages/utils/vim/files/vimrc/usr/share/vim/vimrc/etc/vim/bundle/Vundle.vim/test/vimrc/etc/vim/bundle/vundle/test/vimrc/etc/vim/vimrcNo Cannot chdir into mountpoint output. root@hwy:/home/debian8# sudo find / -name 'vimrc'Cannot chdir into mountpoint./home/debian8/openwrt/feeds/packages/utils/vim/files/vimrc/root/openwrt/feeds/packages/utils/vim/files/vimrc/usr/share/vim/vimrc/etc/vim/bundle/Vundle.vim/test/vimrc/etc/vim/bundle/vundle/test/vimrc/etc/vim/vimrcCannot chdir into mountpoint.root@hwy:/home/debian8# su debian8debian8@hwy:~$ sudo find / -name 'vimrc'[sudo] password for debian8:Cannot chdir into mountpoint./home/debian8/openwrt/feeds/packages/utils/vim/files/vimrc/root/openwrt/feeds/packages/utils/vim/files/vimrc/usr/share/vim/vimrc/etc/vim/bundle/Vundle.vim/test/vimrc/etc/vim/bundle/vundle/test/vimrc/etc/vim/vimrcCannot chdir into mountpoint.Cannot chdir into mountpoint output for the last two situation.Why there are two lines output Cannot chdir into mountpoint. ?@Julie,here is what i get . debian8@hwy:~$ cd /tmpdebian8@hwy:/tmp$ cdNothing output.debian8@hwy:~$ cd /tmpdebian8@hwy:/tmp$ sudo bash -c cd /Cannot chdir into mountpoint.Cannot chdir into mountpoint. Now there are two lines output Cannot chdir into mountpoint. root@hwy:~# cd /tmproot@hwy:/tmp# sudo su -;Signature not found in user keyringPerhaps try the interactive 'ecryptfs-mount-private'Signature not found in user keyringPerhaps try the interactive 'ecryptfs-mount-private'
Why Cannot chdir into mountpoint?
mount;find
null
_softwareengineering.235719
For an API I'm building what it does is load an XML file that is passed to it as a string, drill to the correct element, modify values, and return the modified XML.I'm doing something like this in my codeif (valid){ XDocument docRoot = XDocument.Parse(XMLstring); var node1 = docRoot.Descendants(namespace + @node1); foreach (var result in node1) { var child1 = result.Descendants(ns + child1); var test = child1.First(); test.SetValue(Transform(test.Value)); } //return the transformed XML}else { }Now I want to create a configuration file in XML format that allows user to specify which nodes in the XML to modify and what modification to perform, (later I want to make use of this in a GUI)so something like<root Value=> <Modify Xpath=\parent\child1\superchild\ Attribute= Mode=delete /> <Modify Xpath=\parent\child2\ Attribute=Value Mode=multiply /></root>And I have these two pieces but don't know how to connect them together. I think I have to make a class from my XML configuration file and somehow map those to the values in the other XML.
Executing user configuration settings
c#;.net
null
_cstheory.12404
Suppose I have four sets A={0, 4, 9}, B={2, 6, 11}, C={3, 8, 13}, and D={7, 12}.I need to choose exactly one number from each of these sets, so that the difference between the largest and smallest chosen numbers is as small as possible. What type of problem is this? Is there a graph algorithm that could be used to solve this problem?
Choosing one number from each set so that the difference between maximum and minimum is minimized
ds.algorithms;graph algorithms
It's not really a graph problem, I think. Problems in which you try to choose some objects to minimize the difference between the min and max chosen object are called minimum range problems e.g. look up minimum range cut, which is a graph problem but this one looks like you're trying to find the minimum range basis of a partition matroid with one partition set for each of your groups.In general minimum range matroid basis problems can be solved in $O(n\log n)$ time, plus $O(n)$ steps of a subroutine that finds a basis of a set with corank one: sort the elements from smallest to largest and then process the elements one by one. While you process the elements maintain an independent set $I$; when you process an element $e$, add $e$ to $I$ and, if that addition causes $I$ to become dependent, kick out the minimum weight element in the unique circuit of $I$. The minimum range basis is one of the sets $I$ that you found in this process: the one that has full rank and has as small a range between min and max as possible.For your partition matroid special case it's easy to find the circuit in $I$ when it becomes dependent: a circuit happens when $e$ belongs to the same group as an element $f$ that you previously added, and $f$ is the element you should kick out of $I$. So the whole algorithm takes $O(n\log n)$ time, or possibly faster depending on how much time it takes to do the sorting step.
_codereview.65169
bd is a bash script to conveniently jump multiple directory levels up from the current working directory instead of a tedious and possibly inaccurate cd ../../../..Say, for example, that you are in the directory /home/user/project/src/org/main and you want to jump to project. Instead of counting the necessary levels to jump and typing cd ../../.., you can do bd -s pro (where -s is to match the start of the directory name, in this example pro for project).I came across this script in another question, and looking at the github repository I decided to jazz it up a little. But before going ahead and refactoring it, I wanted to make sure I'm not breaking anything, so I needed some sort of unit tests as a sane baseline first.This is the main function in the bd script under testing,and this is not for code review,I'm including it here only for your reference in case it helps in some way:# NOT for code review: the reference implementation under testnewpwd() { OLDPWD=$1 if [ $2 = -s ] then NEWPWD=`echo $OLDPWD | sed 's|\(.*/'$3'[^/]*/\).*|\1|'` index=`echo $NEWPWD | awk '{ print index($0,/'$3'); }'` elif [ $2 = -si ] then NEWPWD=`echo $OLDPWD | sed 's|\(.*/'$3'[^/]*/\).*|\1|I'` index=`echo $NEWPWD | awk '{ print index(tolower($0),tolower(/'$3')); }'` else NEWPWD=`echo $OLDPWD | sed 's|\(.*/'$2'/\).*|\1|'` index=`echo $NEWPWD | awk '{ print index($1,/'$2'/); }'` fi}What I'd like reviewed is my implementation of unit tests to verify the behavior of the newpwd function inside the bd script:#!/bin/bash# loading the newpwd function from the bd script, a necessary ugliness for now. bd nonexistent > /dev/nullsuccess=0failure=0total=0assertEquals() { ((total++)) expected=$1 actual=$2 if [[ $expected = $actual ]]; then ((success++)) else ((failure++)) echo Assertion failed: $expected != $actual >&2 caller 0 echo fi}sample=/home/user/project/src/org/main/site/utils/file/reader/whatever# test run with no argsnewpwd $sampleassertEquals $sample $NEWPWDassertEquals 0 $index# test run with exact matchnewpwd $sample srcassertEquals /home/user/project/src/ $NEWPWDassertEquals 19 $index# test run with prefix but no -s so not foundnewpwd $sample srassertEquals $sample $NEWPWDassertEquals 0 $index# test run with prefix foundnewpwd $sample -s srassertEquals /home/user/project/src/ $NEWPWDassertEquals 19 $index# test run with prefix not found because case sensitivenewpwd $sample -s SrassertEquals $sample $NEWPWDassertEquals 0 $index# test run with prefix found thanks to -sinewpwd $sample -si SrassertEquals /home/user/project/src/ $NEWPWDassertEquals 19 $indexsample='/home/user/my project/src'# test run with space in dirnamenewpwd $sample -s myassertEquals '/home/user/my project/' $NEWPWDassertEquals 11 $indexred='\e[0;31m'green='\e[0;32m'nocolor='\e[0m'echo[[ $failure = 0 ]] && printf $green || printf $redecho Tests run: $total ($success success, $failure failed)printf $nocolorechoMy questions:Is this easy to read? If not, how to improve it?Is this a good way to test stuff in Bash? Is there a better way? I'd rather not add external dependencies to the project though, I'm looking for something ultra-light, or a techniqueAre there any corner cases I missed?Any other improvement ideas?
Unit testing a bash script manipulating the working directory path
unit testing;bash;file system
Just 2 cents:I'd quote the right hand side of the [[ ... = ... ]] to avoid pattern interpretation. Cf.x=123y=*2*[[ $x = $y ]] && echo Equal without quotes[[ $x = $y ]] || echo Not equal with quotesI like naming the tests. I'd probably add a third parameter to assertEquals and include it in the report. It also improves readability. Inspired by Test::More for Perl.
_unix.86143
I'm trying to start the rngd daemon by remotely starting it via ssh. Unfortunately it does not seem to run until I log onto the machine. The command I'm using is:ssh -n -o StrictHostKeyChecking=no -i ... user@host sudo rngd \ -r /dev/urandom -o /dev/random -t 10`When I call cat /proc/sys/kernel/random/entropy_avail I get low (150ish) values which makes me think that rngd is not running. However if I log onto the box, wait a few seconds and check, the pool is full (3000s).
Daemon not running when started over ssh
linux;random
null
_codereview.133715
I've just started to teach myself Rust. I've written the following code to read a text file and store the contents in a String. Is this the typical way of doing this? Can anyone suggest any improvements to this?use std::fs::File;use std::io::Read;use std::io;fn main() { let file_name = test.txt; let mut file_contents = String::new(); match get_file_contents(file_name, &mut file_contents) { Ok(()) => (), Err(err) => panic!({}, err) }; println!({}, file_contents);}fn get_file_contents(name: &str, mut contents: &mut String) -> Result<(), io::Error> { let mut f = try!(File::open(name)); try!(f.read_to_string(&mut contents)); Ok(())}
Read file contents to string safely
strings;io;rust
You could return the string directly:fn main() { let file_name = test.txt; let file_contents = match get_file_contents(file_name) { Ok(s) => s, Err(err) => panic!({}, err) }; println!({}, file_contents);}fn get_file_contents(name: &str) -> Result<String, io::Error> { let mut f = try!(File::open(name)); let mut contents = String::new(); try!(f.read_to_string(&mut contents)); Ok(contents)}and unwrap if you dont intend to handle the error usefully:let file_contents = get_file_contents(file_name).unwrap();
_unix.92799
I am trying to connect to my WEP network just using the command-line (Linux).I run:sudo iwconfig wlan0 mode Managed essid 'my_network' key 'xx:xx:... hex key, 26 digits'Then I try to obtain an IP withsudo dhclient -v wlan0orsudo dhclient wlan0without success (tried to ping google.com).I know that the keyword is right, and I also tried with the ASCII key using 's:key', and again, the same result.I get the message below when running dhclient:Listening on LPF/wlan0/44:...Sending on LPF/wlan0/44:...Sending on Socket/fallbackDHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 3 I have no problem connecting with WICD or the standard Ubuntu tool.
Connecting to wifi network through command line
command line;networking;wifi
null
_unix.359438
The manpage for ps says the following about what ps do when used alone (without flags):By default, ps selects all processes with the same effective user ID (euid=EUID) as the current user and associated with the same terminal as the invoker. It displays the process ID (pid=PID), the terminal associated with the process (tname=TTY), the cumulated CPU time in [DD-]hh:mm:ss format (time=TIME), and the executable name (ucmd=CMD). Output is unsorted by default.So this documentation explicitly states that if ps is used alone, then it will only list the processes that are associated with the terminal that executed ps.Now the documentation for the flags that lists the processes (for example: -e) don't say anything about whether a certain flag lists the processes that are associated with the terminal that executed ps or if it lists all the processes on the system.My question is, can I assume that if the documentation for a certain flag does not say what processes it lists, does that mean that it lists all the processes on the system?Edit: this is what the documentation for the -e flag says:-e Select all processes. Identical to -A.Does it mean it lists all the processes for all users as well as all the processes on the system?
How does ps works when used with flags?
linux;ps
null
_codereview.139942
Problem statement : There is a windmill which collects and stores wind data for various cities. The data is maintained in an xml file by the aggregator part of windmill. Now I am trying to implement the publisher part of the mill.The responsibility of publisher is to notify the registered clients for their respective subscribed cities at registered interval of time for ex :a. Client 1 registers for city DELHI and NOIDA at a refresh rate of 5 sec.b. client 2 registers for city BANGLORE and MUMBAI at refresh rate of 3 sec.The minimum refresh rate can be 1 Sec.The publisher also reads/receives the data from the xml file at rate of 100 ms.The publisher should notify clients about wind speed and wind direction.Lets say the format of xml in which the data is stored is :<CityList><City name=Delhi WindSpeed=50 WindDirection=2/> <City name=Noida WindSpeed=43 WindDirection=1/><City name=Banglore WindSpeed=54 WindDirection=3/><City name=Mumbai WindSpeed=21 WindDirection=2/></CityList>Where name is the name of city ,WindSpeed is the speed of wind and windDirection can 0,1,2,3 denoting NE,NW,SE,SW direction of wind.My Solution : This seems to me to be an observer pattern type problem, Hence I took the help and overview of observer pattern from stackexchange answer.The observer class :EventType Denotes the city for which the WindData [ Event ] is being sent.#ifndef _OBSERVER_#define _OBSERVER_struct Windata;enum class EventType{ DELHI, NOIDA, BANGLORE, MUMBAI};class Observer{public: virtual void onEvent(EventType const &,Windata const &) = 0;};#endifAlso for the periodic timer the implementation is taken from this link of stackoverflow.#include <functional>#include <chrono>#include <future>#include <atomic>class CallBackTimer{public: CallBackTimer() :_execute(false) {} ~CallBackTimer() { if (_execute.load(std::memory_order_acquire)) { stop(); }; } void stop() { _execute.store(false, std::memory_order_release); if (_thd.joinable()) _thd.join(); } template <class callable, class... arguments> void start(int interval, callable&& f, arguments&&... args) { if (_execute.load(std::memory_order_acquire)) { stop(); }; _execute.store(true, std::memory_order_release); std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...)); _thd = std::thread([this, interval, task]() { while (_execute.load(std::memory_order_acquire)) { std::this_thread::sleep_for(std::chrono::milliseconds(interval)); task(); } }); } bool is_running() const { return (_execute.load(std::memory_order_acquire) && _thd.joinable()); }private: std::atomic<bool> _execute; std::thread _thd;};The Wind Mill [ subject ] :#ifndef _SUBJECT_#define _SUBJECT_#include observer.h#include Event.h#include Timer.h#include pugixml.hpp#include <vector>#include <iostream>#include <memory>#include <map>#include <string>#include <mutex>enum class WindDirection{ NE, NW, SE, SW};struct Windata{ int speed; WindDirection dir;};class WindMill_Publisher{ struct ClientDetials { std::vector<EventType> cities; Observer * handle{ nullptr }; long refresh_interval{ 0 }; long saved_refresh_interval{ 0 }; }; std::vector <std::unique_ptr<ClientDetials>> clients; std::map<EventType, Windata> cityData; CallBackTimer refresh_timer; int client_refesh_rate = 1000;//1 sec std::map<std::string, EventType> citycodemap; CallBackTimer update_timer; int update_refresh_rate = 100;//100ms std::mutex cityMutex;public: WindMill_Publisher() { setCityCodes(); readCityData(); update_timer.start(update_refresh_rate, std::bind(&WindMill_Publisher::readCityData, this)); } void registerClient(Observer& observer, std::vector<EventType> cities,long refresh_interval_sec) { for (auto const & myclient : clients) { if (myclient->handle == &observer) throw std::runtime_error(client already registered); } std::unique_ptr<ClientDetials> newclient(new ClientDetials()); newclient->handle = &observer; newclient->cities = cities; newclient->refresh_interval = refresh_interval_sec; newclient->saved_refresh_interval = refresh_interval_sec; clients.push_back(std::move(newclient)); if (clients.size() == 1) { refresh_timer.start(client_refesh_rate, std::bind(&WindMill_Publisher::notifyClients, this)); } } void unregisterClient(Observer& observer) { auto clientitr = clients.begin(); while (clientitr != clients.end()) { if ((*clientitr)->handle = &observer) { clientitr = clients.erase(clientitr); } else { ++clientitr; } } if (clients.size() == 0) { refresh_timer.stop(); } }private: Windata& getCityData(EventType const & city) { std::lock_guard<std::mutex> lock(cityMutex); auto find = cityData.find(city); if (find != cityData.end()) return find->second; } void notifyClients() { for (auto const & myclient : clients) { if (myclient->refresh_interval <= 0) { for (auto myclientcities : myclient->cities) { if (myclient->handle) myclient->handle->onEvent(myclientcities, getCityData(myclientcities)); } myclient->refresh_interval = myclient->saved_refresh_interval; } myclient->refresh_interval -= (client_refesh_rate/ 1000); } } bool readCityData() { pugi::xml_document doc; std::string path = ...\\Citylist.xml; pugi::xml_parse_result res = doc.load_file(path.c_str()); if(!res) { std::cout << unable to load xml file << static_cast<int>(res.status)<<\n; return false; } pugi::xml_node cities = doc.child(CityList); for (pugi::xml_node city = cities.child(City); city; city = city.next_sibling(City)) { std::string name = city.attribute(name).value(); int speed = city.attribute(WindSpeed).as_int(); int dir = city.attribute(WindDirection).as_int(); auto findcity = citycodemap.find(name); if (findcity != citycodemap.end()) { Windata data; data.speed = speed; data.dir = static_cast<WindDirection>(dir); updateCityData(findcity->second, data); } } return true; } void updateCityData(EventType city, Windata data) { std::lock_guard<std::mutex> lock(cityMutex); cityData[city] = data; } void setCityCodes() { citycodemap[Delhi] = EventType::DELHI; citycodemap[Noida] = EventType::NOIDA; citycodemap[Banglore] = EventType::BANGLORE; citycodemap[Mumbai] = EventType::MUMBAI; }};#endifExplanation about windmill : It contains A vector of struct ClientDetials which in turn hold the vector of EventType [cities] for which client wants notification, a handle to client and refresh interval. There are two refresh interval which i will explain in a moment.2.A map of cityData which hold latest updated data for all the cities3.It has two periodic timers refresh_timer and update_timer with period of 1 sec and 100 ms respectively.The refresh_timer has period of 1 sec, and at every cycle it checks weather the refresh_interval of any client has become 0. if it becomes zero it notifies the client and update the refresh_interval with saved_refresh_interval.Another approach in my mind was to have an separate periodic timer for each client but that seemed like much overhead. I am not sure but i chose this way.I also tried to use std::type_index as key but was unable to implement it correctly. The update_timer is for reading the updated data from xml file.For reading the data from xml pugixml is used.The client or test :#include <iostream>#include <vector>#include Observer.h#include Subject.hclass Client_1 :public Observer{public: std::vector<EventType> cities; Client_1(){ cities.push_back(EventType::DELHI); cities.push_back(EventType::NOIDA); } void onEvent(EventType const &city,Windata const &data) { std::cout << Client_1 called for city : << static_cast<int>(city) << with wind speed : << data.speed << and direction : << static_cast<int>(data.dir) << std::endl; }};class Client_2 :public Observer{public: std::vector<EventType> cities; Client_2(){ cities.push_back(EventType::BANGLORE); cities.push_back(EventType::MUMBAI); } void onEvent(EventType const &city, Windata const &data) { std::cout << Client_2 called for city : << static_cast<int>(city) << with wind speed : << data.speed << and direction : << static_cast<int>(data.dir) << std::endl; }};int main(){ Client_1 c1; Client_2 c2; WindMill_Publisher mill; try { mill.registerClient(c1, c1.cities, 5); mill.registerClient(c2, c2.cities, 3); } catch (std::runtime_error &e) { std::cout << e.what()<<std::endl; } while (1) { } return 0;}The cities vector in client is public just for the ease of testing. Also VS2013 was not supporting the list initialization ,so i had to initialize the vector in the constructor.I have certain doubts like : [In bold are the suggestion as per @Edward]Is it too much overhead for publisher class. The timer management and to notify client at refresh_rate should be delegated too another class. : Yes , may be use priority queue.Should I use separate timer for every client or is there a better way to do it without timers at all. : The timer sleep and wake up time can managed using priority queue rather than every 1 sec.Are the Event type and other enums for handling events and data used properly. : Use shared pointers and take care of typos Is it better approach to have a function pointer from client for callback [as in the stackexchange link] rather than having client overload pure virtual function. : Yes, function pointers approach seems to be a better designThanks.
WindMIll Data Publisher using observer pattern
c++;observer pattern
Here are some things that may help you improve your program.Compile with warnings turned onWhen I attempted to compile the project, it told me that this line was suspect:if ((*clientitr)->handle = &observer){ clientitr = clients.erase(clientitr);}Indeed, looking at the context, the condition within the if should be == instead of =. Your compiler can help you spot subtle bugs, so you should get into the habit of turning the warning levels all the way up.Ensure every control path returns a proper valueThe WindMill_Publisher::getCityData() routine returns a reference to a Windata structure under some set of conditions but then doesn't return anything at all otherwise. This is an error. The function must always return a valid reference. If it is not always possible, then the code should be changed to handle the error, as with returning a pointer and then having the caller check for nullptr.Separate interface from implementationThe interface is the part in the .h file and the implementation is in the .cpp file. Users of this code should be able to read and understand everything they need from the implementation file. That means that, for example, the Subject.h file should be separated into two pieces: the interface (only) and the implementation (only). Having all of the code in the .h file defeats much of the purpose of having header files at all.Fix spelling errorsThe code has ClientDetials instead of ClientDetails and Banglore instead of Bangalore. These kinds of typos don't bother the compiler at all, but will bother human readers of the code and make it a little more difficult to understand and maintain.Prefer throw rather than printing to coutThe current code includes this line within WindMill_Publisher::readCityData():if(!res){ std::cout << unable to load xml file << static_cast<int>(res.status)<<\n; return false;}There are a few problems with this. First, the return value is never checked within the constructor, so the result is that the data may or may not have been correctly initialized. The second problem is that it's probably better and easier to simply throw an error from within the function. This helps assure that the created WindMill_Publisher object is valid if no exceptions were thrown.Don't repeat yourselfThe only difference between Client_1 and Client_2 is the data contained, so they should be different instances but the same class. This can easily be done by passing the required data in via a constructor. Even if your compiler doesn't support initializer lists, you can create an external function to allow adding of cities to the object.Be careful with concurrencyAs written, the code passes a reference to an Observer class to the registerClient class and then a pointer to that reference is stored within WindMill_Publisher. That's a serious problem because there is nothing to prevent the passed object from getting deleted after registration. The result is that the callback will attempt to reference a deleted object's member pointer which is not likely to be what you want. Instead, either create a copy and store that or use a std::shared_ptr.Don't overcomplicate the designThere really isn't much need for the Observer class. All that's really required for the callback is a function pointer. This could be done just as well by passing in a freestanding function. It seems to me that this would make for a somewhat more flexible interface.Consider a different approachI find the code for the WindMill_Publisher to be much more complex than it needs to be. Fundamentally, there are a few different things happening. There is first, a data structure that holds current city data and this data structure is asynchronously updated from an external XML file. Next, there is the publisher of this code which sends updated data to each registered client. I would probably want to separate these a little more cleanly. Further, rather than waking up periodically to check the timers, this is a good candidate for a priority queue. Here's how that might work. Calculate the deadlines for all notifications and store them in a priority queue. Then set the alarm for the item at the front of the queue. Example: if there are three items with deadlines that are 2, 5 and 7 seconds away, have the application sleep for 2 seconds. When it wakes, it handles the item at the top of the queue and recalculates. The next item is due 3 seconds later, so it sleeps for 3 seconds, etc. The queue then only needs to be adjusted when either a node is registered or unregistered and when the application wakes up. To avoid sleeping and then waking immediately, process the queue until there are no more items for the current second.Omit return 0When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main. Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments: I didn't know that. or That's bad advice! My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard. For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:[...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;All versions of both standards since then (C99 and C++98) have maintained the same idea. We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function. Reasons against omitting seem to boil down to it looks weird. If, like me, you're curious about the rationale for the change to the C standard read this question. Also note that in the early 1990s this was considered sloppy practice because it was undefined behavior (although widely supported) at the time. So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.
_unix.31378
When I restart httpd, I get the following error. What am I missing?[root@localhost ~]# service httpd restartStopping httpd: [ OK ]Starting httpd: Syntax error on line 22 of /etc/httpd/conf.d/sites.conf:Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configurationI have installed mod_ssl using yum install mod_ssl opensshPackage 1:mod_ssl-2.2.15-15.el6.centos.x86_64 already installed and latest versionPackage openssh-5.3p1-70.el6_2.2.x86_64 already installed and latest versionMy sites.conf looks like this<VirtualHost *:80># ServerName shop.itmanx.com ServerAdmin [email protected] DocumentRoot /var/www/html/magento <Directory /var/www/html> Options -Indexes AllowOverride All </Directory> ErrorLog logs/shop-error.log CustomLog logs/shop-access.log</VirtualHost><VirtualHost *:443> ServerName secure.itmanx.com ServerAdmin [email protected] SSLEngine on SSLCertificateFile /etc/httpd/ssl/secure.itmanx.com/server.crt SSLCertificateKeyFile /etc/httpd/ssl/secure.itmanx.com/server.key SSLCertificateChainFile /etc/httpd/ssl/secure.itmanx.com/chain.crt DocumentRoot /var/www/html/magento <Directory /var/www/html> Options -Indexes AllowOverride All </Directory> ErrorLog logs/shop-ssl-error.log CustomLog logs/shop-ssl-access.log </VirtualHost>
apache2 Invalid command 'SSLEngine'
ssl;apache httpd
Probably you do not load the ssl module. You should have a LoadModule directive somewhere in your apache configuration files.Something like: LoadModule ssl_module /usr/lib64/apache2-prefork/mod_ssl.soUsually apache configuration template has (on any distribution) a file called (something like) loadmodule.conf in which you should find a LoadModule directive for each module you load into apache at server start.
_unix.314903
I disallowed users to launch tc binary from standard location but if they download it from network to home directory they can view traffic control settings. How can I disallow interaction between tc (launched as non-root) and kernel?
How to block Traffic Control (tc) operation if started as non-root?
permissions;tc
null
_codereview.74439
I am trying to create a unique name for my uploaded images. It works, but I wonder whether I should make a few changes or not.HTML <form action=upload.php method=post enctype=multipart/form-data name=uploadform> <input type=hidden name=MAX_FILE_SIZE value=350000> <input name=picture type=file id=picture size=50> <input name=upload type=submit id=upload value=Upload Picture!> </form>PHP// if something was posted, start the process... if (isset($_POST['upload'])) {// define the posted file into variables $name = $_FILES['picture']['name']; $tmp_name = $_FILES['picture']['tmp_name']; $type = $_FILES['picture']['type']; $size = $_FILES['picture']['size'];// if your server has magic quotes turned off, add slashes manually if (!get_magic_quotes_gpc()) { $name = addslashes($name); }// open up the file and extract the data/content from it $extract = fopen($tmp_name, 'r'); $content = fread($extract, $size); $content = addslashes($content); fclose($extract);// connect to the database include ../cn/connect.php; $name = md5($name); $name = $name . uniqid($name); $path = $_FILES['picture']['name']; $ext = pathinfo($path, PATHINFO_EXTENSION); $name = $name...$ext;// the query that will add this to the database $stmt = $sqli->prepare(INSERT INTO image1(name, type, size) VALUES (?,?,?)); $stmt->bind_param(sss, $name, $_FILES['picture']['type'], $_FILES['picture']['size']); $stmt->execute(); $stmt->close(); echo Mission has been completed, sir!; if (!empty($_FILES)) { $target = upload/; $target = $target . basename($_FILES['picture']['name']); $ok = 1; $picture_size = $_FILES['picture']['size']; $picture_type = $_FILES['picture']['type']; //This is our size condition if ($picture_size > 5000000) { echo Your file is too large.<br>; $ok = 0; } //This is our limit file type condition if ($picture_type == text/php) { echo No PHP files<br>; $ok = 0; } //Here we check that $ok was not set to 0 by an error if ($ok == 0) { Echo Sorry your file was not uploaded; } //If everything is ok we try to upload it else { if (move_uploaded_file($_FILES['picture']['tmp_name'], $target)) { echo The file . basename($_FILES['picture']['name']) . has been uploaded <br/>; } else { echo Sorry, there was a problem uploading your file.; } } } echo Successfully uploaded your picture!;} else { die(No uploaded file present);}
Creating unique names for uploaded images
php
It looks like your code works fine, so these comments are my opinion on how I would handle this if I were in your shoes.This is a pretty standard requirement. Users upload images, and you want to save them with a filename that is (a) unique, and (b) won't cause you grief down the road with funny characters in the file name.You also need to handle the case where people upload files with the same name over and over again, without creating duplicates. For instance, for a certain model of camera the first photo on the camera roll might always have the same name. Several people might own the same model of camera. Or, dissatisfied with the results of uploading an image, the user edits it locally and uploads a fresh copy. With the same file name as before.The simplest solution is to skip all the md5 and uniqid() stuff, and simply add a record to a database which has an auto-increment ID field. You would add the original name of the image to the database (for future reference, tooltip etc), but not the name of the file on disk. Once you get the new ID, you copy/move/rename the image file based on the new ID. This gives you nice short, simple file names.I think this is tidier than inventing a unique file name before adding the database record. Databases have a built-in unique ID feature, so you can get a unique ID for free! with each new record. Why invent your own?If the name of the image file ends up being used in URL's, so you don't want it to be easily guessable, then you want to mess up the file name to make it more complicated. If this is the case, you are better off placing the files where they are not accessible directly via URL.If you, as an administrator, want to be able to browse through the image files and have the names make sense, or if you want the image names to appear in the URL to assist visitors or for SEO or Google Image search benefits, then you may want to name the images like blog post titles, i.e. simple lower-case-hyphen-separated words with a unique ID on the end. There is lots of code around that will do that for you. (I've got code if you can't find it elsewhere).
_unix.203306
One of my VM machine was rebooted yesterday, but can't find how & who did it.In the log I can only find receiving signal 15, terminated
VM Machine rebooted, can't find how?
linux;virtual machine;vmware;reboot
With vSphere Client you can see every events happened to ESXi vms.Go into your vm operation system and use last|less to check who shutdown your machines.
_webmaster.27631
I have a website that allows people to search for instructors. It's currently working in the USA and UK.I'm wanting to start marketing the website to the Australian market, and so have been looking at registering a .com.au domain name.What is the best way about doin this as it doesn't seem particularly simple? Apparently I need an ABN or an Australian company but as I'm not an Australian citizen this presumably would be impossible?
What is required to register .com.au domains?
domains;domain registration
This is a good blog post about registering .co.au domains as a foreigner, the law firm which posted it links to this page on their site going over how to register a domain
_unix.210367
I want to alter the TCP RTO (retransmission timeout) value for a connection, and some reading I have done suggests that I could do this, but does not reveal where and how to change it. I have looked at the /proc/sys/net/ipv4 variables, but none of the variables is related to RTO. I would appreciate it if someone can tell me how to alter this value.
Changing the TCP RTO value in Linux
linux;linux kernel;tcp
The reason you can't alter the RTO specifically is because it is not a static value. Instead (except for the initial SYN, naturally) it is based on the RTT (Round Trip Time) for each connection. Actually, it is based on a smoothed version of RTT and the RTT variance with some constants thrown into the mix. Hence, it is a dynamic, calculated value for each TCP connection, and I highly recommend this article which goes into more detail on the calculation and RTO in general.Also relevant is RFC 6298 which states (among a lot of other things):Whenever RTO is computed, if it is less than 1 second, then the RTO SHOULD be rounded up to 1 second.Does the kernel always set RTO to 1 second then? Well, with Linux you can show the current RTO values for your open connections by running the ss -i command:State Recv-Q Send-Q Local Address:Port Peer Address:PortESTAB 0 0 10.0.2.15:52861 216.58.219.46:http cubic rto:204 rtt:4/2 cwnd:10 send 29.2Mbps rcv_space:14600ESTAB 0 0 10.0.2.15:ssh 10.0.2.2:52586 cubic rto:201 rtt:1.5/0.75 ato:40 cwnd:10 send 77.9Mbps rcv_space:14600ESTAB 0 0 10.0.2.15:52864 216.58.219.46:http cubic rto:204 rtt:4.5/4.5 cwnd:10 send 26.0Mbps rcv_space:14600The above is the output from a VM which I am logged into with SSH and has a couple of connections open to google.com. As you can see, the RTO is in fact set to 200-ish (milliseconds). You will note that is not rounded to the 1 second value from the RFC, and you may also think that it's a little high. That's because there are min (200 milliseconds) and max (120 seconds) bounds in play when it comes to RTO for Linux (there is a great explanation of this in the article I linked above).So, you can't alter the RTO value directly, but for lossy networks (like wireless) you can try tweaking F-RTO (this may already be enabled depending on your distro). There are actually two related options related to F-RTO that you can tweak (good summary here):net.ipv4.tcp_frtonet.ipv4.tcp_frto_responseDepending on what you are trying to optimize for, these may or may not be useful.EDIT: following up on the ability to tweak the rto_min/max values for TCP from the comments.You can't change the global minimum RTO for TCP (as an aside, you can do it for SCTP - those are exposed in sysctl), but the good news is that you can tweak the minimum value of the RTO on a per-route basis. Here's my routing table on my CentOS VM:ip route10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15 169.254.0.0/16 dev eth0 scope link metric 1002 default via 10.0.2.2 dev eth0I can change the rto_min value on the default route as follows:ip route change default via 10.0.2.2 dev eth0 rto_min 5msAnd now, my routing table looks like this:ip route10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15 169.254.0.0/16 dev eth0 scope link metric 1002 default via 10.0.2.2 dev eth0 rto_min lock 5msFinally, let's initiate a connection and check out ss -i to see if this has been respected:ss -iState Recv-Q Send-Q Local Address:Port Peer Address:Port ESTAB 0 0 10.0.2.15:ssh 10.0.2.2:50714 cubic rto:201 rtt:1.5/0.75 ato:40 cwnd:10 send 77.9Mbps rcv_space:14600ESTAB 0 0 10.0.2.15:39042 216.58.216.14:http cubic rto:15 rtt:5/2.5 cwnd:10 send 23.4Mbps rcv_space:14600Success! The rto on the HTTP connection (after the change) is 15ms, whereas the SSH connection (before the change) is 200+ as before.I actually like this approach - it allows you to set the lower value on appropriate routes rather than globally where it might screw up other traffic. Similarly (see the ip man page) you can tweak the initial rtt estimate and the initial rttvar for the route (used when calculating the dynamic RTO). While it's not a complete solution in terms of tweaking, I think most of the important pieces are there. You can't tweak the max setting, but I think that is not going to be as useful generally in any case.
_unix.211752
I ran sudo apt-get install python-setuptools python-pip but I received:Reading package lists... DoneBuilding dependency tree Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: python-pip : Depends: python-pip-whl (= 1.5.4-1ubuntu3) but it is not going to be installedE: Unable to correct problems, you have held broken packages.i normally only run sudo apt-get install python-pip and it works, i dont know why i decided to try setuptools. i tried going on Synaptic Package Manager, click on Edit in the menu bar, and click on Fix broken packages and the command line sudo dpkg --configure -a and sudo apt-get -f install but i am still unable to install python-pip. i am on linux mint 17 xfce 3.13.0-37-generic, using Python 2.7.6.any help is greatly appreciated. i saw alot of commands online regarding dpkg but im not familiar enough with packages and i do not want to break anything else.updates:sudo apt-cache policy python-pippython-pip: Installed: (none) Candidate: 1.5.4-1ubuntu3 Version table: 1.5.4-1ubuntu3 0 500 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe amd64 Packages 1.5.4-1 0 500 http://archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packagessudo apt-get install python-pip-whlReading package lists... DoneBuilding dependency tree Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: python-pip-whl : Depends: python-requests-whl but it is not installable Depends: python-setuptools-whl but it is not installable Depends: python-six-whl but it is not installable Depends: python-urllib3-whl but it is not going to be installedE: Unable to correct problems, you have held broken packages.update #2$ sudo apt-cache policy python-pip-whl python-requests-whl python-setuptools-whl python-six-whl python-urllib3-whlpython-pip-whl: Installed: (none) Candidate: 1.5.4-1ubuntu1 Version table: 1.5.4-1ubuntu1 0 500 http://archive.ubuntu.com/ubuntu/ trusty-updates/universe amd64 Packagespython-requests-whl: Installed: (none) Candidate: (none) Version table:python-setuptools-whl: Installed: (none) Candidate: (none) Version table:python-six-whl: Installed: (none) Candidate: (none) Version table:python-urllib3-whl: Installed: (none) Candidate: 1.7.1-1ubuntu3 Version table: 1.7.1-1ubuntu3 0 500 http://archive.ubuntu.com/ubuntu/ trusty-updates/main amd64 Packages$ for pkg in python-requests-whl python-setuptools-whl python-six-whl python-urllib3-whl; do sudo apt-get install $pkg; doneReading package lists... DoneBuilding dependency tree Reading state information... DonePackage python-requests-whl is not available, but is referred to by another package.This may mean that the package is missing, has been obsoleted, oris only available from another sourceE: Package 'python-requests-whl' has no installation candidateReading package lists... DoneBuilding dependency tree Reading state information... DonePackage python-setuptools-whl is not available, but is referred to by another package.This may mean that the package is missing, has been obsoleted, oris only available from another sourceE: Package 'python-setuptools-whl' has no installation candidateReading package lists... DoneBuilding dependency tree Reading state information... DonePackage python-six-whl is not available, but is referred to by another package.This may mean that the package is missing, has been obsoleted, oris only available from another sourceE: Package 'python-six-whl' has no installation candidateReading package lists... DoneBuilding dependency tree Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: python-urllib3-whl : Depends: python-six-whl but it is not installableE: Unable to correct problems, you have held broken packages.update #3$ /etc/apt/sources.list#deb cdrom:[Linux Mint 17.1 _Rebecca_ - Release amd64 20150107]/ trusty contrib main non-freeupdate #4$ /etc/apt/sources.list.d $ lltotal 16drwxr-xr-x 2 root root 4096 Jun 21 01:00 .drwxr-xr-x 6 root root 4096 Jun 24 00:52 ..-rw-r--r-- 1 root root 59 Jan 7 12:29 getdeb.list-rw-r--r-- 1 root root 530 Jan 7 12:29 official-package-repositories.list$ cat getdeb.list# deb http://archive.getdeb.net/ubuntu trusty-getdeb apps $ cat official-package-repositories.list# Do not edit this file manually, use Software Sources instead.deb http://packages.linuxmint.com rebecca main upstream import #id:linuxmint_maindeb http://extra.linuxmint.com rebecca main #id:linuxmint_extradeb http://archive.ubuntu.com/ubuntu trusty main restricted universe multiversedeb http://archive.ubuntu.com/ubuntu trusty-updates main restricted universe multiversedeb http://security.ubuntu.com/ubuntu/ trusty-security main restricted universe multiversedeb http://archive.canonical.com/ubuntu/ trusty partnerupdate #5/etc/apt/apt.conf.d $ lltotal 52drwxr-xr-x 2 root root 4096 Jun 24 01:06 .drwxr-xr-x 6 root root 4096 Jun 24 00:52 ..-rw-r--r-- 1 root root 49 Jun 21 00:59 00aptitude-rw-r--r-- 1 root root 41 Jan 7 11:58 00cdrom-rw-r--r-- 1 root root 73 Jan 7 11:58 00recommends-rw-r--r-- 1 root root 40 Jun 21 00:58 00trustcdrom-rw-r--r-- 1 root root 643 Apr 10 2014 01autoremove-rw-r--r-- 1 root root 992 Jan 7 12:23 01autoremove-kernels-rw-r--r-- 1 root root 123 Apr 10 2014 20changelog-rw-r--r-- 1 root root 243 Mar 11 2013 20dbus-rw-r--r-- 1 root root 2331 Apr 2 2014 50unattended-upgrades-rw-r--r-- 1 root root 182 Feb 23 2014 70debconf-rw-r--r-- 1 root root 33 Jun 24 01:06 99synaptic/etc/apt/preferences.d $ lltotal 16drwxr-xr-x 2 root root 4096 Jun 21 01:16 .drwxr-xr-x 6 root root 4096 Jun 24 00:52 ..-rw-r--r-- 1 root root 216 Feb 3 07:15 official-extra-repositories.pref-rw-r--r-- 1 root root 171 Jan 7 12:29 official-package-repositories.pref
Receiving Unable to correct problems, you have held broken packages. after trying to install python -setuptools and python-pip
apt;python
null
_softwareengineering.306695
For an open source project created by 2 authors, is it proper for an MIT License to have two authors?The MIT License (MIT)Copyright (c) 2016 FIRST NAME and SECOND NAME
MIT License - Dual Authors
licensing
Yes.
_unix.297470
mutt runs correctly like this:$ cat /home/user/testthis is a test$ mutt -s test [email protected] </home/user/testIf I put this inside a bash script (stored in tmp1):#!/bin/bash/usr/bin/mutt -s test [email protected] </home/user/testand in cron:00 22 * * * user /bin/bash /home/user/tmp1I see the script getting executed, but mutt doesn't send any email :-/Also adding to mutt -F option:mutt -F /home/user/.muttrc
mutt doesn't run as a cron job wrapped in a bash script
shell script;cron;mutt
null
_cs.80190
Let $G = (V, E)$ be a digraph, and consider the set $\left\{ v \in V \; \middle| \; \left(\{v\} \times V \right) \cap E \neq \varnothing \right\}$, the set of vertices which form edges with other vertices; or if you will, the set of heads of edges.Is there a commonly-used term for this set?
A commonly-used symbol for the set of all heads of directed edges?
graphs;graph theory;reference request;notation
null
_codereview.27145
The working and functional code below is a simplification of a real test application I've written. It acts as a client which asynchronously sends UDP data from a local endpoint and listens for an echo'ed response from a server implemented elsewhere. The requirements are:Send and listen on the same port number;The port number must be able to change (simulates data coming in from various sources)The program does what I want, but I have doubts about its correctness. Specifically regarding the class members of listenThread and udpClient which are reused when the port number changes. Are they implemented, closed and cleaned-up correctly. using System;using System.Net;using System.Net.Sockets;using System.Threading;namespace cs_console{ class Tester { public void Send(string message, int localPort) { PrepareClient(localPort); SendBytes(System.Text.Encoding.UTF8.GetBytes(message)); } private void PrepareClient(int localPort) { if (localEP == null || localEP.Port != localPort) { localEP = new IPEndPoint(IPAddress.Parse(localHost), localPort); listenThread = new Thread(StartListening); listenThread.Start(); } } private void StartListening() { udpClient = new UdpClient(); udpClient.ExclusiveAddressUse = false; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.Client.Bind(localEP); var s = new UdpState(localEP, udpClient); currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s); } private void ReceiveCallback(IAsyncResult ar) { if (ar == currentAsyncResult) { UdpClient c = (UdpClient)((UdpState)(ar.AsyncState)).c; IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e; Byte[] buffer = c.EndReceive(ar, ref e); if (buffer.Length > 0) System.Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer)); UdpState s = new UdpState(e, c); currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s); } } private void SendBytes(byte[] messageData) { var sender = new UdpClient(); sender.ExclusiveAddressUse = false; sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); sender.Client.Bind(localEP); sender.Send(messageData, messageData.Length, remoteEP); sender.Close(); } private static string localHost = 10.27.21.109; private IPEndPoint localEP = null; private IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(localHost), 11000); private Thread listenThread = null; private UdpClient udpClient = null; private IAsyncResult currentAsyncResult = null; private class UdpState : Object { public UdpState(IPEndPoint e, UdpClient c) { this.e = e; this.c = c; } public IPEndPoint e; public UdpClient c; } } class Program { static void Main(string[] args) { Tester tester = new Tester(); int localPort = 2532; while (true) { ++localPort; var message = Console.ReadLine(); tester.Send(message, localPort); } } }}This is as compact a working example as I could make.
Reusing thread and UdpClient for sending and receiving on same port
c#;.net;multithreading;socket
I find a better naming convention for private fields on a class is _PascalCase or _camelCase. This makes it easy to see whether you are using a field or a local variable.It is completely unnecessary to create a new Thread to call StartListening. The thread will terminate once udpClient.BeginReceive() has been called as this is async. You might as well call StartListening() directly in PrepareClient().UdpClient is IDisposable and should therefor be disposed when not needed anymore. You do not clean up the existing UdpClient at all.The answer to this question indicates that when you call Dispose or Close on a socket then the callback is invoked but will throw an ObjectDisposedException when calling EndReceive . Because you are storing the currentAsyncResult you can probably get around this by changing StartListening() to this:private readonly object _clientLock = new object();private void StartListening(){ lock (_clientLock) { if (udpClient != null) { currentAsyncResult = null; updClient.Dispose(); } udpClient = new UdpClient(); udpClient.ExclusiveAddressUse = false; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.Client.Bind(localEP); var s = new UdpState(localEP, udpClient); currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s); }}Plus you should lock the inner block of your receive callback. This should ensure that you don't kill the client in the middle of receiving.
_unix.187808
I constructed a command like this in a bash scripta=my_cmd;a=$a --verbose;echo $a;$a;It works and executes my command correctly. But when I add an environment variable to the mix it breaks.a=my_cmd;a=URL=myurl $a --verbose;echo $a;$a;It breaks at URL=myurl saying No such file or directory, but if I run it using eval() the command works correctly. a=my_cmd;a=URL=myurl $a --verbose;echo $a;eval $a;Can someone kindly explain why adding environment variable to the mix broke my command in second example.
Running a constructed command from bash script
bash;environment variables;variable substitution
When you leave a variable expansion unquoted, it undergoes word splitting and filename expansion (i.e. globbing). It isn't parsed as a shell command. In general, when you dynamically construct a shell snippet to execute, the right way to execute it is eval $a where a contains the string to parse as shell code.In your first snippet, the value of a is the string my_cmd --verbose. Word splitting breaks it into two words my_cmd and --verbose. Globbing does nothing since there are no wildcards in any of the words. The command resulting from the expansion of $a thus consists of two words my_cmd and --verbose, so the command my_cmd (which could be an alias, a function, a builtin or an executable in the PATH) is executed with the single argument --verbose.In the second snippet, things are similar, with three words resulting from the expansion: URL=myurl, my_cmd and --verbose. This results in an attempt to execute the command URL=myurl with two arguments.The shell command URL=myurl my_cmd --verbose is parsed differently: the first word is parsed as an assignment to the variable URL, and since there is a command name after it the assignment sets the environment variable for the duration of the command only. This is part of parsing, not something that's done after expansion, so it requires the equal sign to be part of the shell source code, the equal sign can't be the result of some expansion.Don't store a command with parameters into a string. Use an array. For a complex command, such as one where you set variables or perform redirection in addition to running the command, use a function if at all possible, and if not use eval (taking great care of proper quoting).
_codereview.8634
I have been building my own carousel over the past few days. I am not a jQuery guru, just an enthusiast, and I think my code is a little sloppy, hence the post.Basically what happens is:If someone hits the page with a # values in the URL it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two.If someone clicks the numbers it will show the appropriate slide.Next and prev also slide through the slides.Is there anything I could have written better, as I know there is a lot of duplicate code?if ($slideNumber == 1) { $('#prev').attr(class, not_active) $('#next').attr(class, active)}else if ($slideNumber == divSum) { $('#next').attr(class, not_active); $('#prev').attr(class, active);}else { $('#prev').attr(class, active) $('#next').attr(class, active)};I've made a jsFiddle and included the complete code below:$(document).ready(function () { //////////////////////////// INITAL SET UP ///////////////////////////////////////////// //Get size of images, how many there are, then determin the size of the image reel. var divWidth = $(.window).width(); var divSum = $(.slide).size(); var divReelWidth = divWidth * divSum; //Adjust the image reel to its new size $(.image_reel).css({ 'width': divReelWidth }); //set the initial not active state $('#prev').attr(class, not_active); //////////////////////////// SLIDER ///////////////////////////////////////////// //Paging + Slider Function rotate = function () { var triggerID = $slideNumber - 1; //Get number of times to slide var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide //sets the active on the next and prev if ($slideNumber == 1) { $('#prev').attr(class, not_active) $('#next').attr(class, active) } else if ($slideNumber == divSum) { $('#next').attr(class, not_active); $('#prev').attr(class, active); } else { $('#prev').attr(class, active) $('#next').attr(class, active) }; //Slider Animation $(.image_reel).animate({ left: -image_reelPosition }, 500); }; //////////////////////////// SLIDER CALLS ///////////////////////////////////////////// //click on numbers $(.paging a).click(function () { $active = $(this); //Activate the clicked paging $slideNumber = $active.attr(rel); rotate(); //Trigger rotation immediately return false; //Prevent browser jump to link anchor }); //click on next button $('#next').click(function () { if (!$(.image_reel).is(':animated')) { //prevent clicking if animating var left_indent = parseInt($('.image_reel').css('left')) - divWidth; var slideNumberOn = (left_indent / divWidth); var slideNumber = ((slideNumberOn * -1) + 1); $slideNumber = slideNumber; if ($slideNumber <= divSum) { //do not animate if on last slide rotate(); //Trigger rotation immediately }; return false; //Prevent browser jump to link anchor } }); //click on prev button $('#prev').click(function () { if (!$(.image_reel).is(':animated')) { //prevent clicking if animating var left_indent = parseInt($('.image_reel').css('left')) - divWidth; var slideNumberOn = (left_indent / divWidth); var slideNumber = ((slideNumberOn * -1) - 1); $slideNumber = slideNumber; if ($slideNumber >= 1) { //do not animate if on first slide rotate(); //Trigger rotation immediately }; } return false; //Prevent browser jump to link anchor }); //URL eg:www.hello.com#one var hash = window.location.hash; var map = { one: 1, two: 2, three: 3, four: 4 }; var hashValue = map[hash.substring(1)]; //animate if hashValue is not null if (hashValue != null) { $slideNumber = hashValue; rotate(); //Trigger rotation immediately return false; //Prevent browser jump to link anchor };});.window { height:200px; width: 200px; overflow: hidden; /*--Hides anything outside of the set width/height--*/ position: relative;}.image_reel { position: absolute; top: 0; left: 0;}.slide {float:left; width:200px; height:200px}.one {background: #03C}.two {background:#0F6}.three {background: #39C}.four {background:#FC3}.hide {display:none}.not_active {background:#F00}.active {background:#0F0}<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js></script> <div class=window> <div class=image_reel> <div class=slide one>slide 1</div> <div class=slide two>slide 2</div> <div class=slide three>slide 3</div> <div class=slide four>slide 4</div> </div> </div> <div class=paging> <a href=# rel=1>one</a> <a href=# rel=2>two</a> <a href=# rel=3>three</a> <a href=# rel=4>for</a> </div> <div class=nav> <a id=prev class=active href=#>prev</a> <a id=next class=active href=#>next</a> </div>
Carousel for website
javascript;jquery;animation
1) Separation of ConcernsStart by refactorring your code in to more granular functions.You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concernsUpdate:E.g. Instead of having your reel resizing code inline, put it in it's own function, like this: function setImageReelWidth () { //Get size of images, how many there are, then determin the size of the image reel. var divWidth = $(.window).width(); var divSum = $(.slide).size(); var divReelWidth = divWidth * divSum; //Adjust the image reel to its new size $(.image_reel).css({ 'width': divReelWidth }); }This achieves 2 things:a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat. b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.Later, you can also encapsulate the whole thing in it's own class (function) and you can move it into it's own js file.2) The jQuery on functionUse the on function to attach your click events, rather than the click function.http://api.jquery.com/on/This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.3) The ready function// I like the more succinct:$(handler)// Instead of:$(document).ready(handler)But you might like the more obvious syntax.Those are just a few things to start with.-- Update 1 --I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorryI am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.So here is an example of a function defined outside of the ready block, but referenced from within.function testFunction () { alert ('it works');}$(document).ready(function () { testFunction(); // ... other code});This should pop up an alert box that says, it works when the page is loaded.You can try it for yourself.Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.also is there a better way to write:if ($slideNumber == 1) { $('#prev').attr(class, not_active) $('#next').attr(class, active)}else if ($slideNumber == divSum) { $('#next').attr(class, not_active); $('#prev').attr(class, active);}else { $('#prev').attr(class, active) $('#next').attr(class, active)};One option is to write it like this:$('#prev').attr(class, not_active)$('#next').attr(class, not_active)if ($slideNumber > 1) $('#prev').attr(class, active)if ($slideNumber < divSum ) $('#next').attr(class, active)
_softwareengineering.181125
Is there some standardized or widely accepted algorithm for picking up operators in shift/reduce conflicts in LALR parser? The question is naive, my problem is not with implementing my solution, but implementing the solution is already widely used.For shift the operator is the next input token, for reduce, it depends -- I consider all already read symbols (for given production) declared as operators:if there is one -- it is the operatorif there are more than one -- I report grammar errorif there is none I use the input token as operatorSo for example:E ::= E + EE ::= E * EE ::= numin case ofE + E | * numConsidering first production I read +, and since it is the only one operator read I pick this one for reduce operator. * is the first token in input so it servers as shift operator. But is my algorithm correct (i.e. the same as normally used for LALR parsers)? I am especially worried for the point when I have more than 1 operator in the read tokens.UpdateWhat I NOT am asking hereI don't ask how to resolve shift/reduce conflict once you have the operators. I don't ask how to set the precedence for operators.What I am asking hereI ask how to extract operators from the stream of tokens. Let's say user set some precedence rules for +, - and *. The stack is: - E + E and input is E. Or the stack is E and input is *.What is the operator for reduce in first case? And in the second? Why?The stack is really entire right hand side of production.
How to extract operators from the grammar productions for conflict resolution in LALR parser?
parsing;operators
Converted from a comment, first, a rephrasing of your question:Suppose we have the following ambiguous grammar:E ::= E + EE ::= E * EE ::= numIn the LR automaton, we will have the following shift-reduce conflict (among others):E ::= E * E , +E ::= E + EAs is common knowledge, reducing here will make '*' bind more tightly as '+' (as normal), while shifting will make '+' bind more tightly.Parser generators such as Yacc and Bison allow the user to mark tokens as binding more tightly than other tokens. As normal, we say that '* > +'.However, there seems to be a mismatch somewhere: the '>' we use above is an operator between two tokens, but the shift-reduce conflict is a conflict between a token and a production.In Yacc and Bison, not just tokens but productions also have a priority. The user can mark tokens with priorities (as is normally done), and productions (that have not been given an explicit priority) have their priority inferred. The priority of a production is equal to the priority of the rightmost token in the production.In E ::= E * E, the rightmost token is '*', so in the shift reduce conflict above the priority of the reduction is '*', and the priority of the shift is '+', and as the priority of '*' is higher than '+', we decide to reduce rather than shift. As another example, the rightmost token of A ::= a b B c d C D E is 'd' (with only capitalized letters being nonterminals).Adding A ::= a b B c d C D E %prec a to a production in Yacc and Bison explicitly gives that production the priority of 'a', but this is not normally done. Note that some productions may not have a rightmost token, or the priority between tokens is not defined, in which cases Yacc and Bison fall back to always shifting to resolve conflicts (Yacc and Bison always create a fully deterministic table, unless in GLR mode).For completeness: the action with higher priority wins, so if the production has a higher priority than the token, we reduce instead of shifting. If priorities are equal, we look at associativity: left associativity means reducing, right associativity means shifting. 'nonassoc' is the third type of 'associativity', and it means an error: the shift/reduce conflict is resolved by removing both entries in the table, so the parser rejects inputs entering that state with that lookahead.
_unix.53593
Playing around with the new Chromebook, was trying to get Make working to the end of installing other software.However, can't seem to get Make anywhere near to install; ./configure doesn't generate the needed build.sh.Does anyone have any advice on how I can go about doing this, or installing Linux software on ChromeOS in general?
Installing GNU Make on ChromeOS
software installation;make;chrome os
null
_codereview.136712
I have a web application that gathers data from the user. Data is gathered via multiple asynchronous requests, so every time new data is retrieved it is immediately sent to the server because I can't know when the user will quit the webpage and I need to process data if even if it is missing.I need to receive these chunks of information, and trigger the processing scripts when no data is retrieved for 30 seconds, without using daemons, system calls or cron jobs. (I'd be happy if you suggest other approaches fulfilling these requirements.)<?php/** * What you see here, is one of the worst things you'll ever see.. * It's almost physically painful just thinking of the concept of this file.. * Feels like pooping glass again.. * Feels like a mad C++ developer.. * Which way did you say Feelodelphia was anyway ? * ** * Father, I know that I have broken your laws and my sins have separated me from you. * I am truly sorry, and now I want to turn away from my past sinful life toward you. * Please forgive me, and help me avoid sinning again. * * Some people actually reached enlightenment because of this... **//** * This is kind of a daemon, that is run only once, and acts like a cron to process * prints, in a reasonable delay of time. * Previous implementation (a daemon per client) would have eaten 2MB per client * of memory, which is a whack. **/include ../helperMethods.php;include daemonconfig.php;ini_set('max_execution_time', 0);ignore_user_abort(true);if (file_exists($runningMarkerFile)) { die(daemon already running);}if (filemtime($runningMarkerFile) - time() > $daemonTimeout) { unlink($runningMarkerFile);}touch($runningMarkerFile);while (true) { set_time_limit($daemonTimeout); $queuedItems = file($queueFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | LOCK_EX); foreach ($queuedItems as $item) { $filePath = $tempPrintsPath . $item; // If file has been saved 30 seconds ago, process it, if not, wait until next iteration if (filemtime($filePath) - time() < 30) continue; // Check if the file has been marked as final. // TODO lock_replace_in_file($queueFile, $item, ); $jPrint = unserialize($filePath); include ../resultPrintHandler.php; } sleep(5);}unlink($runningMarkerFile);I have the following questions on it:Can it reliably run on shared hosting? I know shared hosting caps execution time, the script shouldn't hit it anyway.Should I add timeout logic?
PHP daemon like behavior hack
php
null
_unix.217054
I've configured an interface 'nonlocal' with type dummyip link add nonlocal type dummyon that interface are some IPv6 addresses configured. Now an apache can start with some ip based vhosts on above-said ipv6 addresses.The real addresses get configured on the phyiscal interface if a second machine crashes (failover). Everything works a expected.But I would like to know the exact characteristics of such a dummy interface (on RHEL6 & 7). Is there a homepage or something similar which explains that type?
characteristics of interface type dummy
rhel;interface
According to this and according to the source code, dummy interfaces appear to be kind of like the /dev/null of network interfaces. If will never receive a packet, and any packet you send to it goes nowhere.For your use case, you probably don't need a dummy interface at all. You can probably achieve what you need to binding the virtual IP address in question as a secondary IP address on the loopback interface (lo) as either a /32 (for IPv4) or /128 (for IPv6).
_codereview.39427
Preface: I'm starting to learn C# and I don't want to port any of my bad habits from other languages, so I'm following convention wherever possible.Using the default Visual Studio code formatting, this relatively simple function requires 14 lines of code.public void add(int[] values, Func<int, int> transform = null){ foreach (int v in values) { if (transform == null) { add(v); } else { add(transform(v)); } }}My first thought was to use the ?? operator to do something like the following snippet, but apparently that's gibberish.public void add(int[] values, Func<int, int> transform = null){ foreach (int v in values) { add(transform(v) ?? v); }}Is there a more concise and/or readable way to write the following method?
Is there a more concise and/or readable way to write the following method?
c#;beginner
There are at least two answers.The short one:public void add(int[] values, Func<int, int> transform = null){ foreach (int v in values) add( (transform != null) ? transform(v) : v);}The efficient one:public void add(int[] values, Func<int, int> transform = null){ if( transform != null) foreach (int v in values) add( transform(v)); else foreach (int v in values) add( v);}Not nice, but you wanted a short version.Maybe someone has a LINQ at hand which does this even better.
_webapps.3081
I wish to create a link map between blogs so to reflect the social network between bloggers.Such a service would take a starting point of a blog or two, and start adding links and mapping the links between them.Is there a web service to do this?(I am sure I once found a service that does that - but can't find it at the moment)
Mapping the link network between websites (blogs)?
social networks;links;social graph;blog
null
_unix.254494
I've noticed that { can be used in brace expansion:echo {1..8}or in command grouping:{ls;echo hi}How does bash know the difference?
How does bash differentiate between brace expansion and command grouping?
bash;shell script
A simplified reason is the existence of one character: space.Brace expansions do not process (un-quoted) spaces.A {...} list needs (un-quoted) spaces.The more detailed answer is how the shell parses a command line.The first step to parse (understand) a command line is to divide it into parts.These parts (usually called words or tokens) result from dividing a command line at each meta-character from the link:Splits the command into tokens that are separated by the fixed set of meta-characters: SPACE, TAB, NEWLINE, ;, (, ), <, >, |, and &. Types of tokens include words, keywords, I/O redirectors, and semicolons.Meta-characters: spacetabenter;,<>| and &.After splitting, words may be of a type (as understood by the shell): Command pre-asignements: LC=ALL ... Command LC=ALL echo Arguments LC=ALL echo hello Redirection LC=ALL echo hello >&2 Brace expansionOnly if a brace string (without spaces or meta-characters) is a single word (as described above) and is not quoted, it is a candidate for Brace expansion. More checks are performed on the internal structure later.Thus, this: {ls,-l} qualifies as Brace expansion to become ls -l, either as first word or argument (in bash, zsh is different).$ {ls,-l} ### executes `ls -l`$ echo {ls,-l} ### prints `ls -l`But this will not: {ls ,-l}. Bash will split on space and parse the line as two words: {ls and ,-l} which will trigger a command not found (the argument ,-l} is lost): $ {ls ,-l} bash: {ls: command not foundYour line: {ls;echo hi} will not become a Brace expansion because of the two meta-characters ; and space.It will be broken into this three parts: {ls new command: echo hi}. Understand that the ; triggers the start of a new command. The command {ls will not be found, and the next command will print hi}:$ {ls;echo hi}bash: {ls: command not foundhi}If it is placed after some other command, it will anyway start a new command after the ;:$ echo {ls;echo hi}{lshi}ListOne of the compound commands is a Brace List (my words): { list; }.As you can see, it is defined with spaces and a closing ;.The spaces and ; are needed because both { and } are Reserved Words. And therefore, to be recognized as words, must be surrounded by meta-characters (almost always: space).As described in the point 2 of the linked pageChecks the first token of each command to see if it is .... , {, or (, then the command is actually a compound command.Your example: {ls;echo hi} is not a list.It needs a closing ; and one space (at least) after {. The last } is defined by the closing ;.This is a list { ls;echo hi; }. And this { ls;echo hi;} is also (less commonly used, but valid)(Thanks @choroba for the help).$ { ls;echo hi; }A-list-of-fileshiBut as argument (the shell knows the difference) to a command, it triggers an error:$ echo { ls;echo hi; }bash: syntax error near unexpected token `}'But be careful in what you believe the shell is parsing:$ echo { ls;echo hi;{ lshi
_webapps.43328
I tried this formula: =concatenate(query('Scheda Intervento'!C2:K14;select SUM (K) where (F>= date '2013-01-01' and F <= date '2013-01-31' and C = ' & A2 &');0))The result is right but it gives me:sum 35 but I want to have 35
Problem QUERY function in Google Spreadsheets formula
google spreadsheets
Use the following formula:=INDEX(query('Scheda Intervento'!C2:K13;select sum (K) where (F >= date '2013-01-01' and F <= date '2013-01-31' and C = ' & A2 &'));2;1)After that you can perform the CONCAT handling.
_unix.221994
I am trying to start my server remotely with this: ssh [email protected] /sbin/rebootAnd keep getting this backssh: connect to host xxx.xx.xx.xx port 22: Operation timed outWhy can't I start my server?
Start Server remotely using SSH
linux;centos;ssh;reboot;wake on lan
null
_codereview.98313
I'm writing a little math module in C to handle vectors and matrices. This will be column-major style but right now I've only finished the basics of the vector functions and wanted some feedback on optimization tips, naming conventions, etc. This is C so no real function overloading. I would like to keep it C style.vec3f.h#include stdlib.h#include math.hconst double m_PI = 3.14159265359;typedef struct vec3f{ double p[3];}vec3f;vec3f* vec3fx(double x, double y, double z);vec3f* vec3fv(vec3f* v3);vec3f vec3fs(double x, double y, double z);void vec3fadd(vec3f* out, struct vec3f* a, struct vec3f* b);void vec3fsub(vec3f* out, struct vec3f* a, struct vec3f* b);void vec3fmul(vec3f* out, struct vec3f* a, struct vec3f* b);void vec3fnegate(vec3f* out);void vec3fscale(vec3f* out, double a);void vec3fscaleu(vec3f* out, double x, double y, double z);void vec3fscalex(vec3f* out, double a);void vec3fscaley(vec3f* out, double a);void vec3fscalez(vec3f* out, double a);void vec3flen(double* out, vec3f* in);void toDegrees(double* out, double angleInRadians);void toRadians(double* out, double angleInDegrees);void vec3fdot(double* out, vec3f* a, vec3f* b);void vec3fcross(vec3f* out, vec3f* a, vec3f* b);void vec3fnorm(vec3f* out, vec3f* in);void vec3fdist(double* out, vec3f* a, vec3f* b);void vec3fangle(double* out, vec3f* a, vec3f* b);vec3f.c#include vec3f.hvec3f* vec3fx(double x, double y, double z){ vec3f* v = (vec3f*)malloc(sizeof(vec3f)); v->p[0] = x; v->p[1] = y; v->p[2] = z; return v;}vec3f* vec3fv(vec3f* v3){ vec3f* v = (vec3f*)malloc(sizeof(vec3f)); v->p[0] = v3->p[0]; v->p[1] = v3->p[1]; v->p[2] = v3->p[2]; return v;}void vec3fadd(vec3f* out, vec3f* a, vec3f* b){ out->p[0] = a->p[0] + b->p[0]; out->p[1] = a->p[1] + b->p[1]; out->p[2] = a->p[2] + b->p[2];}void vec3fsub(vec3f* out, vec3f* a, vec3f* b){ out->p[0] = a->p[0] - b->p[0]; out->p[1] = a->p[1] - b->p[1]; out->p[2] = a->p[2] - b->p[2];}void vec3fmul(vec3f* out, vec3f* a, vec3f* b){ out->p[0] = a->p[0] * b->p[0]; out->p[1] = a->p[1] * b->p[1]; out->p[2] = a->p[2] * b->p[2];}void vec3fnegate(vec3f* out){ out->p[0] = -out->p[0]; out->p[1] = -out->p[1]; out->p[2] = -out->p[2];}void vec3fscale(vec3f* out, double a){ out->p[0] *= a; out->p[1] *= a; out->p[2] *= a;}void vec3fscaleu(vec3f* out, double x, double y, double z){ out->p[0] *= x; out->p[1] *= y; out->p[2] *= z;}void vec3fscalex(vec3f* out, double a){ out->p[0] *= a;}void vec3fscaley(vec3f* out, double a){ out->p[1] *= a;}void vec3fscalez(vec3f* out, double a){ out->p[2] *= a;}void vec3flen(double* out, vec3f* in){ double res = 0; res += in->p[0] * in->p[0]; res += in->p[1] * in->p[1]; res += in->p[2] * in->p[2]; *out = sqrt(res);}void toDegrees(double* out, double angleInRadians){ *out = angleInRadians * (double)(180.0/m_PI);}void toRadians(double* out, double angleInDegrees){ *out = angleInDegrees * (double)(m_PI/180.0);}void vec3fdot(double* out, vec3f* a, vec3f* b){ double total = 0; total += a->p[0] * b->p[0]; total += a->p[1] * b->p[1]; total += a->p[2] * b->p[2]; *out = total;}void vec3fcross(vec3f* out, vec3f* a, vec3f* b){ out->p[0] = a->p[1] * b->p[2] - b->p[1] * a->p[2]; out->p[1] = a->p[2] * b->p[0] - b->p[2] * a->p[0]; out->p[2] = a->p[0] * b->p[1] - b->p[0] * a->p[1];}void vec3fnorm(vec3f* out, vec3f* in){ double t = 0; vec3flen(&t, in); out->p[0] = in->p[0]/t; out->p[1] = in->p[1]/t; out->p[2] = in->p[2]/t;}void vec3fdist(double* out, vec3f* a, vec3f*b){ vec3f tmp; vec3fsub(&tmp, b, a); vec3flen(out, &tmp);}void vec3fangle(double* out, vec3f* a, vec3f* b){ double tmp; vec3fdot(&tmp, a, b); *out = acos(tmp);}
vector3 math module
performance;c;coordinate system
This seems to be generally well-written code. I have a few observations which may help you improve your code.Separate interface from implementationThe interface is the part in the vec3f.h file and the implementation is in the vec3f.c file. Users of this code should be able to read and understand everything they need from the implementation file. That means that only #includes essential to being able to understand the interface should be in the .h file. In this case, none are needed, so the #include lines should be deleted from the .h file. Also...Use all appropriate #includesThe implementation file (the .c file) does need some #include files but they should be in angle brackets and not quotes. When you write #include math.h it is different from #include <math.h>. For standard headers, you should use the <> form. If you're not sure about the difference, see this question for more detail. In this case, vec3f.c should start with:#include vec3f.h#include <stdlib.h>#include <math.h>Use include guardsThere should be an include guard in the .h file. That is, start the file with:#ifndef VEC3F_H#define VEC3F_H// file contents go here#endif // VEC3F_HOmit spurious declarationsThe vec3f.h file includes a declaration for vec3fs but no implementation exists in the vec3f.c file. The declaration should be omitted.Use const where practicalFor a number of the operations, the vec3f structures passed in are unaltered. That's good design, but you should make it explicit. So for example instead of this:void vec3fadd(vec3f* out, struct vec3f* a, struct vec3f* b);Use this instead:void vec3fadd(vec3f* out, const vec3f* a, const vec3f* b);Note that this change also uses the next suggestion.Use defined typedef where practicalThe declarations for vec3fadd, vec3fsub and vec3fmul should use the the typedef'd vec3f rather than the longer struct vec3f. Both are correct, but since you've created the typedef, it makes sense to also use it consistently.Provide a means for non-heap allocationPerhaps your unwritten vec3fs function was intended to do this, but there is currently no way to initialize values for an stack-based vec3f. I'd recommend adding one like this:vec3f* vec3fs(vec3f* v, double x, double y, double z){ if (v != NULL) { v->p[0] = x; v->p[1] = y; v->p[2] = z; } return v;}Check the return value of mallocIf the program runs out of memory, a call to malloc can fail. The indication for this is that the call will return a NULL pointer. You should check for this and avoid dereferencing a NULL pointer (which typically causes a program crash). For example, using the vec3fs above, you could rewrite vec3fx as:vec3f* vec3fx(double x, double y, double z){ vec3f* v = malloc(sizeof(vec3f)); return vec3fs(v, x, y, z);}Note also that the cast is not required since malloc returns a void *.Don't pointlessly initialize variablesThe current code includes this function:void vec3fdot(double* out, vec3f* a, vec3f* b){ double total = 0; total += a->p[0] * b->p[0]; total += a->p[1] * b->p[1]; total += a->p[2] * b->p[2]; *out = total;}Consider instead this minor rewrite of vec3fdot:double vec3fdot(const vec3f* a, const vec3f* b){ return a->p[0] * b->p[0] + a->p[1] * b->p[1] + a->p[2] * b->p[2];}Return something useful from functionsThe way the functions are currently written, most return void but this prevents one from writing useful construct such as:toDegrees(vec3fangle(vec1, vec2));To support this, you could rewrite those two functions as:double toDegrees(double angleInRadians){ return angleInRadians * (double)(180.0/m_PI);}double vec3fangle(const vec3f* a, const vec3f* b){ return acos(vec3fdot(a, b)/(vec3flen(a)*vec3flen(b)));}Similarly, I'd recommend that each function that takes a vec3f *out as the first parameter should also return it. This would make your vec3f.h file look like this:vec3f.h#ifndef VEC3F_H#define VEC3F_Hconst double m_PI = 3.14159265359;typedef struct vec3f{ double p[3];}vec3f;vec3f* vec3fx(double x, double y, double z);vec3f* vec3fv(vec3f* v3);vec3f* vec3fs(vec3f* v, double x, double y, double z);vec3f* vec3fadd(vec3f* out, const vec3f* a, const vec3f* b);vec3f* vec3fsub(vec3f* out, const vec3f* a, const vec3f* b);vec3f* vec3fmul(vec3f* out, const vec3f* a, const vec3f* b);vec3f* vec3fnegate(vec3f* out);vec3f* vec3fscale(vec3f* out, double a);vec3f* vec3fscaleu(vec3f* out, double x, double y, double z);vec3f* vec3fscalex(vec3f* out, double a);vec3f* vec3fscaley(vec3f* out, double a);vec3f* vec3fscalez(vec3f* out, double a);double vec3flen(const vec3f* in);double toDegrees(double angleInRadians);double toRadians(double angleInDegrees);double vec3fdot(const vec3f* a, const vec3f* b);vec3f* vec3fcross(vec3f* out, const vec3f* a, const vec3f* b);vec3f* vec3fnorm(vec3f* out, const vec3f* in);double vec3fdist(const vec3f* a, const vec3f* b);double vec3fangle(const vec3f* a, const vec3f* b);#endif // VEC3F_HConsider providing in-place operations as wellYour interface already includes the more generic form in which the output vector is different from either input vector, but it would likely be handy to have an explicit in-place version for your operators as well. For example,vec3f* vec3fadd(vec3f* a, const vec3f* b) { return vec3fadd(a, a, b);}Similarly, you may want to provide non-in-place versions of functions such as the scaling functions:vec3f* vec3fscale(vec3f* out, const vec3f* a, double f);Consider making the dimensionality genericIf you ever wanted to make a 2D or 4D point, consider how it might be done:double vec2flen(const vec2f* in){ return sqrt(in->p[0] * in->p[0] + in->p[1] * in->p[1]);}double vec3flen(const vec3f* in){ return sqrt(in->p[0] * in->p[0] + in->p[1] * in->p[1] + in->p[2] * in->p[2]);}double vec4flen(const vec4f* in){ return sqrt(in->p[0] * in->p[0] + in->p[1] * in->p[1] + in->p[2] * in->p[2] + in->p[3] * in->p[3]);}It might be useful to consider writing these generically in terms of the dimensionality of p. That might be either a fixed compile-time value as shown below or potentially as a member of a generic vecf structure.double vecflen(const vecf* in){ double sum = 0; for (int i=0; i < DIMENSIONS; ++i) { sum += in->p[i] * in->p[i]; } return sqrt(sum);}Consider removing allocating functionsInstead of the functions which allocate memory and then initialize, I think it may be better to leave out the allocation, since it's nothing more than malloc(sizeof(vec3f)) anyway. Doing so will prevent hidden memory allocations since both the allocation and freeing of that memory will happen in some calling function using the usual memory allocation/deallocation calls.Consider adding a projection functionOne handy function that does not appear in your list is a projection function:// calculate the projection of b onto a vec3f* vec3fproj(vec3f* out, const vec3f* a, const vec3f* b){ vec3fcopy(out, a); double alen = vec3flen(a); return vec3fscale(out, vec3fdot(a, b)/(alen*alen));}
_webmaster.86734
Just thought, if that would be possible, I can get users native language, and display my webpage on their language, or on the closest one. So;Is it possible to get someone's language using his/her Google account cookies in somehow?
Getting user language via Google cookies
google;language;cookie;design
To answer your question, you don't need to hack into Google's cookies to get that information, but can find it out yourself in your own code.IMPORTANT NOTE: You are talking about automatically serving content to users based on their language settings, which can actually lead to a lot of SEO problems if done badly. A better option is to serve the URLs as normal, and if you detect that the user is viewing a different language version than their own, you provide a pop-up that offers to take them to the language of their choice. This approach will also allow you to correctly encode hreflang tags on your pages and will facilitate Google automatically picking up the most relevant language version to show users is search results.
_cs.9714
So I have the following pseudo-code:Function(n):for (i = 4 to n^2): for (j = 5 to floor(3ilog(i))): // Some math that executes in constant timeSo far, I know that to find this i will be calculating$\sum_{i=4}^{n^2}\sum_{j=5}^{3i \log_{2}i}C$ where $C$ is a constant, but I am completely lost as to how to proceed past the first summation which, if I'm not mistaken, will give me $3C \cdot (\sum_{i=4}^{n^2}(i \log_{2}i) - 5(n^2 - 4))$, but from here I'm lost. I don't need exact running time, but the asymptotic complexity.All help is greatly appreciated! I realize that this might be a duplicate, but I haven't been able to find a nested for loop problem of this nature anywhere...
Running time of a nested loop with $\sum i \log i$ term
time complexity;algorithm analysis;asymptotics
$$F(n) = \sum\limits_{i = 4}^{n^2} \sum\limits_{j = 5}^{3i\log i}C = C\sum\limits_{i = 4}^{n^2}(3i\log i - 4) = 3C\sum\limits_{i = 4}^{n^2}i \log i - \Theta(n^2)$$For asymptotic analysis, we can start the summation from $i = 1$ instead of $4$. Let$\begin{align}T(n) &= \sum\limits_{i = 1}^{n^2}i\log i = \sum\limits_{i = 1}^{n^2}\log {i^i} \\&= \log {1^1} + \log {2^2} + \log {3^3} + \dots + \log {(n^2)^{n^2}} \\&\le n^2 \cdot \log (n^2)^{n^2} \ \ \text{(there are \(n^2\) terms)}\\&= 2n^4 \log n \\&= O(n^4 \log n)\end{align}$Now, since $f(x) = x\log x$ is a continuous increasing function in $x \in [1, \infty)$, you can verify that :$\int\limits_{1}^{n^2}x\log x \ dx \le \sum\limits_{x = 1}^{n^2}x\log x \ \ $ (changing $i$ to $x$ simply because $x$ looks better when integrating). According to Wolfram, $\int\limits_{1}^{n^2}x\log x \ dx = \frac{1}{4}\left(n^4 \log \left({\frac{n^4}{e}}\right) + 1\right) = n^4 \log \left({\frac{n}{e}}\right) + \frac{1}{4}$Therefore, $\sum\limits_{x = 1}^{n^2}x\log x = \Omega(n^4\log n)$.Combining the upper and lower bounds, we have $T(n) = \Theta(n^4\log n)$Overall, $F(n) = \Theta(n^4\log n) - \Theta(n^2) = \Theta(n^4 \log n)$.So, your loops have complexity $\Theta(n^4 \log n)$.Remarks:1. You can show the lower and upper bounds in a similar way by observing that:$\int\limits_{1}^{n^2}x\log x \ dx \le \sum\limits_{x = 1}^{n^2}x\log x \le \int\limits_{0}^{n^2}(x+1)\log {(x+1)} \ dx$2. For the above inequalities, you can use the method of Riemann sum (use the left and the right Riemann sums to see the two bounds). Draw unit-width rectangles on an increasing function to see these bounds.3. I have done some implicit simplifications, such as just ignoring the constant $3C$ term, or starting the summation from $1$ instead of $4$ since we are dealing with $\Theta$. I have also made the common but slight abuse of notation when equating or subtracting $\Theta$ terms, without affecting the answer.
_unix.181130
Becuase some of limitation of MS.Windows, my friends and my family gime their flash memory to solve their problem. Such as format, partitioning in Linux with the cfidsk ,parted, sfidsk(dump and manipualting partition table),mkfs.*, dd commands, and other operations. But i get the new problem with set of flash memory, yes, bit of read only set to 1:When use :root@debian:/home/mohsen# hdparm -r /dev/sdb/dev/sdb: readonly = 1 (off)When i use: root@debian:/home/mohsen# hdparm -r0 /dev/sdbAnd use :root@debian:/home/mohsen# hdparm -r /dev/sdb/dev/sdb: readonly = 0 (off)But when i unplug and plug flash i prevent with the previous result:root@debian:/home/mohsen# hdparm -r /dev/sdb/dev/sdb: readonly = 1 (off)When i use cfdisk /dev/sdb or any command i get read-only disk error, This is 4th disk i get same error.Do you have any idea?
Flash memory and set to read only , Is it virus?
disk;readonly;flash memory;hdparm
null
_webapps.17314
In Hotmail, you can click an exclamation mark ! for an outgoing email to let the sender know it is important. How do I do this in Gmail?
Add a ! or a star to mark an outgoing email as urgent in Gmail
gmail
null
_unix.83829
I am trying to install dropbox onto my Debian machine, and I saw the instructioncd ~ && wget -O - some website leading to the download of a tar file | tar xzf - But what I did was just typing thiswget -O - some website leading to the download of a tar fileand I got a lot of rubbish on my terminal. What does wget -O -means? Does it do any harm to my computer?
What is the meaning of wget -O -
wget
Take a look at the man page for wget.-O file --output-document=file The documents will not be written to the appropriate files, but all will be concatenated together and written to file. If - is used as file, documents will be printed to standard output, disabling link conversion. (Use ./- to print to a file literally named -.) Use of -O is not intended to mean simply use the name file instead of the one in the URL; rather, it is analogous to shell redirection: wget -O file http://foo is intended to work like wget -O - http://foo > file; file will be truncated immediately, and all downloaded content will be written there.So you can either download the contents of URL to a file using -O somefile or you can download it and redirect its contents via STDOUT to another tool to do something with it. In this case that's what they're doing with the | tar xvf -.Your command:$ cd ~ && wget -O - some website leading to the download of a tar file | tar xzf -The above is taking the tarball from the URL and as it's being downloaded it's being redirected to the command tar so that it can be unpacked into your filesystem.
_unix.176597
It's pretty simple. I would like to figure out what combination of changes in /etc/login.defs and/or /etc/pam.d/system-auth-ac. I would need to perform to allow the following behavior:I want a user's password to be valid for 60 days.After 60 days, the system needs to yell at the user when they log in, telling them they need to change their password ASAP.The system must not impede the user's access to the system.This must apply to existing users (non-system accounts, UID >=500) as well as any newly-created users.Rationale: Limited users will not be managing the system account passwords, only system admin(s). Therefore, users should not have their access to the system impeded because the admin missed a password change. The number of accounts is rather small (maybe 9 or 10), but we're all human and we forget to do stuff from time to time.I'm not sure if login.defs or PAM offer this. The documentation leads me to believe that you can either have the system force the user to change their password when it expires, or you can have the password not age at all. A third option is to have the password age limit set to some huge amount, like 9,999 days, and then start warning the user that their password will expire in 9,936 days, but that's not really what I need either. I've done other kinds of PAM configuration, so it's not my first trip around the block. I'm just stuck on this problem.So, can this be done with PAM/login.defs, or do I need another utility that can take their place?
Warn about password expiration without forcing change
password;pam;accounts
null
_unix.377672
Let's say the group name of user1 is xyz.Is it possible, in the same Linux machine, that the username of some other user (not user1) is xyz?
Can group name of a user and the username of some other user be the same?
linux;users;group
Yes, it is possible but I wouldn't recommend it as it would be confusing.Actually it is common practice in most UNIXes and Linux distros, when user xyz is created, to automatically create a group named xyz and assign to it user xyz as its (only) member.
_unix.335778
echo Enter usernameread $WORDif [[ $WORD =~ ^(Dale|Paul|Ray)$ ]]; then echo $WORD is validelse echo $WORD is invalidfi
Bash regex test not working
bash
The error is in read command, use read WORD instead of read $WORD.Check this:echo Enter usernameread WORDif [[ $WORD =~ ^(Dale|Paul|Ray)$ ]]; then echo $WORD is validelse echo $WORD is invalidfi
_softwareengineering.255581
Consider a micro service infrastructure in which each service is responsible for one set of activities, and exposes a RESTful interface to its functionality. For example, assume a chat application.We might have one service which is responsible for creating users, and a second service that is responsible for creating messages.Now, we want to create a public-facing REST interface to the application. Are there any best practices for creating this public facade to the micro services? I'm interested in a couple of things, mainly:Which layer should handle authentication/authorization (if the underlying services - do they share this data or each implement their own auth)Clearly in this application messages are sent from users to users. However the message service can easily be written in such a way to be usable for anything. Should the public proxy be the one to determine the user information and then delegate to a message service?
Public API Facade with Micro Services
web services;rest;soa;services
There are two authorization models that are common: trusted subsystems and delegation.Trusted subsystems is an architecture in which the user creation & message creation services trust the API application to perform the user authentication & authorization. In this model, the API application is trusted (via network ACLs, tokens, x509 certificates, etc.) and can interact with both services in an unrestricted capacity.Delegation is an alternative architecture where the API calls the microservice on behalf of the user; in such a model, both the API & the microservices would handle authorization, with the microservices validating both the identity of the API application and the claims of the user making the original request. The API validates that the user is authenticated & authorized to make the request, while the message microservice validates that both the application is trusted and the user is authorized to create messages.There are tradeoffs between these two approaches; trusted subsystems is an easier architecture easier to implement, but delegation enables more advanced security features. For your application, it is likely much easier to follow the trusted subsystem strategy, so I would strongly consider building authn/authz at the API facade (maybe gateway is a better word here?).EDIT: The answer depends heavily on what the message service is doing, and what data is required for it to carry out its duties. If the message service is just routing messages in realtime to websockets, the requirements may be different than if the messages are persisted to a database. In general, though, it's possible that the service interacts with user IDs without being directly coupled to the user service (e.g. storing the messages in a table as sender_id, recipient_id, and message).Check out this post for more on delegation and traversing layers.
_unix.378344
I am working on small Debian 8 based server. For some reason (which I'm trying to investigate) PDO PHP extension stopped functioning loading when working as Apache module. If I run PHP CLI all works fine. As result I'm receiving following fatal error message: Fatal error: Class 'PDO' not found in /var/www/html/myproject/vendor/doctrine/dbal/lib/Doctrine/DBAL/DriverManager.php on line 155What I have done?checked if PDO extension is enabled for PHP under Apachereverted /etc/php5/apache2/php.ini file to base versionexplicit set extension_dir in php.iniI would kindly ask for any hints about what could I do to fix the issue and find probable reason why this mayed occured.
PHP PDO class not found even it's enabled under Apache2
debian;apache httpd;php5
null
_vi.11096
I want to copy different strings from different lines of the file and then paste them together at once. In other words, I want to collect different words in a basket and then paste them at once. How can I do this?
Copying multiple words (from different lines) and paste them at once
cut copy paste;register
Use an uppercase register when yanking (copying):AyA says to append to the a register, as opposed to a which would replace the contents of the a register.Once you've copied everything into the register, you can then paste it all at once with:ap
_cs.7215
I'm reviewing for a computability test, and my professor has not provided solutions to his practice questions. I came up with a solution to this problem, but it really seems like my answer is wrong (since I call upon $\mathsf{Halt}$ twice)...We are given this initial language for some machine $M$:$\mathsf{2Strings} = \left\{ \left<M\right>\ |\ L(M)\text{ contains at least 2 distinct strings }\land M\text{ is a }TM \right\}$And we are told to [s]how that [the language] is recursive-enumerable. The problem title is Reduction, so I assume we are supposed to use that.My solution is as follows:Pass $\left<M\right>$ to the following reduction:Create $w_1 \in L(M), w_2 \in L(M)$, so that $w_1 \not= w_2$, and let $M' = M$.Pass $\left<M', w_1\right>$ to $\mathsf{Halt}$. If the answer is Yes, proceed to step 4. Otherwise, return No.Pass $\left<M', w_2\right>$ to $\mathsf{Halt}$. If the answer is Yes, return Yes. Otherwise, return No.Basically, this is my logic: We pass each of two distinct strings from $L(M)$ to $\mathsf{Halt}$ separately; if either one says No, our answer is No. If both say Yes, the answer is Yes.Is my answer valid? More importantly, is it correct? If not, what should I do to fix it?
Reducing a problem to Halt
computability;reductions
First of all I find it rather artificial to argue with reductions, since a more direct argument is applicable here. However, you can of course do it.I think your approach follows basically the right direction. But it is not a clean reduction. Here is how I would phrase it.We want to show that ${\sf 2Strings}$ is recognizable by showing ${\sf 2Strings}\le_m {\sf Halt}$. The reduction goes as follows: Assume we have a TM $M$ and based om $M$ we define a different TM $M'$. Let us first define a NTM $N$: 0. Delete the input 1. Guess two words u and w 2. If u=w cycle 3. Simulate u on M 4. Simulate w on M 5. Accept if both simulation accepted, otherwise cycleNow let $M'$ be the deterministic version of $N$. The reduction maps $\langle M \rangle $ to $\langle M',\varepsilon \rangle$. By construction, $$\begin{align}\langle M \rangle \in {\sf 2String} & \iff N \text{ accepts every input}\\ & \iff M' \text{stops on every input}\\ & \iff M' \text{stops on }\varepsilon \\ & \iff \langle M',\varepsilon\rangle \in {\sf Halt} \\\end{align}$$
_codereview.38689
I have some Scala code that uses Internet to authorize a user. Therefore, it can throw Exceptions like IOException in the method.The original code was written in Java. So, yes, it uses variables, not val. Also it returns early many times if some condition is not satisfied.The following is an example. (The actual code is, of course, a little more complicated.)def connect(): (IdInfo, PasswordInfo, ConnectionInfo) = { var idInfo: IdInfo = null var pwdInfo: PasswordInfo = null var connInfo: ConnectionInfo = null try { idInfo = calcIdInfo() } catch { case ex: IOException => return null } try { pwdInfo = calcPwdInfo(idInfo) } catch { case ex: AuthorizationException => return null } try { connInfo = calcConnInfo(idInfo, pwdInfo) } catch { case ex: IOException => return null } try { verify(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => return null case ex: AuthorizationException => return null } (idInfo, pwdInfo, connInfo)}I'm trying to rewrite the code in the functional style. What I did wasUse vals instead of varsRemove return earlyUse None instead of nullI tried to use methods like fold, but at each stage, the types of input or the types of output are different - IdInfo, (IdInfo, PasswordInfo), (IdInfo, PasswordInfo, ConnectionInfo) are all different types - and, what each stage does is also diffrent from each other, so I couldn't use such method.def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { val idInfoOpt = try { Some(calcIdInfo()) } catch { case ex: IOException => None } idInfoOpt map (idInfo => { val pwdInfoOpt = try { Some(calcPwdInfo(idInfo)) } catch { case ex: AuthorizationException => None } pwdInfoOpt map (pwdInfo => { val connInfoOpt = try { Some(calcConnInfo(idInfo, pwdInfo)) } catch { case ex: IOException => None } connInfoOpt map (connInfo => { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None } }) getOrElse None }) getOrElse None }) getOrElse None}The resultant code is more complex than the original one. There are deeper indentations, and the type of each value is not easy to determine (A lot of Options and map and getOrElse).In the above example, the code has calc***Info() methods, but in reality the code is more complex since it has more statements between each stage, so there seems almost no reason to use the actual resultant code instead of the original one.I think that the procedural style is better than the functional style in this case. Or not? The more complex the code is, the more chance of errors there will be. Are there better ways to get rid of vars and early returns?For ease, here are compilable source codes (although it does nothing):The first one: http://ideone.com/KJS1tnThe second one: http://ideone.com/gulzgs
Code with many early returns (exits) into the functional style
functional programming;scala
After reading the code, I assume these are the signatures of the building blocks of your codeclass IdInfoclass PasswordInfoclass ConnectionInfodef calcIdInfo:IdInfo=???def calcPwdInfo(idInfo:IdInfo):PasswordInfo=???def calcConnInfo(idInfo:IdInfo,pwdInfo:PasswordInfo):PasswordInfo=???I left out the implementations for the calc as they don't really matter.There are several possible variations to improve on the current code. Let's have a look at the last call to map in connect : connInfoOpt map (connInfo => { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None } }) getOrElse NoneThe try expression has type Option[(IdInfo, PasswordInfo, ConnectionInfo)] which is the type you want as the output of the function connect. As the name connInfoOpt suggests, it is also an option. Map on option has a signature roughly equivalent to : map(f:A=>B):Option[B]Where A is the type which is wrapped in the original option, and B is the type wrapped in the resulting option. Thus let's say connInfoOpt has type Option[ConnectionInfo] we get A = ConnectionInfoB = Option[(IdInfo, PasswordInfo, ConnectionInfo)]Therefore the return type of the map expression is Option[B] which can be expanded to Option[Option[(IdInfo, PasswordInfo, ConnectionInfo)]]Here lies the first problem : to get the Option[(IdInfo, PasswordInfo, ConnectionInfo)] out, you use getOrElse None. A slightly shorter way to express that is to call flatten. The original expression can thus be rewritten as: connInfoOpt map (connInfo => { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None } }) flattenwhich has type Option[(IdInfo, PasswordInfo, ConnectionInfo)]. The next step is to study the option type and see that it has a flatMap method which has the following signature :flatMap(f:A=>Option[B]):Option[B]// for comparison with map which was map(f:A=>B):Option[B]Then notice that each intermediary is step is of the form : option map { A=> Option[B] } flattenfor instance: connInfoOpt map (connInfo => { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None }}) flattencan be rewritten as : connInfoOpt flatMap (connInfo => { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None }})Which means the whole function can now be simplified to : def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { val idInfoOpt = try { Some(calcIdInfo()) } catch { case ex: IOException => None } idInfoOpt flatMap (idInfo => { val pwdInfoOpt = try { Some(calcPwdInfo(idInfo)) } catch { case ex: AuthorizationException => None } pwdInfoOpt flatMap (pwdInfo => { val connInfoOpt = try { Some(calcConnInfo(idInfo, pwdInfo)) } catch { case ex: IOException => None } connInfoOpt flatMap (connInfo => { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None } }) }) }) }We got rid of the 3 getOrElse but this still isn't so nice. Let's extract a few methods next to make the code easier to read :def safeIdInfo():Option[IdInfo]={ try { Some(calcIdInfo()) } catch { case ex: IOException => None }}def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { try { verify(idInfo, pwdInfo, connInfo) Some(idInfo, pwdInfo, connInfo) } catch { case ex: IOException => None case ex: AuthorizationException => None }}def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Option[ConnectionInfo] = { try { Some(calcConnInfo(idInfo, pwdInfo)) } catch { case ex: IOException => None }}def safePwdInfo(idInfo: IdInfo): Option[PasswordInfo] = { try { Some(calcPwdInfo(idInfo)) } catch { case ex: AuthorizationException => None }}then the connect method looks like : def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { safeIdInfo() flatMap (idInfo => safePwdInfo(idInfo) flatMap (pwdInfo=> safeConnInfo(idInfo, pwdInfo) flatMap (connInfo => verifyConnInfo(idInfo, pwdInfo, connInfo) ) ) )}Which is better but not perfect. Let's apply some scala syntactic sugar : def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { for{ idInfo <- safeIdInfo() pwdInfo <- safePwdInfo(idInfo) connInfo <- safeConnInfo(idInfo, pwdInfo) verified <- verifyConnInfo(idInfo, pwdInfo, connInfo) } yield verified } The connect method is much better (I think) but we end up with repetition in the safe methods. Actually, Scala offers a type to reduce this duplication, the Try type which we will use to replace the Option type in the safe methods :def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Try[(IdInfo, PasswordInfo, ConnectionInfo)] = Try { verify(idInfo, pwdInfo, connInfo) (idInfo, pwdInfo, connInfo)}def safeIdInfo():Try[IdInfo]=Try(calcIdInfo()) def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Try[ConnectionInfo] = Try(calcConnInfo(idInfo, pwdInfo))def safePwdInfo(idInfo: IdInfo): Try[PasswordInfo] = Try(calcPwdInfo(idInfo))Of course doing this, the connect method is no longer valid at the type level it needs to be adapted. To match the exact behavior of the original code the adaptation will look like : def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { val tryVerified = for{ idInfo <- safeIdInfo() pwdInfo <- safePwdInfo(idInfo) connInfo <- safeConnInfo(idInfo, pwdInfo) verified <- verifyConnInfo(idInfo, pwdInfo, connInfo) } yield verified tryVerified match { case Success(value) => Some(value) case Failure(authException:AuthorizationException)=> None case Failure(ioException:IOException)=> None case Failure(failed)=> throw failed } } However I will suppose that you don't really want to rethrow unknown runtime exceptions and instead want to return None for any error, in which case the following form of connect should work : def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { val tryVerified = for{ idInfo <- safeIdInfo() pwdInfo <- safePwdInfo(idInfo) connInfo <- safeConnInfo(idInfo, pwdInfo) verified <- verifyConnInfo(idInfo, pwdInfo, connInfo) } yield verified tryVerified.toOption } The complete code is now : def verifyConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo, connInfo: ConnectionInfo) :Try[(IdInfo, PasswordInfo, ConnectionInfo)] = Try { verify(idInfo, pwdInfo, connInfo) (idInfo, pwdInfo, connInfo) } def safeIdInfo():Try[IdInfo]=Try(calcIdInfo()) def safeConnInfo(idInfo: IdInfo, pwdInfo: PasswordInfo): Try[ConnectionInfo] = Try(calcConnInfo(idInfo, pwdInfo)) def safePwdInfo(idInfo: IdInfo): Try[PasswordInfo] = Try(calcPwdInfo(idInfo)) def connect(): Option[(IdInfo, PasswordInfo, ConnectionInfo)] = { val tryVerified = for{ idInfo <- safeIdInfo() pwdInfo <- safePwdInfo(idInfo) connInfo <- safeConnInfo(idInfo, pwdInfo) verified <- verifyConnInfo(idInfo, pwdInfo, connInfo) } yield verified tryVerified.toOption } Using the right types, a functional style and some syntactic sugar can go a long way to simplify your code :)For further reference, check the scala doc for Option and Try, also check out the FAQ on yield for more explanations on the for-expression syntactic sugar.
_unix.198959
My $HOME on a server is in a Andrew file system, and the server runs kerberos. I created a tmux session, wherein I ran a shell process. Then I detached it, and logged out, and after a while logged in again and reattach the tmux session. In the shell process in tmux, I found that I didn't have permission to access my (non-directory) files in $HOME. I checked my ticket and it didn't expire, and I renewed it by running krenew and still didn't have permission.$ ls -lls: cannot access README: Permission deniedls: cannot access setup.sh: Permission deniedls: cannot access setup.sh~: Permission deniedtotal 14drwxrwxr-x. 2 t 2048 Apr 6 21:48 bindrwxrwxr-x. 11 t 2048 Apr 24 18:16 data??????????? ? ? ? ? ? README.md??????????? ? ? ? ? ? setup.sh??????????? ? ? ? ? ? setup.sh~drwxrwxr-x. 2 t 2048 Apr 22 18:50 srcThanks!
Not permitted to access my files on $HOME in tmux after log out and log in
kerberos
null
_unix.23852
Sort of like the Windows counterpart of CamStudio.
What is the easiest way for me to take a video of what I'm doing on a Linux desktop?
x11;video;desktop
You can have a look at RecordMyDesktop or Freeeseer.
_vi.6196
On bash's readline in emacs mode, I recently discovered the transpose functionality, giving me the opportunity to quickly fix a typo likedc dirto cd dirby pressing CTRL+T on the c character.Is there something similar in Vi/Vim that lets me swap characters and words around?
How do I flip characters or words like emacs' transpose?
normal mode
For characters, it's fairly simple: xp to swap the letter under the cursor with the following letter, and Xp to swap the letter under the cursor with the previous letter.The x command deletes the character under the cursor, leaving the cursor on the next character. The X command deletes the character just before the cursor, leaving the cursor on the same character it was on.p puts (pastes) the last deleted or last yanked text just after the current cursor position. (P puts it just before the current cursor position, so xP and XP both leave the text the way it was before you started.)For swapping words, I'm not sure; perhaps someone else can answer that. You can come close with dawwP (or remap it to be shorter) but that will break on several edge cases, for example near the end of a line.
_softwareengineering.211962
I'm just wondering if anyone knows about some well designed .NET Open Source Applications using WPF?I have already tried to search at the usual sites like GitHub and Sourceforge, but I wasn't very satisfied by the results at all.Actually I'm interested in the right usage of MVVM, Data Binding etc. in the context of relatively large Software (at least more than the few lines of sample code, you will find at most Tutorials and Books). Also ORM with NHibernate lies in my main concern.Currently I also do have the overall impression WPF is not used very extensively at all, am I right with that? Which closed source (commercial) Software Products are out there, using it?
Well designed Open Source WPF Applications
c#;.net;software;wpf
null
_unix.361839
I've been trying to download and play with the Open gym software that past two days. Specifically the Mujoco which I'm planning to use for research.After some trials and tribulations actually figuring out how to use the terminal(I'm using the BASH terminal on windows 10), I finally downloaded all the files from open gym, gym.openai doc , onto my desktop.when I try to run any of the python files, it gives me this error.File /usr/local/lib/python2.7/dist-packages/mujoco_py/config.py, line 33, in init_configraise error.MujocoDependencyError('To use MuJoCo, you need to either populate ~/.mujoco/mjkey.txt and ~/.mujoco/mjpro131, or set the MUJOCO_PY_MJKEY_PATH and MUJOCO_PY_MJPRO_PATH environment variables appropriately. Follow the instructions github /openai/mujoco-py for where to obtain these.')mujoco_py.error.MujocoDependencyError: To use MuJoCo, you need to either populate ~/.mujoco/mjkey.txt and ~/.mujoco/mjpro131, or set the MUJOCO_PY_MJKEY_PATH and MUJOCO_PY_MJPRO_PATH environment variables appropriately. Follow the instructions on github /openai/mujoco-py for where to obtain these.Which takes me here: https://github.com/openai/mujoco-pyOf course it states that Mujoco isn't open sourced. So I went along with the trial program, got the license key and it tells me to download the binaries.Which is not found.https://roboti.com/active/mjpro131_windows.zipDon't know how to proceed from here. Any helps would be appreciated. It's for research.By the way I took the https and .com out of my links because stackexchange wouldn't let me post otherwise.
Installing Mujoco from AI gym onto Windows 10(For research)
ubuntu;software installation
null
_codereview.36782
Here are a couple of examples of one-liners that go way beyond 80 characters:scope = DepartmentRepository.includes(:location).by_account(@request.account_id).find(approved_department_ids)departments = ActiveModel::ArraySerializer.new(scope, each_serializer: DepartmentWithLocationSerializer).as_jsonI usually simply break these kinds of chained method calls before the . and indent the next line. My IDE (Emacs) runs rubocop on my source files as I edit them and doesn't complain about this practice. It does complain about lines longer than 80 characters so I feel somewhat compelled to fix them. How would I refactor these? The first line is calling ActiveRecord finders and scopes. Scopes can be compbined but then they have ackward names that seldom see reuse (e.g. by_account_with_locations).
How do I refactor lines of Ruby code that run too long due to method chaining or object instantiation?
ruby
I don't really see any real trouble with those lines. But I know the feeling that a line just seems too long (especially if everything else in the file is nice and neat). It's often a good thing to notice, but in some cases it just doesn't make sense to worry.Are the lines readable? Absolutely. They are very descriptive in fact. If you were talking about a very long conditional filled with && and || and negations, then yeah, it should probably be changed. But in this case, I don't see reason to fret.But if you're intent on refactoring, you could (as an example) move the ArraySerializer instantiation into a factory on DepartmentWithLocationSerializer and get something likeDepartmentWithLocationSerializer.serialize(scope).as_jsonThat sort of thing helps a bit. But if I knew a good zen quote about a little imperfection being OK too, I'd drop it here :)Anyway, don't worry about adding methods for things you'll only use once. You don't always need a very practical reason like DRY, to add some more methods. If adding some methods it can make the code a little neater to look at, that's a reason in itself. Everything in moderation, YMMV, etc., so just try it out and see if the code seems nicer afterwards. If it doesn't, well, then try to live with the long lines.
_codereview.17974
var ContentEditingHelper;$(ContentEditingHelper = function () { var costCenterSelector = '#CostCenter'; var projectSubcodeSelector = '#ProjectSubcode'; var incidentNumberSelector = '#IncidentNumber'; //This bit of code affects the 'Add New Order' dialog. It works on the 'Incident Number', 'Project Subcode', and 'Cost Center' input fields. //Since only one of these fields is allowed to be populated at a time -- use jQuery to disable the other fields when typing is detected in one. $(this).on('keyup', '#CostCenter, #ProjectSubcode, #IncidentNumber', function () { if ($(this).val() === '') { $(costCenterSelector).prop('disabled', false); $(projectSubcodeSelector).prop('disabled', false); $(incidentNumberSelector).prop('disabled', false); } else { switch (this.id) { case 'CostCenter': $(projectSubcodeSelector).prop('disabled', true); $(incidentNumberSelector).prop('disabled', true); break; case 'ProjectSubcode': $(costCenterSelector).prop('disabled', true); $(incidentNumberSelector).prop('disabled', true); break; case 'IncidentNumber': $(costCenterSelector).prop('disabled', true); $(projectSubcodeSelector).prop('disabled', true); break; } } }); //Public methods go here. return { };} ());So I've got this and it works. There are some clear code smells and some not-so-clear. I would like to be able to be able to reuse my selector names as much as possible. Is it possible to use them in my declaration of on? And how should I handle my case statements?Furthermore, is there an overall easier way to achieve my goal?
I have three input fields. When one has any information in it, the others should be disabled. Can I express this more succinctly?
javascript;jquery
var $inputs = $('#CostCenter, #ProjectSubcode, #IncidentNumber');$inputs.on('keyup', function() { $inputs.not(this).prop('disabled', this.value !== '');});If your elements are not available at document ready, use this:var selector = '#CostCenter, #ProjectSubcode, #IncidentNumber';$(document).on('keyup', selector, function() { $(selector).not(this).prop('disabled', this.value !== '');});Just keep in mind that this will query the DOM on every single keyup!! Are you sure you can't somehow do this differently?
_webmaster.86116
I have a site hosted with VidaHost (www.thinkchecksubmit.org) on a webspace-only package, and a number of domain names registered with 1and1. The site is built on a Wordpress install with a custom theme, and we have a DNS redirect from the primary URL to the IP of our webspace at VidaHost.For the majority of visitors, heading to thinkchecksubmit.org results in the site loading fine. However I've had reports that some visitors are greeted with 1and1's /defaultsite page (shown below), rather than being redirected to the Vidahost webspace.The DNS redirect appears to be correctly configured; running thinkchecksubmit.org through the OpenDNS checker (https://cachecheck.opendns.com) shows that the redirect is working as expected. 1and1 have repeatedly told me it's not their problem and that the affected visitors must be loading a cached version of the page from before any content was uploaded (this odds of this being true for multiple people all over the world are vanishingly small), or that the issue is with VisaHost's server being incorrectly configured.VidaHost have assured me that the site's configured correctly at their end, and that their server's experienced no downtime at the time these errors have been experienced - so it must be something at 1and1's end. You can see where this is going.So basically, neither party's been able to offer an explanation why it's occurring (nor why it works for most people who visit the site, but not others) - given that the error page is 1and1's default holding page, I'm inclined to think that the problem is at their end. Unfortunately, because we have a domain-only package with 1and1, I can't access the defaultsite page to try and modify things there for the few people who aren't redirected automatically.I'm tearing my hair out over this, as I've not found any way to resolve it and I need to be confident that anyone demonstrating the site at an event won't have the holding page above splashed across a 20ft screen in front of thousands of people.Can anyone out there recommend steps I could take to resolve the issue?
DNS redirect not working for some site visitors
redirects;dns;1and1
null
_cs.47777
I was wondering whether it is possible (and if so, then how) to tell what is the maximum number of equivalence classes generated by a DFA as per Myhill-Nerode theorem (assuming it has no redundant transitions) as a function of number of accepting and rejecting states and cardinality of its alphabet. My guess is that it should be something like $\log(n) \cdot |{\Sigma}|$, where $n$ is the number of states, since one could see this as tree of derivations created by something like left-regular grammar equivalent to the same automata, and classes would be the leafs of this tree. But this is just a guess.
What is the maximum number of classes resulting from partitioning by DFA as function of number of states?
automata;finite automata
I'm not sure what you mean by classes, but if you mean MyhillNerode equivalence classes, then the classical construction shows that the (unique) minimal DFA has as many states as equivalence classes.
_webapps.17812
I wanted to create official Facebook page for my organization, but it already exists as a passive page. I mean, there's just something like an article copied from Wikipedia and nothing more. Seems like nobody is managing it.Nevertheless, it has over 3.000 fans!Is there any possibility to take over this site, without need to say to all of these people Hey, we are here now, come and click 'like it' again?
Taking over Facebook page
facebook;facebook pages
null
_softwareengineering.188299
I have a private method in my test class that constructs a commonly used Bar object. The Bar constructor calls someMethod() method in my mocked object:private @Mock Foo mockedObject; // My mocked object...private Bar getBar() { Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()}In some of my test methods I want to check someMethod was also invoked by that particular test. Something like the following:@Testpublic void someTest() { Bar bar = getBar(); // do some things verify(mockedObject).someMethod(); // <--- will fail}This fails, because the mocked object had someMethod invoked twice. I don't want my test methods to care about the side effects of my getBar() method, so would it be reasonable to reset my mock object at the end of getBar()?private Bar getBar() { Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod() reset(mockedObject); // <-- is this OK?}I ask, because the documentation suggests resetting mock objects is generally indicative of bad tests. However, this feels OK to me.AlternativeThe alternative choice seems to be calling:verify(mockedObject, times(2)).someMethod();which in my opinion forces each test to know about the expectations of getBar(), for no gain.
Is this an appropriate use of Mockito's reset method?
java;mocking
I believe this is one of the cases where using reset() is ok. The test you are writing is testing that some things triggers a single call to someMethod(). Writing the verify() statement with any different number of invocations can lead to confusion.atLeastOnce() allows for false positives, which is a bad thing as you want your tests to always be correct.times(2) prevents the false positive, but makes it seem like you are expecting two invocations rather than saying i know the constructor adds one. Further more, if something changes in the constructor to add an extra call, the test now has a chance for a false positive. And removing the call would cause the test to fail because the test is now wrong instead of what is being tested is wrong.By using reset() in the helper method, you avoid both of these issues. However, you need to be careful that it will also reset any stubbing you have done, so be warned. The major reason reset() is discouraged is to preventbar = mock(Bar.class);//do stuffverify(bar).someMethod();reset(bar);//do other stuffverify(bar).someMethod2();This is not what the OP is trying to do. The OP, I'm assuming, has a test that verifies the invocation in the constructor. For this test, the reset allows for isolating this single action and it's effect. This one of the few cases with reset() can be helpful as. The other options that don't use it all have cons. The fact that the OP made this post shows that he is thinking about the situation and not just blindly utilizing the reset method.
_webmaster.34754
I believe that images on the same domain can contribute to search engine rankings (mainly Google), example:http://example.com/image.jpg helps http://example.comSo it is my understanding that using a images on a different domain or a (CDN) content delivery network is not good for SEO. A popular solution is to use a sub domain, such as:http://cdn.example.com/image.jpgQuestion(s):Does hosting images on a sub domain impact SEO?Does hosting images on a different domain impact SEO?Does hosting images on a CDN impact SEO?
Does Google reward sites for using images from different domains, sub domains and CDN's?
seo;google;domains;dns;cdn
Google has said that it sees whatever.example.com as a different site than www.example.com for instance. So, it would make sense that for SEO purposes, hosting the pictures on a sub domain would be a bad idea. However, Google at the same time actively promote the use of CDN's for performance purposes.Google does not consist of just computers, but rather a lot of people who check the algorithms all the time, which is why I'm pretty sure that using a CDN should have no adverse effect on your SEO rankings.But as always when it comes to SEO questions, it's a guessing game and the rules can change with Google's will (or ill-will)...So to sum up:http://cdn.example.com/image.jpg should rank as effectively as http://example.com/image.jpgI doubt it will boost the main http://example.com, however I don't think it'll hurt either.It shouldn't rank differently.Using a CDN shouldn't sacrifice ranking. Perhaps there might be a dip for a while until Google realizes you're using a CDN, but it should bounce back.
_codereview.43920
At the innermost loop of my software is a lookup of a function value from a piecewise defined function with interpolation between the sample points.Illustration:* * * * * * |--|------|------|--------X---------|-------------|There are several different interpolation methods in between the sample points.My current implementation consists of two arrays, one for the interval endpoints and one for the function values. Searching is done via std::upper_bound if the array is large and find_if if the arrays are small. Based on the access patterns the speed improved tremendously by adding a cache value for the previous positions interval and checking if it is still valid for the new position[1%] if (x >= *cache && x < *(cache + 1)) { outside = false; position = cache;} else if (x < *begin || x > *end) { outside = true;} else { outside = false; if (n_ < 64) {[3%] position = std::find_if(begin, end, std::bind2nd(std::greater_equal<argument_type>(), x)) - 1; } else { position = std::upper_bound(begin, end, x) - 1; } cache = position ;}The lookup currently still takes about 5% of total execution time, which seems too much.I have indicated costs of the most expensive lines which is the comparison with the cached position [1%] and the linear search [3%].Is there a faster way to lookup the interval which contains X?EditI have included the switch after profiling since Linear search can faster for small arrays (and there are a lot of small arrays).Edit It seems the std::find_if implemenation is actually faster than binary search after all.I have made a test here: http://ideone.com/Fo5ZeW#include <iostream>#include <ctime>#include <algorithm>using namespace std;double* binary_search8(double* arr, const double& x){ if (x<arr[4]) { if(x<arr[2]) { if(x<arr[1]) { return arr; } else { return arr + 1; } } else { //2..3 if(x<arr[3]){ return arr + 2; } else { return arr + 3; } } } else { // 4..7 if(x<arr[6]) { if(x<arr[5]) { return arr + 4; } else { return arr + 5; } } else { //6..7 if(x<arr[7]) { return arr + 6; } else { return arr + 7; } } }}double* binary_search16(double* arr, const double& x){ if (x<arr[8]) return binary_search8(arr, x); else return binary_search8(arr+8, x);}int main() {double test[16] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150}; vector<double> test_vals; size_t num_elem = 10000000; for (size_t i=0; i<num_elem; i++) test_vals.push_back(rand()%150); clock_t begin, end; double elapsed_secs; // Linear search double linavg = 0; begin = clock(); for (size_t i=0; i<num_elem; i++) { linavg += *(find_if(test, test+16, bind2nd(std::greater_equal<double>(), test_vals[i]))-1); } end = clock(); elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << linear secs: <<elapsed_secs << , testval = << linavg << std::endl; // Binary search double binavg = 0; begin = clock(); for (size_t i=0; i<num_elem; i++) { binavg += *binary_search16(test, test_vals[i]); } end = clock(); elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << binary secs: <<elapsed_secs << , testval = << binavg << std::endl; // Binary search 2 double binavg2 = 0; begin = clock(); for (size_t i=0; i<num_elem; i++) { binavg2 += *(std::upper_bound(test, test+16, test_vals[i])-1); } end = clock(); elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << binary2 secs: <<elapsed_secs << , testval = << binavg2 << std::endl; return 0;}
How to speed up interval lookup for a piecewise defined function?
c++;optimization;performance;lookup
null
_unix.381043
I am currently running Linux Mint 18.2 Xfce (64-bit), and would like to use Compton as the default window manager. Linux Mint provides a handy tool called Desktop Settings for choosing window managers with ease.I choose Compton to eliminate my screen-tearing issues. It works very well, but when I reboot, screen tearing is back. I open Desktop Settings again, and Xfwm4 + Compton is still highlighted, but it acts as though Xfwm4 + Compositing were selected instead. If I choose any other item in the list and then change back to Compton, screen-tearing is eliminated until the next reboot. This is highly annoying. Is there any configuration file I can edit to make Linux Mint load Compton by default?
Make Linux Mint choose Compton by default?
linux mint;window manager;compton
null
_vi.9368
In vim you can do daw to delete the entire word, but it also removes the space after the word, (caw too).Is there a way to operate on the entire word without effecting the space around it?For examplea d c ^Performing caw -> bGives us:a bcIs there a way spaces can be treated as other delimiters, brackets for eg, which would give us: a b c ?While this isn't what you would do as a user, it makes writing macros more difficult, since surrounding delimiters aren't as predictable.Note, this is quite similar to this question, but not identical since the word may be surrounded by tabs or other delimiters.https://stackoverflow.com/questions/1607904/vim-deleting-from-current-position-until-a-space
How to operate on all of a word without its surrounding space?
cut copy paste;cursor motions;whitespace
Yes, you can use the iw object. For example, diw or ciw etc. You can read more about the various text objects available to you here.In this particular case, rather than ciw, you could just use cw, since it happens to be equivalent to ce. This is a special case, since for example dw would delete the extra space. You can read more about this behavior here in the documentation.
_softwareengineering.283722
I've just been handed an MVC2 application and noticed that there is no bundling or minifying of the JavaScript or Stylesheets. I've used the built in bundling and minifying logic that comes out the box with MVC3+ but unfortunately this doesn't seem to be available with MVC2.I am unable to upgrade the project to a later version so my question is as follows...What are my options for bundling and minifying within an MVC2 application?
Bundling and minifying options for MVC2
javascript;asp.net;asp.net mvc;css
You can manually minify and bundle the files and add some compilation instructions to switch between the two options depending on whether you are building for release or debugIf its your own javascript/css and it changes often you can automatic the minify process into your build script.
_webmaster.12833
Everytime I open google analytics account I get some default date range which is one month from yesterday to yesterday.Is there a way to set default to bestart: some day I defineend: last possible day there is
End date on google analytics
google analytics
null
_codereview.111508
I am trying to learn how to build a very basic MVC structure before jumping on rails and other frameworks. I am working from a .txt file, and I organized a project into four parts: a model, a view, a controller, and a runner. .txt file pattern:line1 -> questionline2 -> answerline3 -> #blank lineline4 -> questionline5 -> answerline6 -> and so on.runner.rb:require_relative 'view'require_relative 'model'require_relative 'controller'file = 'flashcard_samples.txt'go = Controller.new(file)view.rbrequire_relative 'model'class View def initialize(question) @question = question puts Question: + question endendcontroller.rbrequire_relative 'model'class Controller def initialize(filename) a = Model.new(filename) a.play endendmodel.rbrequire_relative 'view'class Model attr_reader :data, :questions, :answers, :punchline def initialize(filename) @data = [] @questions = [] @answers = [] @score = 0 @file = File.open(filename) end def play welcome_message parse startquestions end def parse @file.each_line do |line| @data << line end end def checkanswer @goodanswer = false @oneanswer == @useranswer ? @goodanswer = true && @score += 1: @goodanswer = false && score += 0 end def displaypunchline if @goodanswer == true puts well done else puts the good answer was #{@oneanswer} end end def displayscore puts Your score is now: + @score.to_s end def display_separation puts -------------------------------------------------------------------------- end def getuserinput @useranswer = gets.chomp end def crazygameloop @counter = 1 loop do break if @counter >= @data.length - 1 @questions = @data.unshift[@counter-1].tr(\n,) @oneanswer = @data.unshift[@counter].tr(\n,) @onequestion = View.new(@questions) @data.unshift[@counter+1] @counter += 3 getuserinput checkanswer displaypunchline displayscore display_separation end end def startquestions crazygameloop end def welcome_message puts welcome in my shitty game puts ||||||||||||||||||||||||| endendSo far it's working but it's un-DRY, not very readable and probably a bad/incomplete MVC implementation. I'm looking for advice on how I should re-organize my model in order to increase my view responsibilities and optimize my controller in case I would add other features. Any input appreciated.
MVC flash card application
ruby;mvc;quiz
All the parts are here, but your model is taking on too much work. First, let's tackle one of the three hardest things in computer programming: Naming things.Naming Classes in an MVC ApplicationYou have three classes, called aptly Controller, View and Model. I know you are trying to learn the MVC pattern, but an important aspect or learning this pattern is that names should make sense beyond telling you which layer in MVC they go. A convention for naming things is a must.The Rails way of naming things all starts with the model. In your case, your Model class contains data about a quiz, so Quiz is a perfect name for that class. The controller that handles user interaction for Quiz objects should be called QuizesController -- note that Quiz is pluralized, because the controller object handles all quizes, not just one.After that, a QuizView seems like a good name for the view object.Really if you think about it, a quiz is composed of two other things: quiz questions and quiz answers. We need to properly model a quiz before anything else. The Model layer in MVC is the foundation -- the bedrock of your application.Know Your Domain: Properly Modeling Your QuizWe actually have a need for 3 model classes:QuizQuizQuestionQuizAnswerA quiz has one or more questions. An answer requires a question. We need to model this in Ruby.class Quiz attr_reader :questions def initialize(questions) @questions = questions @grade = 0 end def answer_question(question, answer_text) question = questions[question_number - 1] question.answer answer_text end def grade return @grade if @grade > 0 number_correct = 0 questions.each do |question| number_correct += 1 if question.answered_correctly? end @grade = calculate_grade number_correct end def retake @grade = 0 questions.each do |question| question.remove_answer end end def quesion_count questions.count endprivate def calculate_grade(number_correct) number_correct / questions.count endendA Quiz is a tad more complex, but it just needs a list of QuizQuestions in its constructor. All other operations on the quiz are public methods, some of which are delegated to the QuizQuestion class.class QuizQuestion attr_reader :text, :answer, :expected_answer def initialize(text, expected_answer) @text = text @expected_answer = expected_answer end def answer(answer_text) @answer = QuizAnswer.new self, answer_text end def answered_correctly? return @answer.nil? ? false : @answer.correct? end def remove_answer @answer = nil endendThe QuizQuestion class glues the quiz together with the answer, which we will see in a moment. Again, the constructor doesn't do much, except take in the data it needs in order to exist: The question text and the expected answer. The answer method creates the QuizAnswer object and returns it. The logic of retaking a quiz is also delegated to the remove_answer method.class QuizAnswer attr_reader :question, :text def initialize(question, text) @question = question @text = text end def correct? return question.expected_answer == text end def question_text question.text endendLastly the QuizAnswer class glues together the quiz question and the user's answer, along with the logic for testing the answer.Now that we've properly modeled our domain, the Quiz, QuizQuestion and QuizAnswer classes become our Domain Models combining data with business logic (taking a quiz). Next, we will take a step up from the foundation of our application to explore the data access layer, or Repository.The Data Access Layer (Repository)The Repository Pattern decouples the data access from your model and controller. What your controller needs is a QuizRepository object that does all the data access.Since you are going with flat file storage, we want to extract this behavior into its own layer.class QuizRepository def initialize(filename) @filename = filename end def all return @quizes unless @quizes.nil? load @quizes end def find(index) return nil if index < 0 || index > all.count return all[index] end def reload @quizes = nil endprivate def filename @filename end def load questions = [] index = 0 question_text = expected_answer = file = File.open filename file.each_line do |line| if index % 2 == 0 question_text = line else expected_answer = line questions << QuizQuestion.new question_text, expected_answer end index += 1 end @quizes << Quiz.new questions endendThe QuizRepository class needs a filename, and it lazy loads the quiz objects only when you need to get them.Notice that there is no console interaction. This should be encapsulated by the Controller.Handling User Interaction and Displaying InformationKnowledge of the console, and what to display is the realm of the controller and views.class QuizesController def initialize(quiz_repository) @quiz_repository = quiz_repository end def run counter = 1 quiz = @quiz_repository.all.first puts Welcome to the Quiz! puts -------------------- quiz.questions.each do |question| puts QuizQuestionView.new question, counter answer_text = gets.chomp answer = quiz.answer_question question, answer_text puts QuizAnswerView.new quiz, answer counter += 1 end endendThe main loop is inside the controller, since the controller in MVC responds to user input. The controller needs a quiz repository which is the only argument in its constructor. You'll also notice there are 2 views: QuizQuestionView and QuizAnswerView.class QuizQuestionView def initialize(question, question_number) @question = question @question_number = question_number end def to_s Question \##{@question_number}: #{@question.text} endendclass QuizAnswerView def initialize(quiz, answer) @quiz = quiz @answer = answer end def to_s text = if answer.correct? well done else the correct answer is #{answer.question_text} end text + \nYour score is now #{@quiz.grade} + \n-------------------------------------------------------------------------- endendAlso notice that there are no calls to gets or puts in the view classes. These classes are responsible for output only. The fact that you are outputting to a console is the responsibility of the Controller, since the Controller knows you are interacting with the user via the console. The to_s method is defined, which returns a string that the Controller then prints to the standard output of the console.Putting All The Layers TogetherNow we actually need to run the program:#!/bin/env rubyquiz_repository = QuizRepository.new /data/quiz.txtcontroller = QuizController.new quiz_repositorycontroller.runThe whole application is started, run and exits in three lines of code.
_unix.303743
I had a VM with a swap partition that I deleted. I now have two primary partitions sda1 and sda2, both ext4. In windows they would be seen as separate drives, but how does linux use these 2 partitions vs one large sda1? My searches just end up talking about how to make partitions or about advantages of partitions.
How is sda1 used differently from sda2?
partition
In practice, they will effectively be used as two separate drives by default, much like in Windows, as you state. For example, if /dev/sda1 has 50MB free and /dev/sda2 has 50MB free and you try to write a 75MB file to either, it will fail with a disk full error despite both of these partitions being divisions of the same disk.
_codereview.164976
I am using an CloseableHttpAsyncClient the following way: public class AsyncHttpClient { private static final Logger logger = LogManager.getLogger(Main.class); private static CloseableHttpAsyncClient HTTP_ASYNC_CLIENT = null; private static HttpPost HTTP_POST = null; private static HttpContext HTTP_CONTEXT; private static PropertiesLoader PROP_LOADER = new PropertiesLoader(); private static Properties PROPERTIES = PROP_LOADER.initProp(./config/config.properties); private static final int CON_REQUEST_TIMEOUT = Integer.valueOf(PROPERTIES.getProperty(connectionrequesttimeout)); private static final int CON_TIMEOUT = Integer.valueOf(PROPERTIES.getProperty(connecttimeout)); private static final int CON_SOCKET_TIMEOUT = Integer.valueOf(PROPERTIES.getProperty(sockettimeout)); private static final String CON_URL = PROPERTIES.getProperty(conurl); private static final int CONMANAGER_MAX_TOTAL = Integer.valueOf(PROPERTIES.getProperty(conmanagermaxtotal)); private static final int DEFAULT_MAX_PER_ROUTE = Integer.valueOf(PROPERTIES.getProperty(conmanagermaxdefaultperroute)); //Reusable connection private static RequestConfig createConnConfig() { return RequestConfig.custom() .setConnectionRequestTimeout(CON_REQUEST_TIMEOUT) .setConnectTimeout(CON_TIMEOUT) .setSocketTimeout(CON_SOCKET_TIMEOUT).build(); } private static PoolingNHttpClientConnectionManager createPoolingConnManager() throws IOReactorException { IOReactorConfig config = IOReactorConfig.DEFAULT; ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor); cm.setMaxTotal(CONMANAGER_MAX_TOTAL); cm.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE); return cm; } private static synchronized CloseableHttpAsyncClient getCloseableClient() throws IOReactorException { if (HTTP_ASYNC_CLIENT == null) { logger.info(New Async Client created ); HTTP_ASYNC_CLIENT = HttpAsyncClientBuilder.create() .setDefaultRequestConfig(createConnConfig()) .setConnectionManager(createPoolingConnManager()).build(); HTTP_ASYNC_CLIENT.start(); } return HTTP_ASYNC_CLIENT; } private static synchronized HttpPost getPost() { if (HTTP_POST == null) { logger.info(New Post created ); HTTP_POST = new HttpPost(CON_URL); HTTP_POST.setHeader(Accept, application/json); HTTP_POST.setHeader(Content-type, application/json); } return HTTP_POST; } public static void postData(String data) throws Exception { //TODO - needs cleanup StringEntity entity = new StringEntity(data); HttpPost httpPost = getPost(); httpPost.setEntity(entity); getCloseableClient().execute(httpPost, HTTP_CONTEXT, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { logger.info(Completed); } @Override public void failed(Exception e) { logger.info(Completed with exception + e); } @Override public void cancelled() { logger.info(Cancelled ); } }); }}Throughout the program I want only one instance to be alive, I am also using multiple threads to post data using the above class.
Async HTTP client the right way
java;http
null
_unix.164197
I have an xml file that have different nodes, I want to split files like this:<unix> <mm></unix><osx> <nn></osx>When I run the script I want it to make one xml file called unix.xml,which contains this<unix <mm></unix>And then another xml file called osx.xml, which contains this<osx> <nn></osx>
Split XML file into multiple files
bash;scripting;conversion;xml
null
_codereview.26167
I am developing a script that will act as a surrogate of sorts for a web portal and an email blast program. The web portal is used to create web-to-print files and is very good at creating print-ready PDF files, but currently lacks any email blast or HTML output options for the end user. In order to circumvent this limitation, my script will parse data that is in an email that is automatically sent after each order is placed. In this email are variables from the site that user has submitted as well as images that the user has uploaded. My code still needs to archive the emails after they have been zipped (to eliminate duplicate files) and send the zip file to the person who ordered the HTML. Despite not being 100%, I was hoping to get some good feedback/criticism on what I have so far. I am not brand new to Python, but I am self taught and figured this is the best place to learn how to refine my code.Here is my current (expected) workflow:User logs into web portal to order.User uploads images, enters text into fields, and receives a proof of their HTML.User completes order, checks out. Process is now out of user's hands.An email is generated and sent to me. This email includes all information necessary to create HTML markup.Script reads email, downloads attachments, assigns values to variables based on their markup in the email. Specific characters are used to identify text strings to be used.Script creates HTML markup using assigned variables, then adds .html file and all included images to a .zip file fit for distribution.Script archives email to prevent duplicate zip files being created on next run.An email is sent to the user with the zip file attached.User uploads zip file to their own specific email blast program.Links to my code and supporting files are here:ScriptEmail filesimport email, getpass, imaplib, os, re, csv, zipfile, glob, threadingdetach_dir = 'directory' # directory where to save attachmentsuser = (username)pwd = (password)# connecting to the gmail imap serverm = imaplib.IMAP4_SSL(imap server)m.login(user,pwd)m.select(INBOX) # here you a can choose a mail box like INBOX instead# use m.list() to get all the mailboxesresp, items = m.search(None, ALL) # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)items = items[0].split() # getting the mails idfor emailid in items: resp, data = m.fetch(emailid, (RFC822)) # fetching the mail, `(RFC822)` means get the whole stuff, but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue # we use walk to create a generator so we can iterate on the parts and forget about the recursive headache for part in mail.walk(): # each part is a either non-multipart, or another multipart message # that contains further parts... Message is organized like a tree if part.get_content_type() == 'text/plain': content = part.get_payload() message = re.compile(r'\%(.+?)\%', re.DOTALL).findall(content) message = re.sub(r'=\\r\\', '', str(message)) message = re.sub(r'\[\'', '', str(message)) message = re.sub(r'\'\]', '', str(message)) token = re.compile(r'\$(.+?)\$', re.DOTALL).findall(content) token = re.sub(r'\[\'', '', str(token)) token = re.sub(r'\'\]', '', str(token)) tag = re.compile(r'\^(.+?)\^', re.DOTALL).findall(content) tag = re.sub(r'\[\'', '', str(tag)) tag = re.sub(r'\'\]', '', str(tag)) print message print token print tag #print part.get_payload() # prints the raw text # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue filename = part.get_filename() counter = 1 # if there is no filename, we create one with a counter to avoid duplicates if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1 att_path = os.path.join(detach_dir, filename) #Check if its already there if not os.path.isfile(att_path) : # finally write the stuff fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() path = detach_dir os.chdir(path) image1 = str(glob.glob('upload-photo1*')) image2 = str(glob.glob('upload-photo2*')) image3 = str(glob.glob('upload-photo3*')) image1 = re.sub(r'\[\'', '', image1) image1 = re.sub(r'\'\]', '', image1) image2 = re.sub(r'\[\'', '', image2) image2 = re.sub(r'\'\]', '', image2) image3 = re.sub(r'\[\'', '', image3) image3 = re.sub(r'\'\]', '', image3) htmlFile = str(token)+'.html' #if tag == 'email_blast_demo': htmlCode = ('''<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd> <html xmlns=http://www.w3.org/1999/xhtml><head> <meta http-equiv=Content-Type content=text/html; charset=utf-8 /> <title>Untitled Document</title></head><body> <table width=554 border=0 cellspacing=0 cellpadding=0 align=center><tr><td> <img src='''+image1+''' width=554 height=186 /></td></tr><tr><td> <p style=font-family:Arial, Helvetica, sans-serif; font-size:11pt; line-height:14pt;> <br />Dear [Fld:FirstName],<br /><br />'''+str(message)+'''<br /><br /><a href=PLACEHOLDER> <img src='''+image2+''' width=248 height=38 alt=Opt-in for men\'s health tips now /></a> <br /><br /><br /><img src='''+image3+''' width=167 height=62 align=right /><br /> <p style=font-family:Arial, Helvetica, sans-serif; font-size:10pt;></td></tr></table> </body></html>''') htmlData = open(os.path.join('directory', htmlFile), 'w+') htmlData.write(htmlCode) print htmlFile+' Complete' htmlData.close() allFiles = [f for f in os.listdir(path) if not f.endswith('.zip')] for file in allFiles: archive = zipfile.ZipFile(token+'.zip', mode='a') archive.write(file) archive.close() os.unlink(file)# This script will access a set email account, parse the text and attachments of each email, create HTML markup# and zip the files together. This script assumes a set template for the HTML. I will most likely have to change# this in order to incorporate multiple templates. The HTML markup for each template will be sent in the email# and be parsed in the ame fashion as the `token` and `tag` variables above.## What still needs to be done:# 1) Archive email after being zipped so that duplicates are not created# 2) Email .zip file to requestor (person who ordered)
Parse emails and create HTML markup from attachments
python;parsing;email
PEP8You're not following PEP8, Python's official coding style guide, for example:Don't put multiple imports on the same linePut a space after commas in parameter lists, so m.login(user, pwd) instead of m.login(user,pwd)There shouldn't be whitespace after :Use at least 2 spaces before inline comments (before each # comment)Put a space after # when starting comments, so # comment instead of #commentSome lines are too long (longer than 79 characters)Bad practicesRemove unused imports: getpass, csv, threadingNo need for the parens in user = (username), and it may get confused as a tuple (which it isn't)The variable m is poorly named: judging by the name I might guess it's a message, when it's actually a mailboxAt the point where you do str(message), message might not have been assigned yetAt the point where you do os.listdir(path), path might not have been assigned yetIn this code:resp, items = m.search(None, ALL)items = items[0].split() # getting the mails idfor emailid in items: resp, data = m.fetch(emailid, (RFC822))The initialization of resp is pointless, because it will be reassigned anyway in the loop. Effectively you throw away the first assignment of resp. In such cases a common practice is to use _ as the variable name, like this:_, items = m.search(None, ALL)On closer look, I see that after the 2nd assignment too,resp is not used again. So it could be replaced with _ there too.message = re.compile(r'\%(.+?)\%', re.DOTALL).findall(content)This is the same as the above but simpler:message = re.findall(r'\%(.+?)\%', content, re.DOTALL)But since you have this code inside a for loop,it would be best to compile the pattern once before the loop,and reuse it inside, like this:re_between_percent = re.compile(r'\%(.+?)\%', re.DOTALL)for part in mail.walk(): # ... message = re_between_percent.findall(content)Do the same for the other statements too where you do re.compile(...).findall(...).Instead of this: htmlData = open(os.path.join('directory', htmlFile), 'w+') htmlData.write(htmlCode) print(htmlFile + ' Complete') htmlData.close()The Pythonic way to work with files: with open(os.path.join('directory', htmlFile), 'w+') as htmlData: htmlData.write(htmlCode) print(htmlFile + ' Complete')