text
stringlengths
175
47.7k
meta
dict
Q: MongoDB & MySQL relationships in jenssegers/laravel-mongodb Let's begin with some plain code. I have two following models. First is using MySQL: class Phrase extends \Eloquent { public function positions() { return $this->hasMany('Position'); } public function getIdAttribute($id) { return (int) $id; } } and second is using MongoDB: use Jenssegers\Mongodb\Model as Eloquent; class Position extends Eloquent { protected $collection = 'positions'; protected $connection = 'mongodb'; public function phrase() { return $this->belongsTo('Phrase'); } } In my controller I want to get phrase positions: Phrase::find(1)->positions which is generating query positions.find({"positions.phrase_id":1}, []) instead of positions.find({"phrase_id":1}, []) How I can fix it? The problem is inside HasMany method (http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Model.html#_hasMany). A: I managed to get the functionality by creating my own function inside the model class Phrase extends \Eloquent { public function positions() { return Position::where('phrase_id', '=', (int) $this->id)->get(); return $this->hasMany('Position'); } } $positions = Phrase::find(1)->positions(); Anyway, this solution is not a great replacement, because it's breaking convention. Third programmers may not know how to use this relationship.
{ "pile_set_name": "StackExchange" }
Q: Removing a character from within a vector element I have a vector of strings: str.vect<-c ("abcR.1", "abcL.1", "abcR.2", "abcL.2") str.vect [1] "abcR.1" "abcL.1" "abcR.2" "abcL.2" How can I remove the third character from the right in each vector element? Here is the desired result: "abc.1" "abc.1" "abc.2" "abc.2" Thank you very much in advance A: You can use nchar to find the length of each element of the vector > nchar(str.vect) [1] 6 6 6 6 Then you combine this with strtrim to get the beginning of each string > strtrim(str.vect, nchar(str.vect)-3) [1] "abc" "abc" "abc" "abc" To get the end of the word you can then use substr (actually, you could use substr to get the beginning too...) > substr(str.vect, nchar(str.vect)-1, nchar(str.vect)) [1] ".1" ".1" ".2" ".2" And finally you use paste0 (which is paste with sep="") to stick them together > paste0(strtrim(str.vect, nchar(str.vect)-3), # Beginning substr(str.vect, nchar(str.vect)-1, nchar(str.vect))) # End [1] "abc.1" "abc.1" "abc.2" "abc.2" There are easier ways if you know your strings have some special characteristics For instance, if the length is always 6 you can directly substitute the nchar calls with the appropriate value. EDIT: alternatively, R also supports regular expressions, which make this task much easier. > gsub(".(..)$", "\\1", str.vect) [1] "abc.1" "abc.1" "abc.2" "abc.2" The syntax is a bit more obscure, but not that difficult once you know what you are looking at. The first parameter (".(..)$") is what you want to match . matches any character, $ denotes the end of the string. So ...$ indicates the last 3 characters in the string. We put the last two in parenthesis, so that we can store them in memory. The second parameter tells us what you want to substitute the matched substring with. In our case we put \\1 which means "whatever was in the first pair of parenthesis". So essentially this command means: "find the last three characters in the string and change them with the last two". A: The solution provided by @nico seems fine, but a simpler alternative might be to use sub: sub('.(.{2})$', '\\1', str.vect) This searches for the pattern of: "any character (represented by .) followed by 2 of any character (represented by .{2}), followed by the end of the string (represented by $)". By wrapping the .{2} in parentheses, R captures whatever those last two characters were. The second argument is the string to replace the matched substrings with. In this case, we refer to the first string captured in the matched pattern. This is represented by \\1. (If you captured multiple parts of the pattern, with multiple sets of parentheses, you would refer to subsequent captured regions with, e.g. \\2, \\3, etc.) A: str.vect<-c ("abcR.1", "abcL.1", "abcR.2", "abcL.2") a <- strsplit(str.vect,split="") a <- strsplit(str.vect,split="") b <- unlist(lapply(a,FUN=function(x) {x[4] <- "" paste(x,collapse="")} )) If you want to parameterize it further change 4 to a variable and put the index of the character you want to remove there.
{ "pile_set_name": "StackExchange" }
Q: Sample settings.xml required Can somebody provide me link to a sample settings.xml? My problem is that I have eclipse maven plugin. This eclipse is one which I have copied from somewhere and the plugin came with it. Now the settings.xml isn't created as usual in .m2 folder. So I need a sample settings.xml so that the maven plugin works in my eclipse. NB: I am using eclipse Galileo 3.5 Thanks. A: As mentioned in the m2eclipse FAQ: How to Configure Proxy and location of Maven local repository Eclipse Plugin is using Maven’s settings.xml for proxy, local repository location and any other environment-specific configuration. This way we can use same settings between the command line and the IDE. Default location of the settings.xml is at <user home>/.m2/settings.xml, but you can also specify location of the global settings, i.e. one in <maven home>/conf/settings.xml. You can see what a minimal settings.xml looks like in this blog post on "Build a mixed Scala 2.8/Java application from scratch with Maven (Eclipse Settings)": <settings xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <localRepository> C:/Documents and Settings/Administrator/.m2/repository </localRepository> <interactiveMode>true</interactiveMode> <usePluginRegistry>false</usePluginRegistry> <offline>false</offline> </settings> (Change the 'localRepository' path to adapt it to your encvironment) All the details on a maven settings.xml are in the Maven Setting reference page.
{ "pile_set_name": "StackExchange" }
Q: std::vector without exceptions: warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc I am trying to insert a moveable, non-copyable object into std::vector. I reduced the original code to this example: #include <vector> class MovingClass { public: MovingClass(const int value) : _value(new int(value)) {} //! No copy allowed MovingClass(const MovingClass& src) = delete; MovingClass& operator=(const MovingClass& src) = delete; // move is OK MovingClass(MovingClass&& source) : _value(source._value) { source._value = nullptr; } MovingClass& operator=(MovingClass&& source) { _value = source._value; source._value = nullptr; } ~MovingClass() { delete _value; } // do not mind that this is all kinds of bad, it's just an example int* _value; }; int test_vector_main() { std::vector<MovingClass> containers; containers.push_back({ 42 }); return 0; } The original purpose of the class is closing winapi handles, not deleting pointers. I can reproduce the warning in a blank project if I set "Enable C++ Exceptions" to "No" in Configuration Properties->C/C++->All Options. The project I work with treats warnings as errors and has exceptions disabled. I am not sure what to do except giving up on no-copy rules or enabling the exceptions. I'll enable the exceptions, but if I couldn't what else could I do? Why does push_back even require exceptions? A: Why does push_back even require exceptions? vector::push_back has to do two things: Make sure that there's space for the new element. That could involve allocating memory - which can fail. It reports this failure by throwing an exception. Construct a new element in the vector. That involves calling your class' copy or move constructor - which can fail. Constructors usually report failures by throwing an exception. You can indicate that your move constructor will never fail by marking it as noexcept.
{ "pile_set_name": "StackExchange" }
Q: Redirecting documents folder for windows 7 I have a GPO set to redirect the Documents folder to the H: drive of our students. It works, but conditionally. If the student already has My Pictures, My Videos, and/or My Music folders already in existence within their H: drive, then Documents will not redirect as it automatically creates those folders within. If I delete those three folders from the student's drive, then the folder redirection will then activate. Obviously it is not practical to go into each student's folder and delete these out of there. Is there a workaround or something I am missing? The policy is set for Basic-Redirect everyone's folder to the same location pointing to the target location of the user's home drive. Under the settings of the GPO, all 3 boxes are checked and Policy Removal has "Leave the folder in the new location when policy is removed" selected. A: Turns out the answer to fix this was to uncheck the policy option to grant exclusive rights of the Documents folder to the user. As soon as I unchecked that, everything went just fine.
{ "pile_set_name": "StackExchange" }
Q: problem in configuring clang static analzer i follow the following steps to install and configure clang static analyser.but still i could not run scan-build command in project directory can anyone can give correct tutorial to set path and also run scan-build command.terminal shows "scan-build command not found" the steps i followed: Installation: Navigate to http://clang.llvm.org/StaticAnalysis.html Download the linked checker tarbell (it says tar.bz2, but it's really tar.bz2.tar). Extract that and copy that to a directory on your device. I chose ~/Developer/clang Open terminal and type sudo nano /etc/paths Enter the directory in which you keep your clang stuffs. Press 'Ctrl + X' to Exit, and press 'Y' to save. You're now done with installation. Quit and restart terminal. To use this, First make sure you go into Xcode and "Clean All" before you do anything. When that's all set, open terminal and navigate to the directory of the app you want to build. Enter the following command. Make sure to replace the name od the sdk with the one you currently want to build with. scan-build -k -V xcodebuild -configuration Debug -sdk iphonesimulator3.0 A: I've never added paths that way. But regardless you should not need to. If you added clang to ~/Developer/clang, then just change the command you are using to run it to: ~/Developer/clang/scan-build -k -V xcodebuild -configuration Debug -sdk iphonesimulator3.0
{ "pile_set_name": "StackExchange" }
Q: Can web robots inflate download counts? I have a PHP program connected to an MYSQL database on a website. Upon clicking a link to download a file, the program reads an integer field from the database, increments it, then puts the number back, to count the number of downloads. That program works. The download counts, however, over time, seem to be moderately inflated. Could the download counts be incremented by web robots following the links to download the files? If so, would telling the web robots to ignore the download page on the website, using the robots.txt file, solve the inflated count problem? Here is the PHP code: function updateDownloadCounter($downloadPath, $tableName, $fileNameField, $downloadCountField, $idField) { require("v_config.php"); if(isset($_REQUEST["file_id"]) && is_numeric($_REQUEST["file_id"])) { try { $sql = "SELECT * FROM " . $tableName . " WHERE file_id = " . $_REQUEST[$idField]; $connection = new PDO($dsn, $username, $password, $options); $statement = $connection->prepare($sql); $statement->execute(); $result = $statement->fetchAll(); if ($result && $statement->rowCount() == 1) { foreach ($result as $row) { if(is_file($_SERVER['DOCUMENT_ROOT'].$downloadPath . $row[$fileNameField])) { $count = $row[$downloadCountField] + 1; $sql = "UPDATE " . $tableName . " SET " . $downloadCountField . " = " . $count . " WHERE file_id = " . $_REQUEST[$idField]; $statement = $connection->prepare($sql); $statement->execute(); $documentLocationAndName = $downloadPath . $row[$fileNameField]; header('Location:' . $documentLocationAndName); } } } } catch(PDOException $error) { echo $sql . "<br>" . $error->getMessage(); } } } A: The answer to both of your questions is yes. When a crawler indexes your website, it also looks for related content, akin to creating a sitemap. The first place it looks for related content on a page are the direct links. If you're linking to your files directly on your download page, the crawler will also attempt to index those links. Preventing the crawlers from seeing your download page with robots.txt would prevent this problem, but then you'd be losing potential SEO. And what if a third party links to your downloads directly? If they have their downloads page indexed, your links will still be visible to crawlers. Fortunately, you can disable this behaviour. Simply tell the crawlers that the links on the download page are all canonical ones, by adding the following to the <head> section of the downloads page: <link rel="canonical" href="http://www.example.com/downloads" /> Considering the parameters are essentially different 'pages', crawlers will think that /downloads?file_id=1 is different to /downloads. Adding the above line will inform them that it is the same page, and that they don't need to bother. Assuming that you have actual files that are being indexed (such as PDFs), you can prevent crawlers from indexing them in your .htaccess or httpd.conf: <Files ~ "\.pdf$"> Header set X-Robots-Tag "noindex, nofollow" </Files> As a fallback, you could always check who is attempting to download the file in the PHP itself! It depends how pedantic you want to be (as there are a lot of different crawlers), but this function works pretty well: function bot_detected() { return ( isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider|mediapartners/i', $_SERVER['HTTP_USER_AGENT']) ); } Then simply call it as a conditional before running your try: if (!bot_detected()) { try { } // Will only get executed for real visitors } Also, as an aside, I'd recommend using $_GET["file_id"] over $_REQUEST["file_id"]. $_REQUEST combines $_GET with both $_POST and $_COOKIE, which tend to be used in rather different ways. While this is technically secure if you're only retrieving data, it's far safer to limit the request to a simple $_GET. Hope this helps! :)
{ "pile_set_name": "StackExchange" }
Q: How can I use SSO to login to my Ubuntu machine instead of Local User Management Instead of maintaining local user accounts, I would like to be able to use Ubuntu SSO (Ubuntu One) accounts to authenticate the logins to my Ubuntu machine. Any chance? A: The topic was mooted at the Ubuntu Developer Summit in late 2011. OMG! Ubuntu! covered the topic. The Ubuntu One team liked the idea, but there are many technical challenges before logging in with SSO credentials will be possible. Don't expect to see it anytime soon.
{ "pile_set_name": "StackExchange" }
Q: How to extract text in php using regex My Text : 12a49803-713c-4204-a8e6-248e554a352d_ Content-Type: text/plain; charset="iso-8859-6" Content-Transfer-Encoding: base64 DQrn0Ocg0dPH5MkgyszR6sjqySDl5iDH5OfoyuXq5A0KDQrH5OTaySDH5NnRyOrJIOXP2ejlySAx MDAlDQogCQkgCSAgIAkJICA= --_12a49803-713c-4204-a8e6-248e554a352d_ Content-Type: text/html; charset="iso-8859-6" Content-Transfer-Encoding: base64 PGh0bWw+DQo8aGVhZD4NCjxzdHlsZT48IS0tDQouaG1tZXNzYWdlIFANCnsNCm1hcmdpbjowcHg7 I want to extract iso-8859-6 A: you could do: preg_match('/charset="([^"]+)"/',$string,$m); echo $m[1]; Edit: In case all need matching (prompted from other answer) modify like this: preg_match_all('/charset="([^"]+)"/',$string,$m); print_r($m);
{ "pile_set_name": "StackExchange" }
Q: I just downloaded Ruby 2.0.0 using RubyInstaller, but Ruby -v still says I'm running 1.9.3. What am I doing wrong? I just downloaded Ruby 2.0.0 using RubyInstaller, but Ruby -v still says I'm running 1.9.3. What am I doing wrong? I am running Windows 7 (which I know is not ideal, but is what I'm currently stuck with), and I have successfully run Ruby in the past. Thanks! A: I did a combination of several answers here, including: Uninstalling old versions of Ruby and reinstalling version 2.0.0 Update the path Environment variable to the new path Restart the computer (I think this is what I was missing the whole time) Thanks to everyone who helped!
{ "pile_set_name": "StackExchange" }
Q: What's the term for using the wrong word because it sounds the same? I was reading about various terms for incorrect words, but they didn't seem to fit. I saw a post where someone said "what do you like to do when you're board?". That kind of thing. Also, would that be considered a mistake in grammar? I didn't think so, but my friend insists it is. I'm not sure if there even is a word for that kind of mistake, but was just curious about it. Thanks! A: Actually, a malapropism is the substitution of a word that sounds similar, but not identical, to the intended word (such as when Archie on "All in the Family" referred to the "Women's Lubrication Movement", rather than "Liberation"). In Strahan's example, "bored" and "board" are words that sound identical but are spelled differently. These are called homophones. As far as I know, Strahan's example would simply be called a misspelling. I don't know of any term that specifically means substituting a homonym. In a case like this, it's irrelevant that "board" also happens to be a word, as its meaning is obviously unrelated to the text. A: Malapropism fits the bill I think. Form oxford: The mistaken use of a word in place of a similar-sounding one, often with an amusing effect (e.g. ‘dance a flamingo’ instead of flamenco). Origin Mid 19th century: from the name of the character Mrs Malaprop in Sheridan's play The Rivals (1775) + -ism. EDIT: I know this doesn't seem to satisfy the OP's example of bored/board. But the OP maybe couldn't think of a better example. It satisfies what they asked for in the title: "What's the term for using the wrong word because it sounds the same"
{ "pile_set_name": "StackExchange" }
Q: Searching multiple repeating patterns of text using regular exressions I am trying to search for texts from a document, which have repeating portions and occur multiple times in the document. However, using the regex.match, it shows only the first match from the document and not others. The patterns which I want to search looks like: clauses 5.3, 12 & 15 clause 10 C, 10 CA & 10 CC The following line shows the regular expression which I am using. regex_crossref_multiple_1=r'(clause|Clause|clauses|Clauses)\s*\d+[.]?\d*\s*[a-zA-Z]*((,|&|and)\s*\d+[.]?\d*\s*[A-Z]*)+' The code used for matching and the results are shown below: cross=regex.search(regex_crossref_multiple_1,des) (des is string containing text) For printing the results, I am using print(cross.group()). Result: clauses 5.3, 12 & 15 However, there are other patterns as well in des which I am not getting in the result. Please let me know what can be the problem. The input string(des) is can be found from following link. https://docs.google.com/document/d/1LPmYaD6VE724OYoXDGPfInvx8WTu5JfrTqTOIv8zAlg/edit?usp=sharing In case, the contractor completes the work ahead of stipulated date of completion or justified extended date of completion as determined under clauses 5.3, 12 & 15, a bonus @ 0.5 % (zero point five per cent) of the tendered value per month computed on per day basis, shall be payable to the contractor, subject to a maximum limit of 2 % (two percent) of the tendered value. Provided that justified time for extra work shall be calculated on pro-rata basis as cost of extra work excluding amount payable/ paid under clause 10 C, 10 CA & 10 CC X stipulated period /tendered value. The amount of bonus, if payable, shall be paid along with final bill after completion of work. Provided always that provision of the Clause 2A shall be applicable only when so provided in ‘Schedule F’ A: You could match clauses followed by an optional digits part and optional chars A-Z and then use a repeating pattern to match the optional following comma and the digits. For the last part of the pattern you can optionally match either a ,, & or and followed by a digit and optional chars A-Z. \b[Cc]lauses?\s+\d+(?:\.\d+)?(?:\s*[A-Z]+)?(?:,\s+\d+(?:\.\d+)?(?:\s*[A-Z]+)?)*(?:\s+(?:[,&]|and)\s+\d+(?:\.\d+)?(?:\s*[A-Z]+)?)?\b Explanation \b Word boundary [Cc]lauses?\s+\d+(?:\.\d+)? Match clauses followed by digits and optional decimal part (?:\s*[A-Z]+)? Optionally match whitespace chars and 1+ chars A-Z (?: Non capture group ,\s+\d+(?:\.\d+)? Match a comma, digits and optional decimal part (?:\s*[A-Z]+)? Optionally match whitespace chars and 1+ chars A-Z )* Close group and repeat 0+ times (?: Non capture group \s+(?:[,&]|and) Match 1+ whitespace char and either ,, & or and \s+\d+(?:\.\d+)? Match 1+ whitespace chars, 1+ digits with an optional decimal part (?:\s*[A-Z]+)? Match optional whitespace chars and 1+ chars A-Z )? Close group and make optional \b Word boundary Regex demo
{ "pile_set_name": "StackExchange" }
Q: Discover multiple jwplayers on a page I need to write some javascript code which will loop through all jwplayers available on a page. The jwplayer api has a function selectPlayer(): var player = jwplayer.api.selectPlayer(); But this only returns the first player on the page. I can't see a way to find them all? A: There are a few ways to do this, but the simplest would be to call "jwplayer(x)" - where x is a zero-based index relating to an Array of jwplayers on the page - as this will return the Player instance at that index. So for JW7 / JW8 you could simply do the following: var jwpAll = document.querySelectorAll('.jwplayer'); for(var jwpIndex=0,jwpTotal=jwpAll.length;jwpIndex<jwpTotal;jwpIndex++){ var player = jwplayer(jwpIndex); }
{ "pile_set_name": "StackExchange" }
Q: ASPX Jquery 1.11 $(Document).ready(function() {} was skipped I'm a freshman to Jquery, and I tried to load this when the html was opened, but ready() was not called. <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script src="Script/jquery-1.11.1.js"></script> <script type="text/javascript"> $(Document).ready(function() { alert("HelloWorld"); }); }) </script> <title></title> The alert() didn't pop up. A: There are two issues in your code: It is "document", not "Document". Case matters. You have an extra "})" at the end of your script. Your code works after those two corrections: <script type="text/javascript"> $(document).ready(function() { alert("HelloWorld"); }); </script> Demo: http://jsfiddle.net/BenjaminRay/2tvv6tLc/
{ "pile_set_name": "StackExchange" }
Q: Xterm: working with multiple tabs I am used to working with multiple tabs in gnome. Opening a new tab can be done easily with Ctrl+Shift+T as well as switching between tabs (Left Alt+tab number). What are the Xterm equivalents? A: You need to use an external tool called a terminal multiplexer such as GNU screen/tmux. I don't think that xterm itself can open multiple tabs.
{ "pile_set_name": "StackExchange" }
Q: Helper Devise: could not find the `Warden::Proxy` instance on request environment I try to use Devise for my Rails app. I can sign up and login but when I go to my other page "build" I get the following error: Devise::MissingWarden in Home#show Devise could not find the Warden::Proxy instance on your request environment. Make sure that your application is loading Devise and Warden as expected and that the Warden::Manager middleware is present in your middleware stack. If you are seeing this on one of your tests, ensure that your tests are either executing the Rails middleware stack or that your tests are using the Devise::Test::ControllerHelpers module to inject the request.env['warden'] object for you. Here is my controller: class ApplicationController < ActionController::Base protect_from_forgery with: :exception private # Overwriting the sign_out redirect path method def after_sign_out_path_for(resource_or_scope) build_path end end Here rea my two partial views: <!-- views/devise/menu/_login_items.html.erb --> <% if user_signed_in? %> <li> <%= link_to('Logout', destroy_user_session_path, :method => :delete) %> </li> <% else %> <li> <%= link_to('Login', new_user_session_path) %> </li> <% end %> and <!-- views/devise/menu/_registration_items.html.erb --> <% if user_signed_in? %> <li> <%= link_to('Edit registration', edit_user_registration_path) %> </li> <% else %> <li> <%= link_to('Register', new_user_registration_path) %> </li> <% end %> After debugging, I figured out that the problem is coming from this line in my "show" controller: template = HomeController.render('layouts/_template') Thanks for your help. A: Based on this SO answer you need to include the Devise::Test::ControllerHelpers module in your controller specs. Add the following to your rails_helper: RSpec.configure do |config| config.include Devise::Test::ControllerHelpers, type: :controller end A: Add config.include Devise::Test::ControllerHelpers, type: :controller in your rails_helper.rb file. A: It can be happening when you try to get Devise current_user in some part of code being managed by action cable. like a background job to render comment or something else. you can resolve it by using something like following in your controller, since you cant access warden at a model or job level(according to my limited knowledge): (I call a job right after creation of my comment in CommentsController create action, which calls a private method to render a comment partial containing edit and delete button, for which current_user was required) def create @product = Product.find(comment_params[:product_id]) @comment = @product.comments.build(comment_params) @comment.save! gon.comment_id = @comment.id gon.comment_user_id = @comment.user_id ActionCable.server.broadcast "chat", comment: render_comment render :create, layout: false end def render_comment CommentsController.renderer.instance_variable_set(:@env, {"HTTP_HOST"=>"localhost:3000", "HTTPS"=>"off", "REQUEST_METHOD"=>"GET", "SCRIPT_NAME"=>"", "warden" => warden}) CommentsController.render( partial: 'comments/comment_detail', locals: { product: @product, comment: @comment } ) end this will help you resolve warden issue, if you have used devise's current_user in that partial, it will give you the commentor user (as it should since that user initiated the rendering of partial). Now to solve this, if you have a front end framework you might need to fetch the current user from cookies in order to restrict some actions like edit/delete. but if you are working in pure rails the solution I came across is that you have to make a hidden field in the dom having current users id, and you will fetch that id for comparison in a script. you might need to access rails variables in javascript, for that you can use GON gem. I know this answer might contain much more than asked but I've searched alot and no where I found a satisfactory solution to this problem, feel free to discuss.
{ "pile_set_name": "StackExchange" }
Q: PHP/mySQL - Select WHERE multiple values in an associative array $skuArray = array(00240=>123,00241=>456); $getSkus = mysql_query("SELECT sku FROM data WHERE sku IN($skuArray)"); My above code doesn't work, how can I make it SELECT all sku's FROM data WHERE sku = any of the key names in $skuArray? (00240 and 00241 in this case) Hope this makes sense, Thank You. A: Try this: <?php $skuArray = array('00240'=>123, '00241'=>456); $inSkus = array(); foreach (array_keys($skuArray) as $key) { $inSkus[] = '"' . $key . '"'; } $sql = 'SELECT sku FROM data WHERE sku IN (' . implode(', ', $inSkus) . ')'; echo $sql; You need to have the keys as strings and you then need to wrap them in parentheses for the SQL query.
{ "pile_set_name": "StackExchange" }
Q: How to escape Chinese Unicode characters in URL? I have Chinese users of my PHP web application who enter products into our system. The information the’re entering is for example a product title and price. We would like to use the product title to generate a nice URL slug for those product. Seems like we cannot just use Chinese as HREF attributes. Does anyone know how we handle a title like “婴儿服饰” so that we can generate a clean url like http://www.site.com/婴儿服饰 ? Everything works fine for “normal” languages, but high UTF‐8 languages give us problems. Also, when generating the clean URL, we want to keep SEO in mind, but I have no experience with Chinese in that matter. A: This code, which uses the CPAN module, URI::Escape: #!/usr/bin/env perl use v5.10; use utf8; use URI::Escape qw(uri_escape_utf8); my $url = "http://www.site.com/"; my $path = "婴儿服饰"; say $url, uri_escape_utf8($path); when run, prints: http://www.site.com/%E5%A9%B4%E5%84%BF%E6%9C%8D%E9%A5%B0 Is that what you're looking for? BTW, those four characters are: CJK UNIFIED IDEOGRAPH-5A74 CJK UNIFIED IDEOGRAPH-513F CJK UNIFIED IDEOGRAPH-670D CJK UNIFIED IDEOGRAPH-9970 Which, according to the Unicode::Unihan database, seems to be yīng ér fú shì, or perhaps just ying er fú shi per Lingua::ZH::Romanize::Pinyin. And maybe even jing¹ jan⁴ fuk⁶ sik¹ or jing˥ jan˨˩ fuk˨ sik˥, using the Cantonese version from Unicode::Unihan. A: If your string is already UTF-8, just use rawurlencode to encode the string properly: $path = '婴儿服饰'; $url = 'http://example.com/'.rawurlencode($path); UTF-8 is the preferred character encoding for non-ASCII characters (although only ASCII characters are allowed in URIs which is why you need to use the percent-encoding). The result is the same as in tchrist’s example: http://example.com/%E5%A9%B4%E5%84%BF%E6%9C%8D%E9%A5%B0
{ "pile_set_name": "StackExchange" }
Q: How to create two LinearLayout with equal width programmatically? I'm trying to create two LinearLayout with equal width programmatically: mGroupLayout.setOrientation(HORIZONTAL); mGroupLayout.setWeightSum(2f); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT ); params.weight = 1.0f; leftLayout = new LinearLayout(getContext()); leftLayout.setOrientation(VERTICAL); leftLayout.setLayoutParams(params); mGroupLayout.addView( leftLayout, params ); rightLayout = new LinearLayout(getContext()); rightLayout.setOrientation(VERTICAL); rightLayout.setLayoutParams(params); mGroupLayout.addView( rightLayout, params ); But all my linear layouts isn't visible (they has 0 width). How i can do that? A: LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.MATCH_PARENT,1 ); FirstLinearLayout.setLayoutParams(params ); SecondLinearLayout.setLayoutParams(params ); 1 is the Weight of each layout.
{ "pile_set_name": "StackExchange" }
Q: Post a image on facebook using Javascript api error 324 requires upload file FB.login(function(response) { if (response.authResponse) { FB.api('/me/photos', 'post', { url:'http://test.xyzfoodservices.com/wp-content/plugins/facebook_login/single.jpg' }, function(response) { if (!response || response.error) { console.log(response.error); console.log(response); } else { alert('Success: Content Published on Facebook Wall'); } }); FB.api('/me/picture?type=normal', function(response) { var str="<figure class='tint'> <img id='img' src='"+response.data.url+"'/></figure>"; document.getElementById("popUpDiv").innerHTML+=str; }); } else { console.log('User cancelled login or did not fully authorize.'); } },{scope: 'email,user_photos,user_videos'}); I had Successfully got access from Facebook .But While I try to post a image on User wall facebook javascript 324 requires upload file. I had test many codes and solutions But nothings helps me up. So Please Answer some Different solutions because i already tried solutions which provided on stack OverFlow. Thanks in Advance. A: FB.api( "/me/photos", "POST", { "url": "{image-url}" }, function (response) { if (response && !response.error) { /* handle the result */ } } );
{ "pile_set_name": "StackExchange" }
Q: Make a struts action do nothing Is there a way to make a struts action do nothing? I don't want to do anything after my action is performed. Every single action in the project I inherited (794 of them) are redirectAction. But I don't want to redirect. I just want to stay on the same page. What can I do to just stay on the same page? I want like <result name="success" type="doNothing"></result> Is there something I can do to get this behavior? Or even fake it? A: Return ActionSupport.NONE. What's the usecase? What would an action do that wouldn't return anything?
{ "pile_set_name": "StackExchange" }
Q: Objective-C: Help needed to understand why two methods react differently when accessing a UIView in two different ways I feel bad asking three questions in the space of two days but I am stuck and searching the forum I couldn't find the answer so I hope someone can help me - all part of the fun of learning I suppose! In my program I have three views which go in the order GridScreen -> GameScreen -> CorrectScreen. On the CorrectScreen I have a button which goes back to the GridScreen. On the GridScreen I have a bunch of buttons which a user can press to go to the GameScreen. When the user answers the question correctly he is taken from the GameScreen to the CorrectScreen for acknowledgement and then back to the GridScreen. In a previous question I asked how to track the button that was pressed on the GridScreen so that when I go back to it from the CorrectScreen I can replace the icon with a tick. That was solved earlier but by doing so I've created another problem. In the CorrectScreen, when the user presses the button to go back the following two functions are called: [self.gridScreen updateUserIcon:buttonThatWasPressed]; [self.gridScreen updatePoints:accumulatedpoints]; where updateUserIcon is: -(void)updateUserIcon:(UIButton *)button { UIButton *buttonPressed = button; self.button1 = buttonPressed; [self.button1 setImage:[UIImage imageNamed:@"tick.png"] forState:UIControlStateNormal]; } and updatePoints is: -(void)updatePoints:(int)points { self.currentPoints.text = [[NSString alloc]initWithFormat:@"Current points: %d", points]; } where button1 is a UIButton and currentPoints is a UILabel. Now, when I go back to the GridScreen using the following code after calling the two functions the tick appears on the button I want, but the label does not update correctly: FIRST CASE: [[[self presentingViewController]presentingViewController] dismissModalViewControllerAnimated:YES]; whereas if I use this next way, the tick does not appear at all, but the label updates perfectly: SECOND CASE: GridScreen *screen = [[GridScreen alloc] initWithNibName:nil bundle:nil]; screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentModalViewController:screen animated:YES]; (I normally load views using the second case). In the first case, even if I did the following code: -(void)updatePoints:(int)points { self.currentPoints.text = @"A"; NSLog(@"Current Points %@", self.currentPoints.text); } My NSLog returns Current Points (null). The solution is something to do with my first method of going back to the GridScreen I don't actually load the view again but in the second method I do - but I cannot understand what I need to do to get both the score updating correctly and the tick. If anyone can help I would love to know - I am fairly new to programming with Objective-C so if any of this is 'bad code' I am happy to be told what is wrong so going ahead I don't make similar mistakes. Thanks again to you all, this site is fantastic for helping out and in advance I appreciate the advice. Andy. A: OK, silly question, but why aren't you just using Notifications to message the screens? It's the easiest and safest approach. In the GridScreen add this notification: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toggleLabel:) name:@"CorrectAnswerNotification" object:nil]; before pushing the new screen. Now in the CorrectScreen, fire that notification before poping the view: [[NSNotificationCenter defaultCenter] postNotificationName:@"CorrectAnswerNotification" object:self userInfo:nil]; Pass any information you want in the userInfo dictionary (this can be a dictionary so you can pass along any information's you need) And in the GridScreen manage everything in the toggleLabel method: -(void)toggleLabel:(NSNotification *)notification { //read the documentation dictionary NSDictionary *infoDictionary = [notification userInfo]; //remove the notification first [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CorrectAnswerNotification" object:nil]; //now change the buttons... [self updateUserIcon:buttonThatWasPressed]; [self updatePoints:accumulatedpoints]; } Because I was asked about the Notification Center, here are some details straight from Apple Documentation: An NSNotificationCenter object (or simply, notification center) provides a mechanism for broadcasting information within a program. An NSNotificationCenter object is essentially a notification dispatch table. Objects register with a notification center to receive notifications (NSNotification objects) using the addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: methods. Each invocation of this method specifies a set of notifications. Therefore, objects may register as observers of different notification sets by calling these methods several times. When an object (known as the notification sender) posts a notification, it sends an NSNotification object to the notification center. The notification center then notifies any observers for which the notification meets the criteria specified on registration by sending them the specified notification message, passing the notification as the sole argument. A notification center maintains a notification dispatch table which specifies a notification set for a particular observer. A notification set is a subset of the notifications posted to the notification center. Each table entry contains three items: Notification observer: Required. The object to be notified when qualifying notifications are posted to the notification center. Notification name: Optional. Specifying a name reduces the set of notifications the entry specifies to those that have this name. Notification sender: Optional. Specifying a sender reduces the set of notifications the entry specifies to those sent by this object.
{ "pile_set_name": "StackExchange" }
Q: Executing scripts with Powershell via C# I need to execute the following script: Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize I tried a few solutions with Powershell and Command classes, but they doesn't work. Error that I received: Value parameters cannot be null. A: I think this will do what you're looking for: private string RunLocalExchangePowerShell(string script) { // create the runspace and load the snapin RunspaceConfiguration rsConfig = RunspaceConfiguration.Create(); PSSnapInException snapInException = null; Runspace runSpace = RunspaceFactory.CreateRunspace(rsConfig); runSpace.Open(); rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException); Pipeline pipeLine = runSpace.CreatePipeline(); // load the script and convert the output to a string pipeLine.Commands.AddScript(script); pipeLine.Commands.Add("out-string"); // get the results Collection<PSObject> results; results = pipeLine.Invoke(); // loop through the results and build the output StringBuilder sb = new StringBuilder(); foreach (PSObject obj in results) { sb.AppendLine(obj.ToString()); } // close the pipeline and runspace pipeLine.Dispose(); runSpace.Close(); return sb.ToString(); } Example usage: Console.WriteLine(prog.RunLocalExchangePowerShell("Get-MailboxDatabase -Status | select ServerName,Name,DatabaseSize"));
{ "pile_set_name": "StackExchange" }
Q: Nginx Conditional Dynamic Proxy I have a game running on my server. When a user requests it, a new process on my server is started and starts to listen for a websocket connection on a random port in the range 8001-8100. On the client i want to connect to the game. var port = 8044; // <- Client is given this number when creating a new game connection = new WebSocket("wss://XXX/websocket?port=" + port); My server is a nginx reverse proxy. I want to do something like this: (I need a working replacement for it, the below should illustrate the point.) server { ... location /websocket/ { if(isNumber($port) && $port <= 8100 && $port >= 8001 { proxy_pass http://localhost:$port; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } } } Reason for those reverse proxy shenanigans is to be able to use the default 443 port, meaning clients won't have firewall problems. Othwerwise I would just directly connect to the correct port from the client. Any ideas? A: The port argument is available as $arg_port. It can be checked using a regular expression. For example: location /websocket/ { if ($arg_port !~ "^80[0-9]{2}$") { return 403; } proxy_pass http://localhost:$arg_port; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } A little poetic licence with the port range, but a more complex expression can achieve your precise requirements. I avoid putting anything too complex inside an if block for these reasons. See this document for more.
{ "pile_set_name": "StackExchange" }
Q: Difference between -XX:+UseParallelGC and -XX:+UseParNewGC They are algorithms for the young generation garbage collection. The second one (UseParNewGC) gets activated automatically with the concurrent tenured generation garbage collection (see Java Concurrent and Parallel GC) but, is there a difference between the two parallel algorithms? A: After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003 Young generation garbage collection algorithms The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed. The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector. The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector). From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't. A: Parallel GC XX:+UseParallelGC Use parallel garbage collection for scavenges. (Introduced in 1.4.1) XX:+UseParallelOldGC Use parallel garbage collection for the full collections. Enabling this option automatically sets -XX:+UseParallelGC. (Introduced in 5.0 update 6.) UseParNewGC UseParNewGC A parallel version of the young generation copying collector is used with the concurrent collector (i.e. if -XX:+ UseConcMarkSweepGC is used on the command line then the flag UseParNewGC is also set to true if it is not otherwise explicitly set on the command line). Perhaps the easiest way to understand was combinations of garbage collection algorithms made by Alexey Ragozin <table border="1" style="width:100%"> <tr> <td align="center">Young collector</td> <td align="center">Old collector</td> <td align="center">JVM option</td> </tr> <tr> <td>Serial (DefNew)</td> <td>Serial Mark-Sweep-Compact</td> <td>-XX:+UseSerialGC</td> </tr> <tr> <td>Parallel scavenge (PSYoungGen)</td> <td>Serial Mark-Sweep-Compact (PSOldGen)</td> <td>-XX:+UseParallelGC</td> </tr> <tr> <td>Parallel scavenge (PSYoungGen)</td> <td>Parallel Mark-Sweep-Compact (ParOldGen)</td> <td>-XX:+UseParallelOldGC</td> </tr> <tr> <td>Serial (DefNew)</td> <td>Concurrent Mark Sweep</td> <td> <p>-XX:+UseConcMarkSweepGC</p> <p>-XX:-UseParNewGC</p> </td> </tr> <tr> <td>Parallel (ParNew)</td> <td>Concurrent Mark Sweep</td> <td> <p>-XX:+UseConcMarkSweepGC</p> <p>-XX:+UseParNewGC</p> </td> </tr> <tr> <td colspan="2">G1</td> <td>-XX:+UseG1GC</td> </tr> </table> Conclusion: Apply -XX:+UseParallelGC when you require parallel collection method over YOUNG generation ONLY, (but still) use serial-mark-sweep method as OLD generation collection Apply -XX:+UseParallelOldGC when you require parallel collection method over YOUNG generation (automatically sets -XX:+UseParallelGC) AND OLD generation collection Apply -XX:+UseParNewGC & -XX:+UseConcMarkSweepGC when you require parallel collection method over YOUNG generation AND require CMS method as your collection over OLD generation memory You can't apply -XX:+UseParallelGC or -XX:+UseParallelOldGC with -XX:+UseConcMarkSweepGC simultaneously, that's why your require -XX:+UseParNewGC to be paired with CMS otherwise use -XX:+UseSerialGC explicitly OR -XX:-UseParNewGC if you wish to use serial method against young generation A: UseParNewGC usually knowns as "parallel young generation collector" is same in all ways as the parallel garbage collector (-XX:+UseParallelGC), except that its more sophiscated and effiecient. Also it can be used with a "concurrent low pause collector". See Java GC FAQ, question 22 for more information. Note that there are some known bugs with UseParNewGC
{ "pile_set_name": "StackExchange" }
Q: Multiple optional checks with Where query (to specify file search options) I created checkboxes, where a user can set this for file searching: exclude system files: on/off exclude hidden files: on/off exclude read_only files: on/off now I don't know, how I can use this three different boolean statements with this code line: DirectoryInfo DirInfo = new DirectoryInfo(sCopyFilesFromFilePath); GetDirsToCopy = DirInfo.EnumerateDirectories(".", SearchOption.AllDirectories).Where( ? ); A: You can use an implication. In logic a -> b is translated as !a || b, thus: DirInfo.EnumerateDirectories(".", SearchOption.AllDirectories) .Where(x => !excludeSystem || (x.Attributes&FileAttributes.System) == 0); .Where(x => !excludeHidden || (x.Attributes&FileAttributes.Hidden) == 0); .Where(x => !excludeReadOnly || (x.Attributes&FileAttributes.ReadOnly) == 0); Here we assume excludeSystem, excludeHidden and excludeReadOnly are bools that you first fetched from the checkboxes. You can of course write it in one Where as well. Explanation (one .Where): Given the following expression x => !excludeSystem || (x.Attributes&FileAttributes.System) == 0 You can read this as a predicate. Say excludeSystem is false, then !excludeSystem is true, thus all directories will succeed. If not, the the second operand (x.Attributes&FileAttributes.System) == 0 is executed. The second operand first does and bitwise & on the Attributes of x and the constant FileAttributes.System. If the Attributes thus contain FileAttributes.System, the result will be something different than zero. In that case the second test fails. In other words, you return false if the files are excluded and the file is a system-file. Optimize In case you think you will iterate over thousands of directories, you can make the code a bit more efficient, by making the tests faster: IEnumerable<DirectoryInfo> temp = DirInfo.EnumerateDirectories(".", SearchOption.AllDirectories); if(excludeSystem) { temp = temp.Where((x.Attributes&FileAttributes.System) == 0); } if(excludeHidden) { temp = temp.Where((x.Attributes&FileAttributes.Hidden) == 0); } if(excludeReadOnly) { temp = temp.Where((x.Attributes&FileAttributes.ReadOnly) == 0); } GetDirsToCopy = temp; This will (almost) always be efficient, but it makes the code a bit less beautiful.
{ "pile_set_name": "StackExchange" }
Q: Why does the entity framework need an ICollection for lazy loading? I want to write a rich domain class such as public class Product { public IEnumerable<Photo> Photos {get; private set;} public void AddPhoto(){...} public void RemovePhoto(){...} } But the entity framework (V4 code first approach) requires an ICollection type for lazy loading! The above code no longer works as designed since clients can bypass the AddPhoto / RemovePhoto method and directly call the add method on ICollection. This is not good. public class Product { public ICollection<Photo> Photos {get; private set;} //Bad public void AddPhoto(){...} public void RemovePhoto(){...} } It's getting really frustrating trying to implement DDD with the EF4. Why did they choose the ICollection for lazy loading? How can i overcome this? Does NHibernate offer me a better DDD experience? A: I think i found the solution...See here for more details: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/47296641-0426-49c2-b048-bf890c6d6af2/ Essentially you want to make the ICollection type protected and use this as the backing collection for the public IEnumerable public class Product { // This is a mapped property protected virtual ICollection<Photo> _photos { get; set; } // This is an un-mapped property that just wraps _photos public IEnumerable<Photo> Photos { get { return _photos; } } public void AddPhoto(){...} public void RemovePhoto(){...} } For lazy loading to work the type must implement ICollection and the access must be public or protected. A: You can't insert into an IEnumerable. This applies to the EF just as much as it does to your clients. You don't have to use ICollection, though; you can use IList or other writeable types. My advice to get the best of both worlds is to expose DTOs rather than entities to your clients.
{ "pile_set_name": "StackExchange" }
Q: num_rows() always returns 0 when using prepared statements I've tried looking at every one else's stack overflow with exact error in title, but I still can't figure this out. I'm using http://andrew-greig.net/portfolio/better_mysqli.htm for mysqli extend because it does make binding items as arrays much easier. I been trying to move over from native mysql to mysqli and I've always had this same issue with tring to find out if there is a result or not. Here is my current code $searchSQL = $mysqli->select("SELECT * FROM coreUsers WHERE Username = ? AND Password = ?", $row, array($username, $password)); var_dump($searchSQL); while($searchSQL->fetch()) { echo "<br/>---FOUND Valid LOGIN!!</br>"; exit; } The output I get is.. object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(2) ["field_count"]=> int(19) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) } ---FOUND Valid LOGIN!! so it found the record, if I output the record information it does echo out Username and Password just fine from the row response, but num_rows is always 0. For this I can never get $rowCount = $searchSQL->num_rows(); to work when trying to see if there are actual results before doing the while loop. ----EDIT---- I have no idea why this is marked as a duplicate. The post added refers to "boolean" and that isn't my error. Mine is object given. if ($searchSQL === false) { echo "invalid"; } else { echo "valid"; } this code doesn't work (from the post you marked as duplicate) because my response always will return true if you actually would look at the code I'm using from the extend. A: As mentioned by @Ghost below the issue I was missing was 1 line of code. $stmt->store_result(); $rowCount = $stmt->num_rows; This has to be called BEFORE I can access num_rows() on a prepared statement.
{ "pile_set_name": "StackExchange" }
Q: An intuitive proof for one of the fundamental property of a parallelogram "The sum of the squares of the diagonals is equal to the sum of the squares of the four sides of a parallelogram." I find this property very useful while solving different problems on Quadrilaterals & Polygon,so I am very inquisitive about a intuitive proof of this property. A: Let two sides of the parallelogram correspond to the vectors $\vec a$ and $\vec b$. Then the diagonals correspond to the vectors $\vec a+\vec b$ and $\vec a-\vec b$, and $$(\vec a+\vec b)^2+(\vec a-\vec b)^2=2\vec a^2+2\vec b^2\;,$$ which is the desired identity between the sums of the squares of the diagonals and the sides.
{ "pile_set_name": "StackExchange" }
Q: Problems with su: Authentication Failure I am currently using Ubuntu and am 100% new to Unix. I have installed Ubuntu to program in C and will be using the "Learn C the Hard Way" online textbook (http://c.learncodethehardway.org/book/ex0.html). I attempted the section in the textbook meant for setting up your computer and the second command is causing me some problems. The first command in the link above executes without issue but when I try and run the second command: $ su -c yum groupinstall development-tools it prompts me for my password and when I enter it, it says su: Authentication Failure How do I fix this? A: Look again at the web page. You are trying, wrongly, to run a command for an RPM based Linux like Fedora. Instead, run the command that says: For Debian based systems, like Ubuntu you should just have to install a few things using these commands: $ sudo apt-get install build-essential
{ "pile_set_name": "StackExchange" }
Q: What is the default scope of worksheets and cells and range? When you just type worksheets() what is the default scope ActiveWorkbook or ThisWorkbook? For those who do not know these distinctions they are extremely important especially in Excel 2013 when you want macros to run when you switch to different workbooks. A: In a standard module an unqualified Worksheets() will always reference the ActiveWorkbook. In the ThisWorkbook module, the implicit qualifier is Me and that will reference the containing workbook. Likewise, an unqualified Range() or Cells() (or Rows()/Columns()) in a standard module will reference the ActiveSheet, but in a sheet code module the implicit qualifier is Me, and will reference the corresponding worksheet. Unqualified... Where Implicit Qualifier -------------- -------------- ------------------- Worksheets(), ThisWorkbook Containing workbook (Me) Sheets() Any other module Active workbook (via [_Global]) Range(), Cells(), Sheet module Containing sheet (Me) Rows(), Columns(), Any other module Active sheet (via [_Global]) Names() The easy way to avoid having to remember any of this is to always fully qualify any Worksheets, Sheets, Range, Cells, or Names reference. Qualify the member call with Me when referring to ThisWorkbook in that module's code-behind, or when referring to Sheet1 in that module's code-behind.
{ "pile_set_name": "StackExchange" }
Q: Calculating sum of two columns with individual rows and result store in another column USing ruby on rails I am new to Ruby on rails platform, I have a question i.e., In my module i have table called Asset_classification in which name, type, availability, integerity, level are the fields. i want to calculate(sum) integrity & level fields for each row and finally result should be store in another column.... Any help is appreciate Ruby 1.9.3 Rails 3.2.* A: Add new column sum in database and do this in AssetClassification model before_save :calculate_sum def calculate_sum self.sum = self.integrity + self.level end
{ "pile_set_name": "StackExchange" }
Q: Efficiently average the second column by intervals defined by the first column There are two numeric columns in a data file. I need to calculate the average of the second column by intervals (such as 100) of the first column. I can program this task in R, but my R code is really slow for a relatively large data file (millions of rows, with the value of first column changing between 1 to 33132539). Here I show my R code. How could I tune it to be faster? Other solutions that are perl, python, awk or shell based are appreciated. Thanks in advance. (1) my data file (tab-delimited, millions of rows) 5380 30.07383\n 5390 30.87\n 5393 0.07383\n 5404 6\n 5428 30.07383\n 5437 1\n 5440 9\n 5443 30.07383\n 5459 6\n 5463 30.07383\n 5480 7\n 5521 30.07383\n 5538 0\n 5584 20\n 5673 30.07383\n 5720 30.07383\n 5841 3\n 5880 30.07383\n 5913 4\n 5958 30.07383\n (2) what I want to get, here interval = 100 intervals_of_first_columns, average_of_2nd column_by_the_interval 100, 0\n 200, 0\n 300, 20.34074\n 400, 14.90325\n ..... (3) R code chr1 <- 33132539 # set the limit for the interval window <- 100 # set the size of interval spe <- read.table("my_data_file", header=F) # read my data in names(spe) <- c("pos", "rho") # name my data interval.chr1 <- data.frame(pos=seq(0, chr1, window)) # setup intervals meanrho.chr1 <- NULL # object for the mean I want to get # real calculation, really slow on my own data. for(i in 1:nrow(interval.chr1)){ count.sub<-subset(spe, chrom==1 & pos>=interval.chr1$pos[i] & pos<=interval.chr1$pos[i+1]) meanrho.chr1[i]<-mean(count.sub$rho) } A: You don't really need to set up an output data.frame but you can if you want. Here is how I would have coded it, and I guarantee it will be fast. > dat$incrmt <- dat$V1 %/% 100 > dat V1 V2 incrmt 1 5380 30.07383 53 2 5390 30.87000 53 3 5393 0.07383 53 4 5404 6.00000 54 5 5428 30.07383 54 6 5437 1.00000 54 7 5440 9.00000 54 8 5443 30.07383 54 9 5459 6.00000 54 10 5463 30.07383 54 11 5480 7.00000 54 12 5521 30.07383 55 13 5538 0.00000 55 14 5584 20.00000 55 15 5673 30.07383 56 16 5720 30.07383 57 17 5841 3.00000 58 18 5880 30.07383 58 19 5913 4.00000 59 20 5958 30.07383 59 > with(dat, tapply(V2, incrmt, mean, na.rm=TRUE)) 53 54 55 56 57 58 59 20.33922 14.90269 16.69128 30.07383 30.07383 16.53692 17.03692 You could have done even less setup (skip the incrmt variable with this code: > with(dat, tapply(V2, V1 %/% 100, mean, na.rm=TRUE)) 53 54 55 56 57 58 59 20.33922 14.90269 16.69128 30.07383 30.07383 16.53692 17.03692 And if you want the result to be available for something: by100MeanV2 <- with(dat, tapply(V2, V1 %/% 100, mean, na.rm=TRUE)) A: use strict; use warnings; my $BIN_SIZE = 100; my %freq; while (<>){ my ($k, $v) = split; my $bin = $BIN_SIZE * int($k / $BIN_SIZE); $freq{$bin}{n} ++; $freq{$bin}{sum} += $v; } for my $bin (sort { $a <=> $b } keys %freq){ my ($n, $sum) = map $freq{$bin}{$_}, qw(n sum); print join("\t", $bin, $n, $sum, $sum / $n), "\n"; } A: Given the size of your problem, you need to use data.table which is lightening fast. require(data.table) N = 10^6; M = 33132539 mydt = data.table(V1 = runif(N, 1, M), V2 = rpois(N, lambda = 10)) ans = mydt[,list(avg_V2 = mean(V2)),'V1 %/% 100'] This took 20 seconds on my Macbook Pro with specs 2.53Ghz 4GB RAM. If you don't have any NA in your second column, you can obtain a 10x speedup by replacing mean with .Internal(mean). Here is the speed comparison using rbenchmark and 5 replications. Note that data.table with .Internal(mean) is 10x faster. test replications elapsed relative f_dt() 5 113.752 10.30736 f_tapply() 5 147.664 13.38021 f_dt_internal() 5 11.036 1.00000 Update from Matthew : New in v1.8.2, this optimization (replacing mean with .Internal(mean)) is now automatically made; i.e., regular DT[,mean(somecol),by=] now runs at the 10x faster speed. We'll try and make more convenience changes like this in future, so that users don't need to know as many tricks in order to get the best from data.table.
{ "pile_set_name": "StackExchange" }
Q: difference of property in interface and class interface IVehicle { int Id { get; set; } string Name { get; set; } void Print(); } class Car : IVehicle { public int Id { get; set; } public string Name { get; set; } public void Print() { Console.WriteLine($"Id {Id} Name {Name}"); } } As we all know interface can only declare the members and we implement those members in classes which inherit from that interface. So what is the difference then? Why do I have to re-declare the properties in the class? Can't it use the declarations from the interface? A: An interface defines a contract that classes implementing it must adhere to in order to compile. An interface does not say how the implementation must be done, only that it satisfies the interface. For example, you've created a string property for Name that must expose a getter and setter. Your Car implementation uses autoproperties to satisfy the interface. However, you could have written your car like this: class Car : IVehicle { public int Id { get; set; } private string _name; public string Name { get { return _name; } set { _name = value; } } public void Print() { Console.WriteLine($"Id {Id} Name {Name}"); } } and that would be perfectly valid since it still publicly exposes a string property Name with getters and setters. When you first a create a car (Car myCar = new Car();, it will have default values for its properties. But you can modify those values: IVehicle myCar = new Car(); myCar.Name = "The General"; //alternate syntax using object initializer IVehicle schoolBus = new Car { Name = "Magic School Bus" };
{ "pile_set_name": "StackExchange" }
Q: Iterate from "0" to "ZZZZZ" I was given an assignment, it was as follows: Give a JS code snippet which writes to the console from: "0" to "ZZZZZ" all the combination of the characters of a-z, 0-9 and A-Z. Is my solution correct? I am sure there are better ways to achieve the same, can anybody show some? My code is: function createCharSet(){ var charset = "", c; for(c=48;c<58;c++){ charset += String.fromCharCode(c); } for(c=97;c<123;c++){ charset += String.fromCharCode(c); } for(c=65;c<91;c++){ charset += String.fromCharCode(c); } return charset; } function getNext(curr, charSet){ var length = curr.length, arr = curr.split(""), radix = charSet.length, i, c; for(i=length-1;i>-1;i--){ c = charSet.indexOf(arr[i])+1; if(c==radix){ arr[i]=charSet[0]; if(i==0) return; }else{ arr[i]=charSet[c]; break; } } return arr.join(""); } function iterate() { var charSet = createCharSet(), maxLen = 4, len, i, arr, curr; for(len = 1;len<maxLen+1;len++){ arr = []; for(i=0;i<len;i++){ arr.push(charSet[0]); } curr = arr.join(""); while(curr) { console.log(curr); curr = getNext(curr, charSet); }; } } iterate(); A: Minor observations: I'd just hardcode the charset in this case. Doing so is faster to write (and a lot more explicit) than building it with a bunch of loops. The modulo operator % is a good friend to have for this, as it'll let you "wrap around" array indices. Overall, there's too much code here, I think. This is just counting in base 62. It'd be awesome if Number.prototype.toString() accepted 62 as an argument, but, unfortunately, it only seems to accept bases 2-36. Similarly, it'd be great if we could somehow use the built-in base64 encoding function (btoa), but it's, well, base 64 (and it's got other issues). So we do have to roll our own. Now, if this was base 10, we could obviously just do var limit = Math.pow(10, 5); // i.e. 100000 for(var i = 0 ; i < limit ; i++) { console.log(i); } which will print 0-99999. Using this same basic setup, we can print our base62 values. Our limit will be \$base^{numberOfDigits}\$ just like \$10^5\$ will end up printing five 9s. So for 0-ZZZZZ we'll need to loop from zero to Math.pow(62, 5). And of course, we'll have to do the actual base62 conversion. The basic algorithm is: Get the char corresponding to \$value\bmod base\$ (e.g. charset[538 % 62] => charset[42]) and add it to the output string. Set \$value\$ to the quotient of \$\frac{value}{base}\$ (e.g. Math.floor(538 / 62) => 8). If value is bigger than zero, go to step 1. Otherwise, return the output. In code: var output = ""; do { output = charset[value % base] + output; value = (value / base) | 0; // bitwise floor trick } while(value > 0); return output; Putting it all together, I get this: // define our base62 function (using an IIFE) var toBase62 = (function () { var charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", base = charset.length; // 62, natch return function (value) { // TODO: It'd be nice to guard against negative values here (see comments) var string = ""; do { string = charset[value % base] + string; value = (value / base) | 0; } while(value > 0); return string; } }()); // loop for a long, long time for(var i = 0, l = Math.pow(62, 5) ; i < l ; i++) { console.log( toBase62(i) ); } Note that it takes forever to print all the 916,132,832 values from 0 up to \$62^5\$. JS ain't that fast. I haven't explored optimization, so for testing, I'd advice using (much) fewer iterations.
{ "pile_set_name": "StackExchange" }
Q: logback error while server startup The following is my logback file <?xml version="1.0" encoding="UTF-8"?> <!-- For assistance related to logback-translator or configuration --> <!-- files in general, please contact the logback user mailing list --> <!-- at http://www.qos.ch/mailman/listinfo/logback-user --> <!-- --> <!-- For professional support please see --> <!-- http://www.qos.ch/shop/products/professionalSupport --> <!-- --> <configuration> <appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"> <!-- in the absence of the class attribute, it is assumed that the desired discriminator type is ch.qos.logback.classic.sift.MDCBasedDiscriminator --> <discriminator> <key>type</key> <defaultValue>normal</defaultValue> </discriminator> <sift> <appender name="STDOUT-${type}" class="ch.qos.logback.core.ConsoleAppender"> <file>${catalina.base}/logs/${type}.log</file> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} %-5level %logger{36} - %msg%n </Pattern> </layout> </appender> <appender name="FILE-${type}" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${catalina.base}/logs/${type}.log</file> <Encoding>UTF-8</Encoding> <!-- Current assumption: If we don't provide log file name then default will be used i.e. catalina.out --> <!-- <file>${catalina.base}/logs/ee.log</file> --> <Append>true</Append> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <FileNamePattern>${catalina.base}/logs/${type}/ee.%i.log.zip </FileNamePattern> <MinIndex>1</MinIndex> <MaxIndex>10</MaxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>200MB</MaxFileSize> </triggeringPolicy> </appender> </sift> </appender> <appender name="FILE-HIBERNATE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${catalina.base}/logs/hibernate.log</file> <Encoding>UTF-8</Encoding> <!-- Current assumption: If we don't provide log file name then default will be used i.e. catalina.out --> <!-- <file>${catalina.base}/logs/ee.log</file> --> <Append>true</Append> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <FileNamePattern>${catalina.base}/logs/hibernate/ee.%i.log.zip </FileNamePattern> <MinIndex>1</MinIndex> <MaxIndex>10</MaxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>200MB</MaxFileSize> </triggeringPolicy> </appender> <appender name="FILE-EMAIL" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${catalina.base}/logs/email.log</file> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <Pattern> %d{yyyy-MM-dd HH:mm:ss} - %msg%n </Pattern> </encoder> <Append>true</Append> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${catalina.base}/logs/email/email_%d{yyyy-MM-dd}.zip </FileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>1KB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <filter class="com.expertly.common.logs.filters.EmailLogFilter"> <excludedExceptionClassName>org.springframework.security.access.AccessDeniedException</excludedExceptionClassName> <excludedExceptionClassName>com.expertexecution.ee.common.server.filters.RequestResponseLoggingFilter</excludedExceptionClassName> </filter> <smtpHost>localhost</smtpHost> <to>errors@expertly.com</to> <smtpPort>25</smtpPort> <STARTTLS>false</STARTTLS> <from>error-notifications@webintensive.expertexecution.com</from> <subject>Expertly: Error</subject> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%date %-5level %logger{35} -%n %message%n</pattern> </layout> </appender> <root level="ERROR"> <appender-ref ref="EMAIL" /> </root> <logger name="org.hibernate.type" level="INFO" additivity="false"> <appender-ref ref="FILE-HIBERNATE" /> </logger> <logger name="org.hibernate" level="INFO" additivity="false"> <appender-ref ref="FILE-HIBERNATE" /> </logger> <!-- <logger name="com.expertexecution.ee.common.server.email" level="DEBUG" additivity="false"> <appender-ref ref="FILE-EMAIL" /> </logger> --> <root level="DEBUG"> <appender-ref ref="SIFT" /> <!-- <appender-ref ref="FILE" /> --> <!-- <appender-ref ref="STDOUT" /> --> <!-- <appender-ref ref="EMAIL" /> --> </root> </configuration> I am getting following error while I start my server. It gives array index outof bound error. Not able to understand what is the issue. 15:36:55,735 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy] 15:36:55,735 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml] 15:36:55,735 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/home/anoop/EE%20Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/trunk/WEB-INF/classes/logback.xml] 15:36:55,796 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set 15:36:55,797 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.classic.sift.SiftingAppender] 15:36:55,800 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [SIFT] 15:36:55,821 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.sift.MDCBasedDiscriminator] for [discriminator] property 15:36:55,827 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender] 15:36:55,830 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-HIBERNATE] 15:36:55,841 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@59:13 - no applicable action for [Encoding], current pattern is [[configuration][appender][Encoding]] 15:36:55,876 |-WARN in ch.qos.logback.core.rolling.RollingFileAppender[FILE-HIBERNATE] - This appender no longer admits a layout as a sub-component, set an encoder instead. 15:36:55,876 |-WARN in ch.qos.logback.core.rolling.RollingFileAppender[FILE-HIBERNATE] - To ensure compatibility, wrapping your layout in LayoutWrappingEncoder. 15:36:55,876 |-WARN in ch.qos.logback.core.rolling.RollingFileAppender[FILE-HIBERNATE] - See also http://logback.qos.ch/codes.html#layoutInsteadOfEncoder for details 15:36:55,885 |-INFO in ch.qos.logback.core.rolling.FixedWindowRollingPolicy@74648f3f - Will use zip compression 15:36:55,893 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-HIBERNATE] - Active log file name: /home/anoop/EE Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/logs/hibernate.log 15:36:55,893 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[FILE-HIBERNATE] - File property is set to [/home/anoop/EE Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/logs/hibernate.log] 15:36:55,894 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.rolling.RollingFileAppender] 15:36:55,894 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-EMAIL] 15:36:55,916 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use zip compression 15:36:55,916 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern /home/anoop/EE Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/logs/email/email_%d{yyyy-MM-dd} for the active file 15:36:55,919 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@75f8accb - The date pattern is 'yyyy-MM-dd' from file name pattern '/home/anoop/EE Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/logs/email/email_%d{yyyy-MM-dd}.zip'. 15:36:55,919 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@75f8accb - Roll-over at midnight. 15:36:55,919 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@75f8accb - Setting initial period to Wed Jun 03 14:30:20 IST 2015 15:36:55,921 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@98:19 - RuntimeException in Action for tag [rollingPolicy] java.lang.IndexOutOfBoundsException: No group 1 at java.lang.IndexOutOfBoundsException: No group 1 at at java.util.regex.Matcher.group(Matcher.java:487) at at ch.qos.logback.core.rolling.helper.FileFilterUtil.extractCounter(FileFilterUtil.java:109) at at ch.qos.logback.core.rolling.helper.FileFilterUtil.findHighestCounter(FileFilterUtil.java:93) at at ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP.computeCurrentPeriodsHighestCounterValue(SizeAndTimeBasedFNATP.java:65) at at ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP.start(SizeAndTimeBasedFNATP.java:49) at at ch.qos.logback.core.rolling.TimeBasedRollingPolicy.start(TimeBasedRollingPolicy.java:87) at at ch.qos.logback.core.joran.action.NestedComplexPropertyIA.end(NestedComplexPropertyIA.java:167) at at ch.qos.logback.core.joran.spi.Interpreter.callEndAction(Interpreter.java:318) at at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:197) at at ch.qos.logback.core.joran.spi.Interpreter.endElement(Interpreter.java:183) at at ch.qos.logback.core.joran.spi.EventPlayer.play(EventPlayer.java:62) at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:147) at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:133) at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:96) at at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:55) at at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75) at at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:148) at at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84) at at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:54) at at org.slf4j.LoggerFactory.bind(LoggerFactory.java:128) at at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:108) at at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:279) at at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:252) at at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:156) at at org.apache.commons.logging.impl.SLF4JLogFactory.getInstance(SLF4JLogFactory.java:132) at at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:685) at at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:282) at at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992) at at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5490) at at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) at at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) at at java.util.concurrent.FutureTask.run(FutureTask.java:262) at at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at at java.lang.Thread.run(Thread.java:745) 15:36:55,921 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@99:56 - no applicable action for [layout], current pattern is [[configuration][appender][layout]] 15:36:55,921 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@100:13 - no applicable action for [Pattern], current pattern is [[configuration][appender][layout][Pattern]] 15:36:55,921 |-WARN in ch.qos.logback.core.rolling.RollingFileAppender[FILE-EMAIL] - No TriggeringPolicy was set for the RollingFileAppender named FILE-EMAIL 15:36:55,921 |-WARN in ch.qos.logback.core.rolling.RollingFileAppender[FILE-EMAIL] - For more information, please visit http://logback.qos.ch/codes.html#rfa_no_tp 15:36:55,921 |-WARN in ch.qos.logback.core.joran.action.AppenderAction - The object at the of the stack is not the appender named [FILE-EMAIL] pushed earlier. 15:36:55,921 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.classic.net.SMTPAppender] 15:36:55,934 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [EMAIL] 15:36:55,962 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to ERROR 15:36:55,962 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [EMAIL] to Logger[ROOT] 15:36:55,963 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.hibernate.type] to INFO 15:36:55,963 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting additivity of logger [org.hibernate.type] to false 15:36:55,963 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE-HIBERNATE] to Logger[org.hibernate.type] 15:36:55,963 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [org.hibernate] to INFO 15:36:55,963 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting additivity of logger [org.hibernate] to false 15:36:55,963 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [FILE-HIBERNATE] to Logger[org.hibernate] 15:36:55,963 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to DEBUG 15:36:55,963 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [SIFT] to Logger[ROOT] 15:36:55,963 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration. 15:36:55,964 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@52c481c5 - Registering current configuration as safe fallback point can anyone please help me fixing it? A: Just add a counter %i to the FileNamePattern whenever you use a MaxFileSize. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>${catalina.base}/logs/email/email_%d{yyyy-MM-dd}_%i.zip</FileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>1KB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> Checkout this post.
{ "pile_set_name": "StackExchange" }
Q: hybris - Product Update API I am trying to update Product information in hybris through REST Webservice API. http://localhost:9001/ws410/rest/catalogs/powertoolsProductCatalog/catalogversions/Online/products/2116275 I understand that we need to give the ProductDTO in the body of the PUT request. Please can someone help with an example? I am trying this in a REST Client and will be extending this in a .net environment. Regards Hari A: I have to give the PRODUCT DTO with the code. That made this work.. THanks..
{ "pile_set_name": "StackExchange" }
Q: Gtk3 Python Widget Background Image I'm using Python 3.4 with Gtk 3.18. I've been able to figure out how to implement a background image via CSS for a widget (a Gtk.Box in my case). However, I want to be able to dynamically change that background image to one that the user specifies. How can that be done? The portion of the css file currently being used for the box's background. .backImagePitPass { background-image: url('../software/resources/PitPass.png'); background-size: contain; background-position: left top; background-repeat: no-repeat; border: 1px solid black; outline-style: solid; } Implementing the style sheet for the app. def _initStyles(self): css_provider = Gtk.CssProvider() css_provider.load_from_path('ui/main/gtk-widgets.css') Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) I tried this as a test, but the box and its contents don't even display. context = self._boxPreview.get_style_context() css_provider = Gtk.CssProvider() css_provider.load_from_data(b''' .backImagePitPass { background-image: url('../software/resources//PitPass2.png'); background-size: contain; background-position: left top; border: 1px solid black; } ''') context.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER) A: After doing more searching, I found a solution here Setting Selected property of Row in TreeView dynamically in Gtk3 (python) that pointed me to a workable solution.
{ "pile_set_name": "StackExchange" }
Q: Retrieve data from several Raspberry Pi disk images I have about 40 Raspberry Pi SD-Card backups, dating back several years, with different projects, some of which I barely remember. As they are clogging up my harddrive (400+ GB), I would like to reduce them to a minimum. The files were mostly created with Win32 Disk Imager, a few maybe with dd. I would prefer no to write them back to SD card, boot them and check what is on them. My idea was to mount them in Ubuntu, and retrieve the most common files and directories. I am mostly interested in: the home directory (/home/pi , /home/*) including the bash history (~/.bash_history) I wrote this untested workflow, but I am not experienced with fdisk, grep and bash variables: #!/bin/bash for filename in /RPi_images/*.img; do # creating a filedir for the backed up data mkdir /RPi_data/$filename # retrieving boot start off the second partition bootstrt = $(fdisk -l $filename 2>&1 | grep -o 'img2\s*[0-9]*' | awk '{print $2}') # multiplying boot start with sector size # assuming every image has sectors of 512 bytes offst = $bootstrt * 512 # mount the partition sudo mount -v -o offset=$offst -t ext4 $filename ~/rpi_mnt # copy all files from home dir to back up folder cp -a ~/rpi_mnt/home/. /RPi_data/$filename/home done Output of fdisk: Disk /RPi_images/150101_project1.img: 7.4 GiB, 7948206080 bytes, 15523840 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos Disk identifier: 0xbbda3dc5 Device Boot Start End Sectors Size Id Type /RPi_images/150101_project1.img1 8192 93236 85045 41.5M c W95 FAT32 (LBA) /RPi_images/150101_project1.img2 94208 15523839 15429632 7.4G 83 Linux How do I manage to get the variables $bootstrt $offstcorrect? What else would you recommend an average pi user to back up? A: How do I manage to get the variables $bootstrt $offstcorrect? You do not need them. You should losetup give a try. It is for beginners and will mount your images automagically. You do not have to fiddle with error prone offsets and it will simplify your script very much. For example I have used the Raspbian Buster Lite image: pc ~$ sudo losetup --find --partscan --show 2019-09-26-raspbian-buster-lite.img /dev/loop0 pc ~$ ls /dev/loop0* /dev/loop0 /dev/loop0p1 /dev/loop0p2 pc ~$ sudo mkdir /mnt/p2 pc ~$ sudo mount /dev/loop0p2 /mnt/p2 pc ~$ sudo mount /dev/loop0p1 /mnt/p2/boot You can mount how you like but I have mounted the partitions as they occur on the running system. If doing that you must have attention to the order of the mounts because the mountpoint for the boot partition (in this example) is only available after the first mount. If you like you can attach another image: pc ~$ sudo losetup --find --partscan --show another.img /dev/loop1 pc ~$ ls /dev/loop1* /dev/loop1 /dev/loop1p1 /dev/loop1p2 What else would you recommend an average pi user to back up? I would suggest just to create a compressed archive. So you do not have to worry about to something forget. It will reduce the backup a lot because you only save the files and not the hole space of the image. pc ~$ sudo tar -czf 2019-09-26-raspbian-buster-lite.tar.gz -V "Backup of Raspbian Buster Lite from mounted image" -C /mnt/p2 . # dot as last character Check with: pc ~$ sudo tar -tvf 2019-09-26-raspbian-buster-lite.tar.gz With unmount have attention to the reverse order: pc ~$ sudo umount /mnt/p2/boot pc ~$ sudo umount /mnt/p2 Don't forget to detach all images: pc ~$ sudo losetup --detach-all A: How do I manage to get the variables $bootstrt $offstcorrect? IMHO, Your initial approach is good. I would just avoid using an hardcoded value for the sector size, just in case of ... You maybe could use sfdisk instead of fdisk: it has been developped to ease scripting. Oh, and: To do arithmetic with bash, use the syntax offst=$((bootstrt*512)) (aka double-parenthesis) You do not umount the filesystem at then end of your for loop... You'll probably encounter some problems ;-) Instead of using the same mountpoint (~/rpi_mnt), which may cause problems if the previous run didn't umount correctly, i would instead use one temporary folder per iteration (mktemp -d ~/rpi_mountpoint.XXXX) and remove it at the end. What else would you recommend an average pi user to back up? If your project invovled GPIO and electronic stuff, i would backup /boot/config.txt too (for the dt-overlays stuff, etc...). Maybe a backup of /etc/ may be a good idea too.
{ "pile_set_name": "StackExchange" }
Q: Ubuntu Desktop 14 on PowerEdge doesn't boot on RAID I have a Dell 1U PowerEdge 1950, and for some reason, we cannot install Ubuntu 14.04 64bit Desktop edition on it. I know what you're thinking... why are you installing desktop? I have asked the same question myself over and over again! The individual that will be using this server wants to use the GUI version of Virtual Box and as a result wants nothing but the Desktop version of Ubuntu installed. That issue aside, here is the weird part. I create a RAID 1 array between the two drives like normal and do the install like normal. Everything works great and the system installs successfully. Then upon reboot it drops me to the BusyBox v1.21.1 shell. I get dropped to a (initramfs) prompt. If I pull one of the RAID 1 drives and boot again, it will boot just fine. If I replace the drive and pull the other drive, it also boots just fine. This tells me it is something to do with RAID. ie, when the RAID array is degraded, it is just booting off a single drive as if no RAID was present. When the RAID is active though, it seems it cant boot. Also, before you ask, we have confirmed this is not a hardware issue. I thought we had a RAID hardware issue and so I shipped the original server back and had it replaced with a completely different but identical server. I just tried to do the install again this morning on the new server and ran into the exact same issue. Seems like this is a driver issue, but I have never experienced this before with Ubuntu. Any thoughts? Thanks! Here is the shell I get dropped to with output: Gave up waiting for root device. Common problems: - Boot args (cat /proc/cdmline) - Check rootdelay= (did the system wait long enough?) - Check root= (did the system wait for the right device?) - Missing modules (cat /proc/modules; ls /dev) ALERT! /dev/mapper/ubuntu--vg-root does not exist. Dropping to a shell! BusyBox v1.21.1 (Ubuntu 1:1.21.0-1ubuntu1) built-in (ash) Enter 'help' for a list of builtin commands. (initramfs) A: SOLVED Boot into the system on one disk (ie degraded RAID array), and in /etc/default/grub, set: GRUB_CMDLINE_LINUX="" to GRUB_CMDLINE_LINUX="rootdelay=90" then run update-grub Once that's done, reinstall the disk you removed and re-sync the RAID array using the good disk (Should normally do this by default). Then boot like normal. This is apparently a bug in Ubuntu 14.04. They set the rootdelay to low. This appears to effect other platforms as well. Here is the bug: https://bugs.launchpad.net/ubuntu/+source/initramfs-tools/+bug/1326199 Cheers
{ "pile_set_name": "StackExchange" }
Q: Could not load file or assembly 'System.Data.Entity I am working within a Solution (a jokes website). The Solution has 2 Projects: Model (C# Class Library) MVC 3 Empty Application I am trying to get my view to list the Jokes in the Database, but I get the following error: Could not load file or assembly 'System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified As you can see from the Error message, I have already added the System.Data.Entity to the web.config of the MVC 3 application. No matter what I do, I seem to be unable to fix the error! I have added using statements for the Entity class, to the HomeController and the Index.cshtml. A: To use an external Entity Framework model (embed in a DLL for example) with ASP.NET MVC 3 you must : Add the following reference to your MVC project : System.Data.Entity (Version 4.0.0.0, Runtime v4.0.30319) Add the following line in your web.config ... < compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </assemblies> </compilation> A: To resolve this error: Go to references section in your project Right click it and than go add library package reference. search in online tab for entity framework you will get a lot of installed packages if u have internet connection enabled Select EF4 package, and finally, add it If you have any entity frame work installed and you are getting an error then click for add reference and in Browse tab go to below location: C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 Select to find System.Data.Entity.dll and then add it. This will resolve this issue. A: I was getting the same error, and it was because the MVC3 project used Entity Framework 4.1, and my domain model (in a class library project, same solution) grabbed 4.2 when I added the reference. I uninstalled EF from my Web project, then reinstalled, now both have 4.2 and are working fine. Currently working with the Apress title, Pro ASP.NET MVC Framework (Freeman).
{ "pile_set_name": "StackExchange" }
Q: What is the difference between "raise" and "rise"? What is the difference between raise and rise? When and how should I use each one? A: "Raise" when used as a verb is transitive: it requires that you have a direct object, a noun of some kind that you are applying the verb to. For example, "I must raise an objection"—"an objection" is the object that the subject (I) is using the verb to act upon. "Rise" on the other hand, is an intransitive verb: it does not require a direct object; your sentence can be complete without one. "Please rise" is entirely correct and complete.
{ "pile_set_name": "StackExchange" }
Q: Haskell can't :load a File in ghci: changeWorkingDirectory: does not exist I'm in a ghci session trying to load a Main.hs file I've been working on. It looks like I'm in the right directory in that I can see the file: ghci λ> :cd /home/username/codeplace ghci λ> :! ls lib.hs Main.hs But I can't seem to load it: ghci λ> :load Main *** Exception: code: changeWorkingDirectory: does not exist (No such file or directory) Well that's a weird error. Same for any :l variation I can think of: ghci λ> :l Main *** Exception: code: changeWorkingDirectory: does not exist (No such file or directory) ghci λ> :l Main.hs *** Exception: code: changeWorkingDirectory: does not exist (No such file or directory) ghci λ> :l 'Main.hs' target ‘'Main.hs'’ is not a module name or a source file ghci λ> :l "Main.hs" *** Exception: code: changeWorkingDirectory: does not exist (No such file or directory) ghci λ> :l ./Main.hs *** Exception: code: changeWorkingDirectory: does not exist (No such file or directory) According to reference docs here, it should just be :load Main Right? Some potential sources of weirdness that may help a haskell wizard see the error of my ways: I'm running my ghci in an emacs session using intero. I have a custom prompt in ~/.ghc/ghci.conf eg: :set prompt "ghci λ> " :set +m :set prompt2 "ghci | " Why can't I load, why am I getting this strange error about changing directories, and how can I fix? A: Hmm, I can't provide additional information as to what was happening. Went to answer comments above after rebooting the next day and everything worked fine. Strange.
{ "pile_set_name": "StackExchange" }
Q: Extensions of maximally complete fields Recall that an immediate extension of a (rank 1, non-archimedean) valued field $(K,v)$ is another valued field $(F,w)$ extending $K$, such that $w|_K = v$, and such that $F$ and $K$ have the same residue fields and value groups. We say $K$ is maximally complete if its only immediate extension is itself. Suppose $K$ is maximally complete, and let $H$ be a completion of $K(T)$ with respect to a valuation extending that on $K$, where $T$ is an indeterminate. Suppose we know either of two things: $|H| = |K|$ and $\widetilde{H} = \widetilde{K}(T)$, or $\widetilde{H} = \widetilde{K}$ and $|H^\times|$ is generated in $\mathbb{R}$ by $|K^\times|$ and one extra element $\rho \in \mathbb{R}$. Can we conclude from either of these assumptions that $H$ is also maximally complete? I'll appreciate (partial) answers referencing assumptions 1 or 2, or any counterexample. A: Those conditions do not imply that $H$ be maximally complete as can the following counter-examples illustrate. 2. Take $F:=\mathbb{R}((x^{\mathbb{R}}))$ with its natural valuation, and consider its subfield $K :=\mathbb{R}((x^{\mathbb{Q}}))$. Then $x^{\sqrt{2}}$ is transcendantal over $K$ and the completion $H$ of $K(x^{\sqrt{2}})$ in $F$ has residue field $\mathbb{R}$ and value group $\Gamma$ generated by $\mathbb{Q}$ and $\sqrt{2}$, but $H$ is not maximally complete since it does not contain $\sum \limits_{n \in \mathbb{N}} x^{\sqrt{2}(1-\frac{1}{n+1})}$ and thus admits $\mathbb{R}((x^{\Gamma}))$ as a proper immediate extension. 1. This time consider the subfield $K' = \mathbb{Q}((x^{\mathbb{R}}))$ of $F$, and its extension $K'(\pi)$ in $F$, and take $H'$ as the completion of $K'(\pi)$. Then likewise $H'$ does not contain $\sum \limits_{n \in \mathbb{N}} \pi^nx^{1-\frac{1}{n+1}}$ so it admits $\mathbb{Q}(\pi)((x^{\mathbb{R}}))$ as a proper immediate extension.
{ "pile_set_name": "StackExchange" }
Q: MD5 checksum from input stream I'm trying to get the md5 sum of an input stream but the string I get is encrypted incorrectly. The md5 string I'm getting is: ä?E´]Õaá*TàŠöJ When it should be: e48f0b45b45dd56102e12a54e08af64a Can you spot what I'm doing wrong? Here is a working program: import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class main { public static void main(String[] args) throws IOException { byte[] fileContents = new byte[15 * 10000000]; FileOutputStream out = new FileOutputStream("C:\\testFile"); out.write(fileContents); out.close(); File file = new File("C:\\testFile"); FileInputStream fs = new FileInputStream(file); System.out.println(new String(getBytesOfMd5(fs))); } public static byte[] getBytesOfMd5(InputStream is) throws IOException { byte[] buffer = new byte[1024]; MessageDigest complete = null; try { complete = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return null; } int numRead; do { numRead = is.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); } } while (numRead != -1); is.close(); return complete.digest(); } } A: The method digest() returns the hash as bytes. Then you tried to turn those bytes into a string directly. What you wanted is to convert each of those bytes into two hexadecimal digits. Here is the code: byte[] hash = complete.digest(); StringBuilder sb = new StringBuilder(); for (byte b : hash) sb.append(String.format("%02x", b & 0xFF)); String hexHash = sb.toString(); System.out.println(hexHash);
{ "pile_set_name": "StackExchange" }
Q: SQLite query error with MATCH I'm using the following query to perform a search in SQLite. public MatrixCursor listViewCursor(String query) { open(); Cursor dcursor = null; MatrixCursor cursor = new MatrixCursor(listviewColumns); Object[] listviewarray = null; String[] selectionArgs = new String[] { query }; System.out.println("Selectionarg = "+selectionArgs.toString()); if (query == null) { try {// this works dcursor = database.query(LA_DATABASE_TABLE, listviewColumns, null, null, null, null, LA_TEST_NAME); } catch (Exception e) { e.printStackTrace(); } } else try {// this don't work!!! dcursor = database.query(LA_DATABASE_TABLE, listviewColumns, LA_TEST_NAME + " MATCH ?", new String[] { query }, null, null, null); } catch (Exception e) { e.printStackTrace(); } System.out.println("dcursor count = "+dcursor.getCount()); listviewarray = new Object[dcursor.getColumnCount()]; if (dcursor.moveToFirst()) { do { for (int i = 0; i < dcursor.getColumnCount(); i++) { listviewarray[i] = dcursor.getString(i); } cursor.addRow(listviewarray); System.out.println(dcursor.getString(1)); } while (dcursor.moveToNext()); } else return null; close(); return cursor; } However I'm getting the following error. 0 1-01 04:36:27.376: I/SqliteDatabaseCpp(3171): sqlite returned: error code = 1, msg = statement aborts at 7: [SELECT _id, suggest_text_1, test_value_1, test_value_2, test_type_1 FROM la_table WHERE suggest_text_1 MATCH ?] unable to use function MATCH in the requested context, db=/data/data/com.assistant.lab.royale/databases/la_db 01-01 04:36:27.376: E/SQLiteQuery(3171): exception: SQL logic error or missing database; query: SELECT _id, suggest_text_1, test_value_1, test_value_2, test_type_1 FROM la_table WHERE suggest_text_1 MATCH ? 01-01 04:36:27.376: D/AndroidRuntime(3171): Shutting down VM 01-01 04:36:27.376: W/dalvikvm(3171): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 01-01 04:36:27.465: E/AndroidRuntime(3171): FATAL EXCEPTION: main 01-01 04:36:27.465: E/AndroidRuntime(3171): android.database.sqlite.SQLiteException: SQL logic error or missing database 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.database.sqlite.SQLiteQuery.nativeFillWindow(Native Method) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:86) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:164) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:156) 01-01 04:36:27.465: E/AndroidRuntime(3171): at com.assistant.lab.royale.DataSource.listViewCursor(DataSource.java:52) 01-01 04:36:27.465: E/AndroidRuntime(3171): at com.assistant.lab.royale.LabAssistant.filterListView(LabAssistant.java:32) 01-01 04:36:27.465: E/AndroidRuntime(3171): at com.assistant.lab.royale.LabAssistant.onQueryTextChange(LabAssistant.java:54) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.widget.SearchView.onTextChanged(SearchView.java:1091) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.widget.SearchView.access$2000(SearchView.java:90) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.widget.SearchView$11.onTextChanged(SearchView.java:1548) 01-01 04:36:27.465: E/AndroidRuntime(3171): at android.widget.TextView.sendOnTextChanged(TextView.java:7634) Why is this happening EDIT : I fixed it using dcursor = database.query(LA_DATABASE_TABLE, listviewColumns , LA_TEST_NAME + " LIKE '%"+query+"%'",null, null, null, null); but I'd like to know why the above code didn't work. Seems like ? is not getting replaced properly. A: See the Introduction to FTS3 and FTS4 from here http://sqlite.org/fts3.html and make sure you created a virtual table like this CREATE VIRTUAL TABLE enrondata1 USING fts3(content TEXT); not an ordinary like this CREATE TABLE enrondata2(content TEXT);
{ "pile_set_name": "StackExchange" }
Q: Problemas de conexão com o banco de dados Mysql Estou tentando criar um sistema para faculdade, porém estou com um erro ao tentar conectar com Mysql, estou utilizando PHP e Xampp. Erro: Fatal error: Call to undefined function mysqli_conect() in C:\xampp\htdocs\Cursos\Testes\conecta.php on line 2 Já tentei algumas soluções que funcionaram com outros mas não funcionaram comigo: Alterações no PHP.ini: extension_dir="C:\xampp\php\ext" - Está de acordo com o que informam. extension=php_mysql.dll e extension=php_mysqli.dll - Descomentadas. Apache reiniciado após as alterações. Alguém tem alguma ideia do que pode ser feito? Agradeço desde já. A: Como o usuário acima disse mysqli_conect está mal escrita, escreve-se mysqli_connect, daí teres o retorno : Fatal error: Call to undefined function mysqli_conect() in C:\xampp\htdocs\Cursos\Testes\conecta.php on line 2 que diz que a função não existe ou não está definida. Veja se isso lhe ajuda. <?php $link = mysqli_connect('localhost', 'Usuario_', 'Senha_', 'banco_de_dados_'); if(mysqli_connect_errno()){ die("Erro: ". mysqli_error()); } echo 'Conexão bem sucedida'; mysqli_close($link); ?>
{ "pile_set_name": "StackExchange" }
Q: Uploading a File to SharePoint Online using Microsoft Graph API I'm really new to Microsoft Graph API, I created a script using powershell to get reports from Microsoft 365 and it is being saved on my drive (c:\temp\reports.xlsx). After it is being saved i wish to upload it to SharePoint online. On reading the docs, Microsoft says to do the following request, PUT /sites/{site-id}/drive/items/{parent-id}:/{filename}:/content I then tried to apply it to my use case and this was my request: function RestMethod { Param ( [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Request, [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$RequestMethod, [parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$Body ) $Headers = @{ Authorization = "$($global:RequestToken.token_type) $($global:RequestToken.access_token)" } $RestResults = $null [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 try { $RestResults = Invoke-RestMethod -Uri $Request -Headers $Headers -Method $RequestMethod -ContentType "application/json" } catch { Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription } return $RestResults } $upLoadRequest = "https://graph.microsoft.com/v1.0/sites/tenant.sharepoint.com/drive/items/Test:/$($File):/content" $upLoadResults = RestMethod $upLoadRequest 'PUT' The $File variable contains c:\temp\reports.xlsx the directory where my excel file is saved on getting the reports. The Test in my Url is a folder I created in Documents on my Site. But while doing the request I get this: StatusCode: 400 StatusDescription: Bad Request Please Help Thanks A: The list of changes: in the provided question file is incorrectly addressed, since it needs to be uploaded under Test folder of Documents library, it could be addressed like this: /v1.0/sites/{tenant}.sharepoint.com/drive/root:/Test/reports.xslt:/content refer Addressing resources in a drive on OneDrive for a more details the content of file for Upload endpoint is missing , it could be provided via -InFile parameter, e.g. Invoke-RestMethod -InFile $path ... Here is a minimal example: $access_token = "--access token goes here--" $path = "--path to local file, e.g. c:\data\report.xlsx--" $url = "https://graph.microsoft.com/v1.0/sites/{tenant}.sharepoint.com/drive/root:/{folder}/{filename}:/content" $headers = @{'Authorization' = "Bearer $access_token" } Invoke-RestMethod -Uri $url -Headers $headers -Method Put -InFile $path -ContentType 'multipart/form-data'
{ "pile_set_name": "StackExchange" }
Q: How to change the font size in ListView in JavaFX? I tried this suggestion http://forums.sun.com/thread.jspa?threadID=5421037 but style cannot be found. Is there any other way? Lots of thanks, cancelledout A: It depends on the version of JavaFX, I will suppose it is about 1.3. By default, ListView shows the result of toString() applied to the objects stored in its items variable. But you can define a cellFactory function that will generate a ListCell that takes these objects and presents in a Node holding whatever you put in, for example a Text or Label, or something more complex. So, there, you can format the text the usual way. Now, if you don't want to go to that level of detail, just use CSS: .list-cell { -fx-font: 18pt "Arial"; }
{ "pile_set_name": "StackExchange" }
Q: Counting sentences, only sentences ending with punctuation + 2 spaces I'm trying to figure out how to make a sentence counter, which I have, but the thing is, I need it to count a sentence ONLY when two spaces come after the period/question mark/etc. For example, with the code I have, if you enter the string "hello, my name is ryan..." it returns the count of 3 sentences. I need it to only count one sentence. This program needs to count words also. I count the words by taking the amount of spaces - 1. This is where my problem lies, I either mess up the word count or the sentence count. Here is the method for the word count: public static int countWords(String str){ if(str == null || str.isEmpty()) return 0; int count = 0; for(int i = 0; i < str.length(); i++){ if(str.charAt(i) != ' '){ count++; while(str.charAt(i) != ' ' && i < str.length()-1){ i++; } } } return count; } And here is the method for counting sentences: public static int sentenceCount(String str) { String SENTENCE_ENDERS = ".?!"; int sentenceCount=0; int lastIndex=0; for(int i=0;i < str.length(); i++){ for(int j=0;j < SENTENCE_ENDERS.length(); j++){ if(str.charAt(i) == SENTENCE_ENDERS.charAt(j)){ if(lastIndex != i-1){ sentenceCount++; } lastIndex = i; } } } return sentenceCount; } A: I actually got it, using regex, was super simple also. public static int sentenceCount(String str) { String regex = "[?|!|.]+[ ]+[ ]"; Pattern p = Pattern.compile(regex); int count = 0; Matcher m = p.matcher(str); while (m.find()) { count++; } if (count == 0){ return 1; } else { return count + 1; } } Works great, I added the if statement assuming user is inputting at least one sentence, and added one to the count assuming they won't put two spaces at the end of their last sentence.
{ "pile_set_name": "StackExchange" }
Q: MVVM ListBox controlling a Content Control I've been going round in circles with this for a couple of days, and I'm hoping a WPF guru can see where I'm going wrong. I'm setting CurrentViewModel in code. The Selected item of my ListBox and the Content of my ContentControl bind correctly. But when changing the selected item in the Listbox via the UI the CurrentViewModel is being set but the Content Control is not being updated. I'm using a data template to map my Views and View Models. <DataTemplate DataType="{x:Type ViewModel:MyViewModel}"> <View:MyView /> </DataTemplate> I have a ListBox which is bound to an observable collection of ViewModels. The Selected Item is bound to the current view model. <ListBox ItemsSource="{Binding MyViewModelCollection}" DisplayMemberPath="DisplayName" SelectedItem="{Binding CurrentViewModel, Mode=TwoWay}"/> I also have a content control that is also bound to the CurrentView Model <ContentControl Content="{Binding CurrentViewModel, Mode=TwoWay}"/> This is the property that they are both bound to public MyViewModel CurrentViewModel { get { return _currentViewModel; } set { if (_currentViewModel== value) return; _currentViewModel= value; OnPropertyChanged("CurrentViewModel"); } } I've edited the names for clarity and removed formatting information. Any help greatly appreciated. Cheers, Daniel EDIT: Came across the link How can I debug WPF bindings?. I set a break point on the Content binding and it does indeed only get called once when the binding is first set. A: You should not be setting TwoWay as the mode on your ContentControl: <ContentControl Content="{Binding CurrentViewModel, Mode=OneWay}"/> This is because you intend your ContentControl to read the value, but never write it. As an aside, you can also bind the ContentControl to the currently selected item in the collection, rather than to that property by doing this: <ListBox ItemsSource="{Binding MyViewModelCollection}" DisplayMemberPath="DisplayName" IsSynchronizedWithCurrentItem="True"/> <ContentControl Content="{Binding MyViewModelCollection/}"/> The "slash" (/) at the end of the collection indicates the current item selected in the collection and setting that current item property is as simple as setting the IsSynchronizedWithCurrentItem equal to true. A lot of times I find with this combination, I really don't need the extra property on my view model. Anyway, I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: GCD, order of execution? Assume we have one UIVewcontroller, call it A, in the viewdidload of that VC we add to it two UIViewcontrollers( B,C ). now to make the UI smooth in the Viewdidload of A we do some GCD work dispatch_queue_t queue = dispatch_queue_create("CustomQueue", NULL); dispatch_async(queue, ^{ // Create views, do some setup here, etc etc // Perform on main thread/queue dispatch_async(dispatch_get_main_queue(), ^{ // this always has to happen on the main thread [self.view addSubview:myview1]; [self.view addSubview:myview2]; [self.view addSubview:myview3]; }); }); Now based on this code, am I guaranteed that the views will be added in the same order? view 1 , then 2 , then 3? I am noticing that arbitrarily some views shows up before others !! A: Your problem is almost certainly this part: dispatch_async(queue, ^{ // Create views, do some setup here, etc etc You cannot do anything view-related (or really anything UIKit-related) on a background thread. Period.
{ "pile_set_name": "StackExchange" }
Q: How can i insert timestamp with timezone in postgresql with prepared statement? I am trying to insert to a timestamp with timezone field of my DB a string which includes date, time and timezone using prepared statement. The problem is that Timestamp.valueof function does not take into consideration the time zone that the string inludes so it causes an error. The accepted format is yyyy-[m]m-[d]d hh:mm:ss[.f...] which does not mention timezone. That is the exact code that causes the error: pst.setTimestamp(2,Timestamp.valueOf("2012-08-24 14:00:00 +02:00")) Is there any way that i can overcome it?? Thanks in advance! A: The basic problem is that a java.sql.Timestamp does not contain timezone information. I think it is always assumed to be "local timezone". On solution I can think of is to not use a parameter in a PreparedStatement, but a timezone literal in SQL: update foo set ts_col = timestamp with time zone '2012-08-24 14:00:00 +02:00'`; Another possible solution could be to pass a properly formatted String to a PrepareStatement that uses to_timestamp(): String sql = "update foo set ts_col = to_timestamp(?, 'yyyy-mm-dd hh24:mi:ss')"; PreparedStatement pstmt = connection.prepareStatement(sql); pstmt.setString(1, "2012-08-24 14:00:00 +02:00");
{ "pile_set_name": "StackExchange" }
Q: Is having a loop in C++ constructor a good Idea? I was writing code for my homework. So as I finished one of my classes I ran into a question. Is having a loop to assign values to array a good idea? This is my class. I was thinking of making either loop in the constructor or create a function which would assign values later, by calling it manually. Are these choices different? if yes, Which choice is better and why? class Mule { private: int numofMules; int MapSize; MuleNode* field; MuleNode* mules; public: void random_positions(); void motion(); void print_field(); Mule(int nofMules, int mSize) { numofMules = nofMules; MapSize = mSize; mules = new MuleNode[numofMules]; field = new MuleNode[MapSize*MapSize]; for(i = 0; i < numofMules; i++) { mules[i].ID = i+1; } random_positions(); } } Edited the code because of the problem with allocation of one dimensional array at compilation time and recreated 2 dimensional array in 1 dimensional using formulas. +---------------+-----------+-----------+ | i = j * w + i | x = i % w | y = i / w | w - width of the 2 dimentional array +---------------+-----------+-----------+ Conclusion: As the question was marked as opinion-based, I guess it means that there is no big difference in using loop in the constructor or creating a function which would assign values later. If there are any facts or opinions about this question worth sharing, please comment or write your answer. A: There's not necessarily anything terrible about having a loop in a ctor. At the same time, it's worth considering whether those items you're initializing couldn't/shouldn't be objects that know how to initialize themselves instead of creating uninitialized instances, then writing values into them. As you've written it, the code doesn't really seem to make much sense though. The class name is Mule, but based on the ctor, it's really more like a collection of Mules. A Mule should be exactly that: one mule. A collection of N mules should be something like a std::vector<Mule>. A Mule that's really a collection of Mules is a poor idea. You should also at least consider using std::vector instead of an array (assuming that you end up with a collection of items in the class at all, of course).
{ "pile_set_name": "StackExchange" }
Q: How many vectors from the matrix are linearly independent? I have the matrix: $$ \begin{pmatrix} 3 & 2 & -1 & 4 \\ 1 & 0 & 2 & 3 \\ -2 & -2 & 3 & -1 \\ \end{pmatrix} $$ I have 2 questions to answer: Consider the columns of the matrix as vectors in $R^3$. How many of these vectors are linearly independent? Consider for $R^4$. How many vectors are linearly independent? Is the answer in both cases 2 or am I totally wrong about how to solve this. Thanks A: I interpret the first part of the question as asking for the column rank of the matrix and the second part of the question as asking for the row rank of the matrix. Yes, compute its RREF and you can see that there are two pivot columns, hence the rank is $2$. It is known that the row rank is equal to the column rank and the answer is $2$ for both.
{ "pile_set_name": "StackExchange" }
Q: How to re-enable RightClick only for specific tag/id I'm using this code: document.oncontextmenu = (function() { var counter = 0; return function() { counter++; if (counter == 3) { $("<div id='r-click'></div>").appendTo("#container").html("<span>!!! Protected content !!!</span>").fadeIn(500).show().delay(4000).fadeOut(800, function() { counter = 0; }); } return false; }; })(); Now, my issue is that I have a textarea with the HTML code for a banner, and I need context menu appear only on it. Is possible edit the code I'm using? A: Here the final working example: var counter = 0; document.oncontextmenu = function(e) { if (e.target.id != "txt") { counter++; if (counter == 3) { $("<div id='r-click'></div>").appendTo("#container").html("<span>!!! Protected content !!!</span>").fadeIn(500).show().delay(2000).fadeOut(800, function() { counter = 0 }); } return false; }; }; https://jsfiddle.net/t579asv5/5/
{ "pile_set_name": "StackExchange" }
Q: Ordered lists in django i have very simple problem. I need to create model, that represent element of ordered list. This model can be implemented like this: class Item(models.Model): data = models.TextField() order = models.IntegerField() or like this: class Item(models.Model): data = models.TextField() next = models.ForeignKey('self') What way is preferred? What drawbacks have each solution? A: Essentially, the second solution you propose is a linked list. Linked list implemented at the database level are usually not a good idea. To retrieve a list of n elements, you will need n database access (or use complicated queries). Performance wise, retrieving a list in O(n) is awfully not efficient. In regular code, linked list are used to get better insert performance compared to arrays (no need to move all elements around). In your database, updating all elements is not that complicated in only 2 queries : UPDATE item.order = item.order + 1 FROM item WHERE order > 3 INSERT INTO item (order, ...) VALUES (3, ...) I remember seeing a reuseable app that implemented all that and a nice admin interface, but I cant find it right now ... To summarize, definitly use solution #1 and stay away from solution #2 unless you have a very very good reason not to ! A: That depends on what you want to do. The first one seems better to make a single query in the database and get all data in the correct order The second one seems better to insert an element between two existing elements (because in the first one you'd have to change a lot of items if the numbers are sequential) I'd use the first one, because it seems to fit better a database table, which is how django stores model data behind the hood.
{ "pile_set_name": "StackExchange" }
Q: Including external Header files in programs Being using Windows for most of the time and deciding to start programing in ubuntu,I would like to know how I can include the external header file in my programs.Do I download them manually and paste them into the folder wheres the file?Please be kind... A: If you have a program print.c that prints a text: /* print.c */ #include <stdio.h> #include "print.h" int main(void) { puts(TEXT); return 0; } and a header file defining that text: /* print.h */ #define TEXT "Hello World!" Then you usually put these files in the same folder. For external dependencies, it depends. Many external dependencies should not be downloaded from a website, but installed from the Ubuntu repositories. For instance, the OpenGL headers are available from libgl1-mesa-dev (which installs mesa-common-dev). This makes the headers available in /usr/include/GL/gl.h. In other cases where the header file is not located in the same directory, specify the different include directories while compiling. Example where you have a directory external-deps containing header files: cc -I external-deps source.c -o output-program If there are libraries involved (example for an OpenGL program using libGL): cc -I external-deps source.c -o output-program -L path/to/libraries -lGL
{ "pile_set_name": "StackExchange" }
Q: How to know when you have a file open in vi while using the shell? When I am editting a file in vi or vim, I frequently will be editting the file, and then I need to open a shell to execute a shell command. So, I go to the shell by doing :sh. This brings me to the shell. Now, when I want to return to the file I'm editting, I will freqquently do control + D to return the file. This works fine. I followed the instructions here. I do a lot of work on remote AWS machines which I am ssh-d into. And, control+D is one way to exit those machines. Unfortunately, while ssh-d into those machines, sometimes I do not know if I have a file open in vi/vim and when I do control + D to go back to the file, it exits my ssh session entirely. Is there a way to either 1) know that I have a file currently open in vi or 2) exit the shell and go back to my file safely without risking accidentally closing my ssh session? A: It looks like the problem you're having isn't trying to figure out whether vi is running but rather how to jump between the parent shell and vi using "job control" (grep for job control in the bash or sh man page). Use ctrl-z to background vi and use fg to resume. This works in all POSIX-derived shells and it works over ssh. This is preferred over using :sh and ctrl-d since you avoid the problem you're having, you get the same shell that you were working with when you started vi, and you have one less shell running (this isn't often a performance issue but if you have a lot of shells running it's easier to look at their PIDs when needed). There may be other reasons for :sh but the only one I know of is getting a shell in a vi session that wasn't started from a shell to begin with. Having said that, vi -r (with no args) prints a list of swap files that subsumes the set of files open in vi. Commands like vi -r |& grep -B 3 'still running' are useful.
{ "pile_set_name": "StackExchange" }
Q: Legacy apps requiring administrator privileges on XP I have a legacy Windows 95 app that needs to be run as an Administrator. This is used by students in a school domain. My predecessor set up a domain administrator account for this purpose and a "Run As.." batch script to start the program, but this still requires a teacher to enter a password. I'd like a simpler way for students to start the app, without giving them increased local privileges or the password to a domain administrator account. What's the best way to do this? A: I normally start by finding the HKLM key that the software uses - hopefully something sane - and using regedt32 (note regular regedit won't work) give thier group full control of that registry key. Then I'll give them full control of the installation directory. 99% of the time this resolves issues with needed local admin. Normally at this point if it doesn't work out i start lobbying to upgrade the app sometimes that works sometimes it doesn't. If you are really lucky and it's a common program searching google will give you the exact places you need to give permissions to run as a non admin. A: I hope you mean that you a user in a group that is in the local computer's administrator group, and you don't give out an account that is a member of domain admins. There is absolutely no reason, that the account should need to be a member of the domain administrator group. If you have given out an account to the teachers that is a member of domain admins I strongly urge you to change this ASAP. You should create another group in the domain, and make that group a member of the local administrators group on the computers. You should be able to add the group you create to the local administrators group with a startup script applied by a GPO. Anyway back to solving the issues for the program. What you may need to do is figure out what the application is doing that needs administrative access and then modify the permissions of the filesystem and registry so that students have those privileges. The sysinternals tools filemon, and regmon will be very useful in figuring this out. If you haven't already, try searching Google for information about that specific program, perhaps someone else has already solved the problem and fixed it.
{ "pile_set_name": "StackExchange" }
Q: 3D моделирование в C#, накладывание одного объекта на другой, с чего начать Пример для понимания моей цели: полотенце падает на чайник -> полотенце лежит на чайнике С помощью чего это возможно реализовать, и чем удобней? wpf, opengl, unity... В интернете немало библиотек для реализации 3d, но какая подходит для обработки падения под весом гравитации и "расползания" полотенца по поверхности чайника? A: Погуглите "физика ткани" для C#. Скорее всего, Вам понадобится массив точек фигуры, в котором каждая точка (вершина сетки) подвержена физическим силам (сила гравитации как функция от массы, натяжение соседних с другими вершинами связей, сила упругости поверхности, на которую падает ткань и каждая её точка, сила трения с поверхностью, по которой ткань скользит или скользить не может). Начните с математической модели. опишите сферу по точкам (возьмите не сильно много точек). Для начала - замечательной "сферой" будет куб. Возьмите плоскость 3х3 квадрата (16 вершин). Задайте вершинам плоскости параметры. Задайте вершинам "сферы" параметры. Проведите эксперимент в текстовом режиме. Дальше уже можно будет эту модель привязать к любой графике. И касательно OpenGL, могу сказать, что после построения описанной выше математической (физической) модели, Вы легко сможете повторить её уже в шейдерах (программах для графического процессора) в рамках OpenGL Shading Language. (Презентация на тему) (Вводная статья по шейдерам) Cloth simulation - симуляция ткани на шаре от GeForce (и не только).
{ "pile_set_name": "StackExchange" }
Q: SQL Server Alternative to reseeding identity column I am currently working on a phone directory application. For this application I get a flat file (csv) from corporate SAP that is updated daily that I use to update an sql database twice a day using a windows service. Additionally, users can add themselves to the database if they do not exist (ie: is not included in the SAP file). Thus, a contact can be of 2 different types: 'SAP' or 'ECOM'. So, the Windows service downloads the file from a SAP ftp, deletes all existing contacts in the database of type 'SAP' and then adds all the contacts on the file to the database. To insert the contacts into the database (some 30k), I load them into a DataTable and then make use of SqlBulkCopy. This works particularly, running only a few seconds. The only problem is the fact that the primary key for this table is an auto-incremented identity. This means that my contact id's grows at a rate of 60k per day. I'm still in development and my id's are in the area of 20mil: http://localhost/CityPhone/Contact/Details/21026374 I started looking into reseeding the id column, but if I were to reseed the identity to the current highest number in the database, the following scenario would pose issues: Windows Service Loads 30 000 contacts User creates entry for himself (id = 30 001) Windows Service deletes all SAP contacts, reseeds column to after current highest id: 30 002 Also, I frequently query for users based on this this id, so, I'm concerned that making use of something like a GUID instead of an auto-incremented integer will have too high a price in performance. I also tried looking into SqlBulkCopyOptions.KeepIdentity, but this won't work. I don't get any id's from SAP in the file and if I did they could easily conflict with the values of manually entered contact fields. Is there any other solution to reseeding the column that would not cause the id column values to grow at such an exponential rate? A: I suggest following workflow. import to brand new table, like tempSAPImport, with your current workflow. Add to your table only changed rows. Insert Into ContactDetails (Select * from tempSAPImport EXCEPT SELECT Detail1, Detail2 FROM ContactDetails) I think your SAP table have a primary key, you can make use of the control if a row updated only. Update ContactDetails ( XXX your update criteria) This way you will import your data fast, also you will keep your existing identity values. According to your speed requirements, adding indexes after import will speed up your process.
{ "pile_set_name": "StackExchange" }
Q: java swing hold both mouse buttons I want to implement a method where the user needs to hold the left and right mouse buttons at the same time. I'm using Swing and Java 1.7. I've tried this, but it doesn't detect the both-buttons case like I'd expect it to: public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e) && SwingUtilities.isRightMouseButton(e)){ ///code here } } i tried to separate methods and use bool values to decide if the mouse button is pressed and then i set a condition to find out if both of them are pressed at the same time , but that didint work out too .. A: This is an SSCCE that does what you want... i.e. if I understood your question correctly. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class StackOverflow15957076 extends MouseAdapter { private JLabel status; private boolean isLeftPressed; private boolean isRightPressed; public StackOverflow15957076 () { JFrame frame = new JFrame (); frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel (new FlowLayout (FlowLayout.CENTER)); status = new JLabel ("waiting for both mouse buttons..."); status.addMouseListener (this); panel.add (status); frame.add (panel); frame.pack (); frame.setVisible (true); isLeftPressed = false; isRightPressed = false; } @Override public void mousePressed (MouseEvent e) { if (SwingUtilities.isLeftMouseButton (e)) { isLeftPressed = true; } else if (SwingUtilities.isRightMouseButton (e)) { isRightPressed = true; } if (isLeftPressed && isRightPressed) { status.setText ("both buttons are pressed"); } } @Override public void mouseReleased (MouseEvent e) { if (SwingUtilities.isLeftMouseButton (e)) { isLeftPressed = false; } else if (SwingUtilities.isRightMouseButton (e)) { isRightPressed = false; } status.setText ("waiting for both mouse buttons..."); } public static void main (String[] args) { SwingUtilities.invokeLater (new Runnable () { @Override public void run () { new StackOverflow15957076 (); } }); } }
{ "pile_set_name": "StackExchange" }
Q: sql count of multiple tables possible inner join I have a Table called Jobs and 02 other tables (places and times) that connect to Jobs by the JobID. So, based on the tables below, I need the following in SQL server: Jobs (JobID,Company) 123 ABC 456 DEF 789 GHI PLACES (Country,JobID) BR 123 EU 123 CA 456 TIMES(time,JobID) 05 456 08 123 09 789 Needed query Result: QRYRESULT(JobID,CountOFPLaces,CountofTimes) 123 , 2, 1 456 , 1 , 1 789 , , 1 Thanks for the help! A: There keys here are knowing that using an outer join can give you all results for all jobs and that a count(distinct field) will give you distinct counts eliminating the additional counts added by joins (assuming each record is unique and that duplicates don't exist in a given table) SELECT J.jobID, count(Distinct P.Country) as CountOfPlaces, Count(Distinct T.Time) as CountOfTimes FROM Jobs J LEFT JOIN Places P on J.JobID=P.JobID LEFT JOIN Times T on T.JobID = J.JobID GROUP BY J.JobID
{ "pile_set_name": "StackExchange" }
Q: How can I restore file in master branch I was coding on branch called feature/restful-api, and I want to checkout the files in master branch, so I did git checkout master and changed to master branch. When I wanted to change back, git told me that error: The following untracked working tree files would be overwritten by checkout: gradle/wrapper/gradle-wrapper.jar gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat Please move or remove them before you switch branches. Aborting So I deleted these files and changed back to feature/restful-api branch. Now I found that all the configurations has gone. How can I restore these file back? A: It seems you've deleted the files without Git ever knowing about them. In that case Git can't help you get them back. I'm assuming they're not in Trash/Recycle Bin either. If you're using IntelliJ IDEA, try the Local History feature. Open the project in IDEA, right-click the root of the project and select Local History > Show History... I've recovered a few files this way, can be a life saver.
{ "pile_set_name": "StackExchange" }
Q: SQL Server Session State, web farm, and counting the sessions I have 2 load balanced web servers. My application is using the SQL Server Session State database on SQL Server 2008. The 2 web servers are identical in terms of IIS configuration, and if I understand correctly, the two web apps on the two servers will be mapped to the same app id in the ASPStateTempApplications table since they have the same IIS configuration. So, counting the number of sessions associated with this app Id (from the ASPStateTempSessions tabel) will result in the total count of sessions on the two web servers together. My questions is: Is there a way to know how many sessions are active on each server individually? I have the problem that when I take one server out of the load balance, I want to know if there are still any active sessions on the server or not before recycling it. Another scenario, if I have to recycle the IIS on one of the servers because another web app on the same server is crashing, I would like to know how many sessions will be affected when I do so. Thanks. A: Basically, they all may and actually SHOULD be active on both ) Because in this mode sessions are not bound to the web-servers at all. You can stick each user to a single server with load-balancing techniques on your gateway and if so - better to use InProc mode with all its benefits )
{ "pile_set_name": "StackExchange" }
Q: Transposition of state space form of a transfer function How can I transpose the output of state space model in Mathematica? trying the following code would transpose the top right symbol s instead of the matrices. Transpose @ StateSpaceModel @ TransferFunctionModel[{{a^2/(s^2 + b s + c)}}, s] A: I am not sure what a valid transpose of a StateSpaceModel is but here is an attempt: ssm = StateSpaceModel @ TransferFunctionModel[{{a^2/(s^2 + b s + c)}}, s] Transpose /@ #[[{1, 3, 2, 4}]] & /@ ssm
{ "pile_set_name": "StackExchange" }
Q: jooq-3.2.0 and db2 database Can I use jooq-3.2.0 to work with db2 database, if yes which driver i have to use while generating entity classes from existing schema. I tried to use org.jooq.util.db2.DB2Database, but generator throws exception. Here is stacktrace: java.lang.ClassNotFoundException: org.jooq.util.db2.DB2Database at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at org.jooq.util.GenerationTool.loadClass(GenerationTool.java:335) at org.jooq.util.GenerationTool.run(GenerationTool.java:212) at org.jooq.util.GenerationTool.main(GenerationTool.java:141) at org.jooq.util.GenerationTool.main(GenerationTool.java:128) java.lang.ClassNotFoundException: org.jooq.util.db2.DB2Database at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at org.jooq.util.GenerationTool.loadClass(GenerationTool.java:335) at org.jooq.util.GenerationTool.run(GenerationTool.java:212) at org.jooq.util.GenerationTool.main(GenerationTool.java:141) at org.jooq.util.GenerationTool.main(GenerationTool.java:128) I'm using community edition now. A: With jOOQ 3.2, jOOQ has become dual-licensed. The DB2 integration is available only with a jOOQ Enterprise Edition license. You may, however, download a free 30 day trial version that works with DB2. Note, there is also a fix for jOOQ 3.2.1 (to be released soon), to give community edition users more information rather than just a stack trace.
{ "pile_set_name": "StackExchange" }
Q: How to mark outbound FTP traffic with iptables? i have a user called "testuser" in my debian system and i want to mark the FTP traffic going from testuser's account how can i do that? i use following commands to mark all the outgoing traffic for "testuser" iptables -t mangle -N HTB_OUT iptables -t mangle -I POSTROUTING -j HTB_OUT iptables -t mangle -A HTB_OUT -m owner --uid-owner testuser -j MARK --set-mark 10 how to set two marks for "testuser"? one for FTP traffic only and one for all other traffic? A: Add a --dport (--destination-port) option. You'll need at least two of them - 20:21 for FTP traffic and !20:21 for non-FTP.
{ "pile_set_name": "StackExchange" }
Q: Fiberglass batts: how to cover the exposed paper? I need to install fiberglass batts under my (raised) house. I have read that the paper should generally face the warm side, so it depends on where one lives. I live in South Louisiana, so I plan to place the batts with the paper facing outside. But there are clear instructions on the cover of the insulation packs that say that the paper should not be left exposed, so it will need to be covered, but with what? A: At the least i would cover it with 1/4" plywood. At the most I would cover it with 4X8 sheets of cement board. Depending on the moisture present under the home, would temper the choice further.
{ "pile_set_name": "StackExchange" }
Q: How to update 2 tables in mysql? I would like to update two tables called: routing and routing_has_work_center In routing table, user can edit the description while in routing_has_work_center table, user can edit the production_hour. <?php session_start(); // include a php file that contains the common database connection codes include ("dbFunctions.php"); //retrieve computer details from the textarea on the previous page $description = $_POST['description']; $production_hour=$_POST['$production_hour']; //retrieve id from the hidden form field of the previous page $theID = $_POST['routing_id']; $msg = ""; //build a query to update the table //update the record with the details from the form $queryUpdate = "UPDATE routing SET description='$description' WHERE routing_id = $theID"; //execute the query $resultUpdate = mysqli_query($link, $queryUpdate) or die(mysqli_error($link)); //if statement to check whether the update is successful //store the success or error message into variable $msg if ($resultUpdate) { $msg = "Record updated successfully!"; } else { $msg = "Record not updated!"; } ?> I have this the code above but when I update the production hour, it remains the same and is not updated at routing_has_work_center database. Do I have to add something else to the query? A: Check this. $queryUpdate = "UPDATE routing_has_work_center SET production_hour='$production_hour' WHERE routing_id = '$theID' ";
{ "pile_set_name": "StackExchange" }
Q: Iterate over regions and take mean pixel value in OpenCV? So Im basically trying to divide up a gray scale image (in this case 32x32) by resizing the initial image. Once the "regions" are divided up, I need to take the mean pixel value of each one and then add to a string a 1, 0, or X. For example: "Region (3, 19) has a mean value of 21 so that's a 1". I think I have most of the logic down but shouldn't, in theory, the output recreate the image in the form of 1s, 0s, and Xs? I feel like my math is wrong on the for loops maybe? Remember, all Im trying to do is break the image up into an MxN table or grid and taking the mean, 0 channel value of each grid region. Here is my code: Mat image = imread("blackdot.jpg", IMREAD_GRAYSCALE); //Pass in image imshow("Gray scaled image", image); //imshow("Passed in gray scale image", image); Mat resizedImage; // New Mat for saving the blown up image resize(image, resizedImage, Size(3200, 3200)); // Blow up image so it's divisible by 32 using passed in image string bitStream; // Ternary bitstream for (int y = 0; y<resizedImage.cols - 32; y += 32) { for (int x = 0; x<resizedImage.rows - 32; x += 32) { // get the average for the whole 32x32 block Rect roi(x, y, 32, 32); Scalar mean, dev; meanStdDev(resizedImage(roi), mean, dev); // mean[0] is the mean of the first channel, gray scale value; if (mean[0] >= 0 && mean[0] <= 25) { if ((counter % 3200) == 2900) { bitStream += "1\n"; counter = 0; } else { bitStream += "1"; } else if (mean[0] >= 77 && mean[0] <= 153) { if ((counter % 3200) == 2900) { bitStream += "X\n"; counter = 0; } else { bitStream += "X"; } else { if ((counter % 3200) == 2900) { bitStream += "0\n"; counter = 0; } else { bitStream += "0"; } } } cout << bitStream; blackdot.jpg A: The code and logic looks good, for each pixel distribution, add a corresponding character to the bitstream and repeat that for all pixels in the row and for every column in the image. When adding characters to the bitstream, try appending \n to the bitstream when a newline is reached (ie. when a row has been completed), to account for, in the bitstream, the alignment of the image. This equates to this minor adjustment in your code: for (int y = 0; y<resizedImage.cols - 32; y += 32) { for (int x = 0; x<resizedImage.rows - 32; x += 32) { // get the average for the whole 32x32 block Rect roi(x, y, 32, 32); Scalar mean, dev; meanStdDev(resizedImage(roi), mean, dev); // mean[0] is the mean of the first channel, gray scale value; if (mean[0] >= 0 && mean[0] <= 25) { bitStream += "1"; } else if (mean[0] >= 77 && mean[0] <= 153) { bitStream += "X"; } else { bitStream += "0"; } } //after each row has been checked, add newline bitStream += '\n'; } Note: The output window may need maximizing to see correct results.
{ "pile_set_name": "StackExchange" }
Q: How to make the path a variable in react-router? Like I have /a/Star/video I want to make the video a variable, star is already a param. How to do it? I need to know is, When video is provided, I need to render one component and when it is not provided, I want to render another component? A: You can use nested routes and an <IndexRoute> to handle this: <Route path='/a/:param1' component={Root}> <IndexRoute component={OnlyParam1} /> <Route path='video' component={WithVideo} /> </Route>
{ "pile_set_name": "StackExchange" }
Q: In Lucene, what is the accepted way to return an approximate result count without impacting performance? I want my users' search results to include some idea of how many matches there were for a given search query. However, after a bit of research and observation of my users' search logs, I've noticed a direct correlation between logged query speed and the number of total results and have determined that this is because I am accessing the totalHits property, which apparently has to iterate over the entire result set in order to return a value. I would be happy to simply return an approximate value, maybe even just an order of magnitude indicating a rough idea of how many results are available, but I can't see if there's any good way to calculate this without noticeably affecting performance. I don't really want to just dump a seemingly-bottomless result set in front of the user without providing them any rough idea of how many results their search matched. Any suggestions? A: With boolean queries you can try to approximate: |A or B| / |D| = ((|A| / |D|) + (|B| / |D|)) / 2 |A and B| / |D| = (|A| / |D|) * (|B| / |D|) Where A and B are two terms, and |D| is the total number of documents. This is basically making an assumption of independence. You can use the rewrite method to rewrite any query to a boolean query. There isn't really a better way of doing this, but I've found that this assumption isn't too bad in practice. If you have a very small number of docs it might give bad answers though. EDIT: as jpountz points out, my calculation for OR is wrong. Should be: P(A U B) = 1 - P(~(AUB)) = 1 - P((~A) & (~B)) = 1 - P(~A)P(~B) = 1 - (1 - P(A))(1 - P(B)) = 1 - (1 - P(A) - P(B) + P(A)P(B)) = P(A) + P(B) - P(A)P(B)
{ "pile_set_name": "StackExchange" }
Q: CSV formatted data off website not being properly parsed My Python script opens a file through urllib2; the data looks like this: "Charitable Donation: Contribution","012","","","","","","","","","","","","","","","","","","","","" The Python script: reader = csv.reader(data, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: print row The output is this: ['Charitable Donation: Contribution'] ['', ''] ['012'] ['', ''] [''] ['', ''] [''] ['', ''] [''] ['', ''] [''] ['', ''] [''] ['', ''] [''] ['', ''] [''] ['', ''] [''] ['', ''] [''] What am I doing wrong? A: You're using double-quote (") as the delimiter instead of comma (,) ...why? How about reader = csv.reader(data, delimiter=',', quoting=csv.QUOTE_ALL) for row in reader: print row # you can omit the delimiter argument as well, since comma is the default: reader = csv.reader(data, quoting=csv.QUOTE_ALL) # etc.
{ "pile_set_name": "StackExchange" }
Q: Combinational System Theoretical Question I'm currently taking an MIT-OCW course, where it says that a system built from smaller combinational systems following the following compositional rules is combinational: Each component of the system must itself be a combinational device. Each input of each component must be connected a system input, or to exactly one output of another device, or to a constant voltage representing the value 0 or the value 1. The interconnected components cannot contain any directed cycles, i.e., paths through the system from its inputs to its outputs will only visit a particular component at most once. However, it then states: is combinational. However, it looks like C is connected to two outputs of other devices - to A and B. How is this then still combinational? In general, I don't understand the point of why it would only need to be connected to exactly one output of another device. Apologies if this is the wrong StackExchange, wasn't sure where to ask this. A: C has two inputs. Each input of C is connected to exactly one output of another device. Connecting two outputs together usually results in smoke, or the mathematical equivalent, when they compete.
{ "pile_set_name": "StackExchange" }
Q: AngularJS: prepend "http://" to ng-model I have an input for url. I would like to automatically prepend "http://" to the user value, if it does not already exist. I would like to avoid using $watch because there are about 30 such inputs in a single controller... How should I approach this? A: I would say with a classic regex on the blur event you should be fine: <div ng-blur="check(thismodel)"></div> # $scope.check = function($url){ if (!/^(?:(ftp|http|https)?:\/\/)?(?:[\w-]+\.)+([a-z]|[A-Z]|[0-9]){2,6}$/gi.test($url)) { $url = "http://" + $url; } }
{ "pile_set_name": "StackExchange" }
Q: Adding foreign key field to a javabean Consider this regular javabean without ORM/: // primary key is auto incremented by the database, so I can't add it public class User { String name; int personID; // foreign key // no args constructor // getter/setters for fields } Is it ok to do this? I personally think it doesn't make sense because there is no reason to manipulate the foreign key through the bean, but I might be wrong. Are there use cases where this is good? A: I would normally do it like this. public class Person { private final String id; public Person(String id) { this.id = id; } public Person() { this.id = UUID.randomUUID().toString(); } } and public class User { private final String id; private String personId; public User(String id, String personId) { this.id = id; this.personId = personId; } public User() { this.id = UUID.randomUUID().toString(); } public String getPersonId() { return personId; } public void setPersonId(String personId) { this.personId = personId; } } Another alternative for User is to make it immutable. In which case it would look something like this. public class User { private final String id; private final String personId; public User(String id, String personId) { this.id = id; this.personId = personId; } public User(String personId) { this.personId = personId; this.id = UUID.randomUUID().toString(); } public String getPersonId() { return personId; } } Now the classes can be used in an autoincremented or non-autoincremented way. Basically the option is there for the classes to make their own unique ID or for a unique ID to be passed to it. One common dilemma that I have seen is when the id does not exist yet the object does. That is the case when the object is created in the program but the ID (which maybe created by the DB when it is inserted) is not assigned to it yet. In that case the bean may look like this. public class User { private String id; private final String personId; public User(String id, String personId) { this.id = id; this.personId = personId; } public User(String personId) { this.personId = personId; } public String getPersonId() { return personId; } public String getId() { return id; } public void setId(String id) { this.id = id; } } Notice the id is not final and hence the object can exist without the id present and can be added in later if needed
{ "pile_set_name": "StackExchange" }
Q: selecting the same data in different row from database i need to select the 'name' attributes must same value with 'seek' attribute. is kind like a match making concept which i need to select the 'name' attribute = 'seek' attribute in same table so the outcome will be name | seek HEADPHONE | KETTLE KETTLE | HEADPHONE anyone can give me the solution on how to do it. i currently doing my final year project. Thank you A: SELECT t1.NAME, t1.SEEK FROM yourTable t1 INNER JOIN yourTable t2 ON t1.NAME = t2.SEEK AND t1.SEEK = t2.NAME If you want to report only one record for each SEEK/NAME pair, then you can try: SELECT DISTINCT LEAST(t1.NAME, t1.SEEK), GREATEST(t1.NAME, t1.SEEK) FROM yourTable t1 INNER JOIN yourTable t2 ON t1.NAME = t2.SEEK AND t1.SEEK = t2.NAME
{ "pile_set_name": "StackExchange" }
Q: How do I know why my Azure instance doesn't start? I deployed my service package into Windows Azure. Management Portal has been showing "waiting for the role instance to start" for 30 minutes already so I assume something is wrong. I know that there's Azure Diagnostics, but is there some easier way to find what's going on in my instance - like some console displaying some detailed output or something? A: In these cases, it is probably the most expedient to simply RDP into the box and see what is going on. Event logs, hitting the site, etc., from inside the machine usually gives you a pretty good idea. If you have Intellitrace (Visual Studio Ultimate), you can also enable that and suck down the logs to see what is happening. That works very well also. A: @dunnry The problem is that you can't open a RDP session to the server if your Azure Role is not running, so you don't know anything what is going on. Most of the times there is something wrong in your Azure Configuration files. Try removing parts and redeploy afterwards. Pay triple attention to your ConnectionStrings. Make sure that the ServiceDefinition ConfigurationSettings are all defined in the ServiceConfiguration ConfigurationSettings File. What we basically do is to deploy on a nightly build basis. We can check our ChangeSets of the day before after an instance is not reaching the running state.
{ "pile_set_name": "StackExchange" }
Q: React function isn't behaving as its expected to Heres a function from my react app: handleSubmit(evt) { evt.preventDefault(); this.setState({ width: "", height: "", color: "" }); console.log(this.state) }; In my input, I set the value of input to the width, height and color. this handleSubmit function is happens when a form in filled. But I have set the state via setState before the console.log line. So this will replace the values from the form, before the console.log is called. I should get {width :" ", height :" ", color :" "} But instead, I get the value that was set by the input. But it seems like setState is only working when the full function is done, not before the log. Why? A: But it seems like setState is only working when the full function is done, not before the log. Why? setState doesn't change the state immediately. Ref: https://reactjs.org/docs/react-component.html#setstate If you want to do something right after the state change, use a callback function. handleSubmit(evt) { evt.preventDefault(); this.setState({ width: "", height: "", color: "" }, () => { console.log(this.state) }); };
{ "pile_set_name": "StackExchange" }
Q: How can I remove a bootstrap buttons hover effect? I've gotten an assignment to remove the hover effect of the following button: Visit http://www.appsbayou.se, search for the text "Kontaktinformation". Above it there's a button, "Skicka" which has an ugly black hover effect. This style comes from existing css. I'm using Chrome and even if I open up Devtools I can't nail down the style rule that does this effect. How can I remove this black hover color or at least change it to a color of my choosing? A: You will need to toggle the hover state inside the developer tools in order to view the CSS which is applied to the button on hover state. Adding this CSS to your stylesheet will fix the problem: input[type=submit]:hover { background-position: 0px; }
{ "pile_set_name": "StackExchange" }
Q: Hide `"ok glass"` menu when enable contextual voice commands Do you know if it is possible to hide "ok glass" bottom text when enable contextual voice commands? Thanks all! A: The same question is answered here : how to hide ok glass label from google glass voice menu For now in the XE 19.1, Contextual Voice Commands is not customizable, not even the overlay gray background.
{ "pile_set_name": "StackExchange" }
Q: Grabbing just the content of a line I have a simple question: I want to just grab the content of a line from a file x. My file x looks like this: PointXY [387.93852, 200.0] PointXY [200.0, 387.93852] PointXY [200.0, 387.93852] PointXY [200.0, 353.20889] PointXY [387.93852, 200.0] PointXY [200.0, 387.93852] PointXY [200.0, 300.0] My script in Python looks like this: h = open("x.gcode", "r") searchlines = h.readlines() file = "" for i, line in enumerate(searchlines): if "PointXY" in line: P = searchlines[i+1] print(P) I want P to just be [200.0, 100.0] (for instance). It now gives me '[200.0, 100.0]\n'. How can I adjust this in the line "P = searchlines[i+1]"? A: You are looking to strip the new line character from each line, which you can easily do using the available strip method of str: When you get your data in searchlines, do: searchlines[i+1].strip() To see that it is actually removed, check the repr: print(repr(P)) You can even do that repr print before and after applying the strip() to see what happened when calling that strip. Considering the structure of the text you have, you are looking to make it a list, so, you could use loads from json to do this: json.loads(searchlines[i+1].strip())
{ "pile_set_name": "StackExchange" }
Q: How to avoid duplication of code related to shared entities in the repository pattern? I'm building a repository for a large CRM schema that has a high number of relations between entities. Some of the entities are referenced by almost all entities, e.g. Person and Company. Where I have an aggregate root such as Order, that addresses Order Header, Order Lines etc. In the case where the Order is from a new Customer, I need to insert a Company and a Person record at the same time... so far so good. The difficulty is that this is the situation with very many other aggregate roots. I don't want to have a private method insertPerson(IPerson) in every single repository implementation. I have a Customer repository that already has public InsertCustomer(ICustomer) method, which persists a Company and a person record. But my reading indicates that repositories shouldn't depend on each other. If this is a case where it is okay for repositories to depend on each other, what is the best way to go about it? Should I inject the Customer Repository into the Order repository constuctor, pass it as a parameter to the methods that need it, or never commit this evil and duplicate the identical code in all repositories, in case those repositories need to specialise that code for their specific contexts? A: This sounds like an area that Service Layer might come in handy. You could inject the repositories in the service layer and that way each repo won't depend on the others, and the service can coordinate all of the inserts for a given operation across aggregates. Details of your implementation might also guide you depending on the extent to which you're relying on an ORM and need to take into account the atomicity of the repository operations. Without knowing more about that this advice may be less than useful.
{ "pile_set_name": "StackExchange" }
Q: Dynamic environment variable in .htaccess I'm struggling to figure out how to get environment variables to work using SetEnvIf based off my scenario, and was wondering if somebody can tell me how to do it, or give an example. My outcome is that I need the following redirect to fire based off the environment vars, I've got other cases that will also need to use this logic. I've got the below, so the redirect only happens on production <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{ENV:environment} production RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </IfModule> I was hoping that I could setup the following, however cannot figure it out. SetEnvIf environment ^(.*)$ environment=production #set it to production, if it is not already set? SetEnvIf Host ^staging. environment=staging SetEnvIf Host .dev$ environment=wamp Ideally my psudo code would be SetEnvIf environment is not set, set to production SetEnvElse host starts with staging, set to staging SetEnvElse host ends with dev, set to wamp Then in my PHP I've got <?php if( getenv('environment') ){ exit(getenv('environment')); } else { exit("environment not found"); } And my output is definitely environment not found I'm accessing owen.jekyll-test.dev Can anybody point me in the direction as to what I'm doing wrong? A: After many hours, I've finally got a working solution that allows a dynamic .htaccess based off environments For anybody who is interested in a similar setup, here is our configuration which automatically handles SSL, WWW Redirects, Apache Auth and Is_Admin flags. # ---------------------------------------------------------------------- # | Admin Vars | # ---------------------------------------------------------------------- SetEnvIf Remote_Addr ^43\.432\.136\.23 is_admin=1 # Virgin Media SetEnvIf Remote_Addr ^81\.43\.184\.70 is_admin=1 # BT SetEnvIf Remote_Addr ^164\.23\.234\.6 is_admin=1 # Orbtalk SetEnv office_ip 132.39.322.23 # ---------------------------------------------------------------------- # | Environment Detection | # ---------------------------------------------------------------------- SetEnvIf environment .+ env_defined=$0 SetEnvIf environment ^(.*)$ environment=production SetEnvIf Host ^staging. environment=staging SetEnvIf Host .dev$ environment=dev SetEnvIf env_defined .+ environment=$0 SetEnvIf prefix ^(.*)$ prefix=www. SetEnvIf Host ^www !prefix # ---------------------------------------------------------------------- # | Password Protection | # ---------------------------------------------------------------------- AuthType Basic AuthName "Protected Login" AuthUserFile /var/sites/website/.htpasswd Order deny,allow Deny from all Satisfy any SetEnvIf environment "dev" allow SetEnvIf environment "production" allow Allow from env=is_admin Allow from env=allow Allow from env=noauth Require valid-user Require user my_username # ---------------------------------------------------------------------- # | Forcing `https://` | # ---------------------------------------------------------------------- <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on [OR] RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' RewriteCond %{ENV:environment} production RewriteRule ^(.*)$ https://%{ENV:prefix}%{HTTP_HOST}/$1 [R=301,L] </IfModule> # ---------------------------------------------------------------------- # | Forcing the `www.` at the beginning of URLs | # ---------------------------------------------------------------------- # # NOTE: IF THE WEBSITE USES SSL, YOU'LL NEED TO MODIFY THE REWRITE URL LOCATION AND MODIFY THE CONDITION # <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on [OR] RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteCond %{ENV:environment} production RewriteRule ^ https://%{ENV:prefix}%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </IfModule>
{ "pile_set_name": "StackExchange" }
Q: Is a function that calls itself only once no matter the input recursive? Consider a function that does an operation and calls itself at most once (not more than one “recursion” level) no matter what the input is. Is this function considered recursive? Example: join1 :: [Maybe a] -> [a] join1 [Just x] = [x] join1 [Nothing] = [] join1 (x) = concat (map join1 (map (\k->[k]) x)) In this case, when calling: Join1 [nothing, just 2, just 3,...] The join1 function will be called on each element, entering immediately the termination condition A: Yes, it is recursive. The number of calls at runtime and the runtime recursion depth is irrelevant. A definition x = expression is said to be recursive if x appears in expression, referring to the x we are defining right now. Briefly put, "recursiveness" is a syntactic property of the definition, and does not consider the runtime behavior. As a silly example, this definition is recursive, even if it never calls itself at runtime. Even if it could trivially simplified into a non-recursive one. identity :: a -> a identity x = (\_ -> x) identity
{ "pile_set_name": "StackExchange" }
Q: Horizontal OptionGroup in a Table (Vaadin) I' tryind to add an OptionGroup to my table, but so far the table stays empty no matter what I do. Here is what I've tried so far: table = new Table(); table.setSizeFull(); table.addContainerProperty("Name", String.class, null); table.addContainerProperty("Option one", OptionGroup.class, null); table.addContainerProperty("Option two", OptionGroup.class, null); opt1 = new OptionGroup(""); opt1.addItem(); opt1.addItem(); opt1.setMultiSelect(false); table.addItem(new Object[] {"Name one", opt1.getItem(1),opt1.getItem(2)}, new Integer(1)); Am I missing something, or is it not so easy to solve this as shown in my example? A: Just a quick look, but it seem you are not adding any Option Group Options. Have you tried just addeding the Option class itself table = new Table(); table.addContainerProperty("Name", String.class, null); table.addContainerProperty("Option one", OptionGroup.class, null); opt1 = new OptionGroup("Time"); opt1.addItem("AM"); opt1.addItem("PM"); table.addItem(new Object[] {"Name one", opt1}, new Integer(1)); I would also remove the setSizeFull() Also the null, will be the default value if something goes wrong. once you have that working, you can use CSS to arrange the options Horizontally.
{ "pile_set_name": "StackExchange" }
Q: Which surfaces admit hyperbolic metrics bounded by geodesic arcs? Consider a compact oriented surface of genus $g$ with $k$ boundary components, ordered from $1$ to $k$. Next remove $n_i\geq 0$ points from the $i$-th boundary component, for $i=1,...,k.$ For which sequences $(g,n_1,...,n_k)$, the above surface admits a hyperbolic metric whose $i$-th component is bounded by $n_i$ infinite geodesic arcs (going to $n_i$ points at infinity)? $n_i=0$ means that the $i$-th component is a geodesic loop (or, alternatively, a puncture). The answer is yes for all $n_i\geq 3$ but I am not sure about other cases. A: There is indeed a pretty simple way to derive necessary and sufficient conditions on $(g,n_1,...,n_k)$ for existence of such a hyperbolic structure on your surface $S$. To derive a necessary condition, let $S$ be your surface equipped with such a hyperbolic structure. Let $DS$ be obtained by doubling $S$ across the boundary, in other words $DS$ is the quotient of a pair of copies of $S$ by identifying the two copies of the boundary using the identity map. The surface $DS$ is a surface of some finite genus $g'$ and some finite number of punctures $p'$, and one can work out formulas for $g'$ and $p'$ in terms of $(g,n_1,...,n_k)$ (I'll indicate more details below of how one does this). Furthermore, by doubling the hyperbolic structure on $S$ one sees that $DS$ possesses a hyperbolic structure, i.e. a complete hyperbolic metric. Just as for compact surfaces, existence of a complete hyperbolic metric on a punctured surface such as $DS$ is equivalent to saying that $DS$ has negative Euler characteristic: $$\chi(S) = 2 - 2g' - p' < 0 $$ It turns out that this necessary condition is also sufficient, because for any complete hyperbolic structure on $DS$, under the embedding $S \hookrightarrow DS$ one can straighten the boundary of $S$ to get the desired hyperbolic structure on $S$. The number of punctures on $DS$ is simply $$p' = \sum_{i=1}^k n_i $$ because there is exactly one puncture on $DS$ for each boundary point that was removed to form $S$. To compute genus, its easier to work with Euler characteristic, and we have $$\chi(S) = 2 - 2g - k - \sum_{i=1}^k n_i $$ The disjoint union of two copies of $S$ has twice the Euler characteristic: $$\chi(S \cup S') = 4 - 4g - 2k - 2 \sum_{i=1}^k n_i $$ Identifying two circle components of the boundaries does not change Euler characteristic, but identifying two arc components reduces the Euler characteristic by $1$: $$\chi(DS) = 4 - 4g - 2k - 3 \sum_{i=1}^k n_i + \#\{i \mid n_i=0\} $$ Since $\chi(DS) = 2 - 2g' - p'$, and since we have a formula for $p'$, we can solve for $g'$.
{ "pile_set_name": "StackExchange" }
Q: How to paginate array My code : <?php $array = json_decode('{ "friends": { "data": [ { "id": "1000002470615", "gender": "female" }, { "id": "1000005198891", "gender": "female" }, { "id": "1000007859390", "gender": "female" }, { "id": "1000008308250", "gender": "female" }, { "id": "1000009416380", "gender": "male" }, { "id": "1000010894609", "gender": "female" }, { "id": "1000010991284", "gender": "male" }, { "id": "1000011095914", "gender": "female" }, { "id": "1000014648465", "gender": "female" }, { "id": "1000017041889", "gender": "female" }, { "id": "1000017519651", "gender": "female" }, { "id": "1000019029610", "gender": "female" }, { "id": "1000019497511", "gender": "female" }, { "id": "1000019681751", "gender": "female" }, { "id": "1000020582845", "gender": "male" }, { "id": "1000021389766", "gender": "male" }, { "id": "1000022247272", "gender": "female" }, { "id": "1000025425217", "gender": "female" }, { "id": "1000026359294", "gender": "female" }, { "id": "1000031258301", "gender": "male" }, { "id": "1000031499108", "gender": "female" }, { "id": "1000032349067", "gender": "male" }, { "id": "1000032428345", "gender": "female" }, { "id": "1000033101313", "gender": "male" }, { "id": "1000033288824", "gender": "female" }, { "id": "1000033525527", "gender": "female" }, { "id": "1000034062687", "gender": "male" }, { "id": "1000035232214", "gender": "female" }, { "id": "1000035804034", "gender": "female" }, { "id": "1000040066742", "gender": "male" }, { "id": "1000041457943", "gender": "female" }, { "id": "1000042302703", "gender": "female" }, { "id": "1000043758095", "gender": "female" }, { "id": "1000045378342", "gender": "male" }, { "id": "1000048531666", "gender": "female" }, { "id": "1000049731704", "gender": "female" }, { "id": "1000050719295", "gender": "female" }, { "id": "1000050736082", "gender": "male" }, { "id": "1000051733891", "gender": "female" }, { "id": "1000052976810", "gender": "male" }, { "id": "1000053432719", "gender": "male" }, { "id": "1000054595524", "gender": "male" }, { "id": "1000055567339", "gender": "female" }, { "id": "1000056180174", "gender": "female" }, { "id": "1000056737207", "gender": "male" }, { "id": "1000058322123", "gender": "male" }, { "id": "1000058592478", "gender": "female" }, { "id": "1000059646724", "gender": "male" }, { "id": "1000062848532", "gender": "female" }, { "id": "1000062994936", "gender": "female" }, { "id": "1000066441440", "gender": "male" } ] } }', true); foreach($array['friends']['data'] as $details) { echo $details['id'], '<br />'; } ?> result: 1000002470615 1000005198891 1000007859390 1000008308250 1000009416380 1000010894609 1000010991284 1000011095914 1000014648465 1000017041889 1000017519651 1000019029610 1000019497511 ... How to define my paginate as in the example below? 1000002470615 1000005198891 1000007859390 1000008308250 1000009416380 <--Previous Next--> What should you use to make this possible. Sorry for my English expression. A: I would do it like this : $items = 5; // 5 items per page $page = $_GET['page']; // current page $array = json_decode('...', true); $friends = $array['friends']['data']; $pages = ceil(count($friends) / $items); // number of pages (total) $page = $page < 1 ? 1 : $page; // if page is inferior to 1 make it 1 $page = $page > $pages ? $pages : $page; // if is superior to total make it total $current = array_slice(array_slice($friends, $page-1), 0, $items); // show friends for current page foreach($current as $friend) { echo $friend['id'] . '<br />'; } // pagination for($i = 1; $i <= $pages; $i++) { $class = $i == $page ? ' class="active"' : ''; echo '<a' . $class . ' href="url?page=' . $i . '">' . $i . '</a>'; }
{ "pile_set_name": "StackExchange" }
Q: Where are the Rust (aka rust-lang) packages for Ubuntu? I'd like to play with the Rust language on Ubuntu, but there don't seem to be any packages. Did I miss it or is there some problem? A: On ubuntu 16.04 you can use official apt package without install any other ppa repository. sudo apt install rustc ... and don't forget cargo sudo apt install cargo ... but the versions are not really updated: (August 2016) rustc 1.7.0 and cargo 0.8.0. Unfortunally cargo is not compatible with IDEA rust plugin... I used the script pointed in Rust Documentation. A: Jonathon Fernyhough has a PPA (personal package archive) where he provides unofficial nightly and versioned builds of rust, but it does require libstdc++ 6.x (Xenial uses 5.4.0). With Yakkety you can install Rust 1.10 from the universe repository, and 1.13 with Zesty. Rust can be installed from this PPA by running the following, as well as llvm which is now needed: sudo add-apt-repository ppa:jonathonf/rustlang (accept to add llvm) sudo apt-get update sudo apt-get install rustc Alternatively different backport ppas like rustlang-1.13 or rustlang-test can be substituted instead of rustlang to get a the latest unstable code or a particular version. A: This answer is old I see there is a Debian prospective package bug 689207 still open. There are initial packages but it's not ready to be in the distribution. There is also a Debian wiki page about the packaging effort. It alludes to the fact that Rust's compiler is written in Rust so the bootstrapping process is strange, so perhaps that's why it's not packaged yet. There are some issues in upstream Rust that make it hard to package. Bootstrapping is apparently not a catastrophic problem as packagers can start from a binary snapshot. Updated May 2016: Happily, rustc is now in Debian testing, so should be in Ubuntu within a year or so.
{ "pile_set_name": "StackExchange" }
Q: How to calculate the time interval between two time strings I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved. Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences. For the averaging, should I convert to seconds and then average? A: Yes, definitely datetime is what you need here. Specifically, the strptime function, which parses a string into a time object. from datetime import datetime s1 = '10:33:26' s2 = '11:15:49' # for example FMT = '%H:%M:%S' tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT) That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime. This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code: if tdelta.days < 0: tdelta = timedelta(days=0, seconds=tdelta.seconds, microseconds=tdelta.microseconds) (of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case. A: Try this -- it's efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting. import time start = time.time() time.sleep(10) # or do something more productive done = time.time() elapsed = done - start print(elapsed) The time difference is returned as the number of elapsed seconds. A: Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration): #!/usr/bin/env python from datetime import datetime, time as datetime_time, timedelta def time_diff(start, end): if isinstance(start, datetime_time): # convert to datetime assert isinstance(end, datetime_time) start, end = [datetime.combine(datetime.min, t) for t in [start, end]] if start <= end: # e.g., 10:33:26-11:15:49 return end - start else: # end < start e.g., 23:55:00-00:25:00 end += timedelta(1) # +day assert end > start return end - start for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']: s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')] print(time_diff(s, e)) assert time_diff(s, e) == time_diff(s.time(), e.time()) Output 0:42:23 0:30:00 time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.: #!/usr/bin/env python from datetime import timedelta def mean(data, start=timedelta(0)): """Find arithmetic average.""" return sum(data, start) / len(data) data = [timedelta(minutes=42, seconds=23), # 0:42:23 timedelta(minutes=30)] # 0:30:00 print(repr(mean(data))) # -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.
{ "pile_set_name": "StackExchange" }
Q: java how to pass a List for generic element in it I want to create a Util to handle any possible type in a List, so I write this code: class Util{ static class Data<T>{ String message; T raw; boolean report; Data(String m, T d, boolean b){ message=m; raw=d; report=b;} } interface Callback{ public void report(int idx); } static void handleList(List<Data> list, Callback cb){ for(int i=0; i<list.size(); i++) if(list.get(i).report) cb.report(i); } public static void main(String[] args){ List<Data<Float>> list = new ArrayList<Data<Float>>(); list.add(new Data<Float>("iPhone", 3000f, false)); list.add(new Data<Float>("iPad", 999.5f, true)); handleList(list, new Callback(){ @Override public void report(int idx){ Data<Float> data = list.get(idx); System.out.println(data.message+": "+list.get(idx).raw); } }); } } I cannot compile the code until I modify the method handleList with the parameter type List<Data<Float>>, but that is NOT my purpose, because I want to reuse the handleList for any type of Data in the List. What should I do? A: Simply use a parameterized type for the method for Data to be bound by. <T> handleList(List<Data<T>> list, Callback cb){ //code } A: You are almost there. Just make handleList generic: static <L> void handleList(List<Data<L>> list, Callback cb) { ...
{ "pile_set_name": "StackExchange" }
Q: Xamarin Forms Microcharts generating "OutOfMemoryError" I am trying to use a Microcharts graph in my application, which is using Xamarin.Forms (targeting Android, iOS and UWP). I have tried following several tutorials to get a chart to display but each time it results in the error: Unhandled Exception: Java.Lang.OutOfMemoryError: Failed to allocate a 240048012 byte allocation with 5713730 free bytes and 87MB until OOM If I make a new Xamarin.Forms project, this error doesn't occur and it runs absolutely fine (I am running on the same Android device, a Samsung SM-J320FN). Here is the simplified XAML code: <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Foo.DetailPage" xmlns:forms="clr-namespace:Microcharts.Forms;assembly=Microcharts.Forms"> <ContentPage.Content> <StackLayout Grid.Row="2"> <forms:ChartView x:Name="priceChart" HeightRequest="150"/> </StackLayout> Here is the Code Behind: //Temp data for charts List<Entry> entries = new List<Entry> { new Entry(200) { Color=SKColor.Parse("#FF1943"), Label ="January", ValueLabel = "200" }, new Entry(400) { Color = SKColor.Parse("00BFFF"), Label = "March", ValueLabel = "400" }, new Entry(-100) { Color = SKColor.Parse("#00CED1"), Label = "Octobar", ValueLabel = "-100" }, }; public DetailPage(string Code) { ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.FromHex("27b286"); InitializeComponent(); priceChart.Chart = new LineChart() { Entries = entries, BackgroundColor = SKColor.Parse("#00FFFFFF") }; } Without this chart, the page can run absolutely fine, even when the list is generated and the chart is included in XAML, it seems to be when initialising the chart through the code behind that causes the issue. A: I added <application android:hardwareAccelerated="true" android:largeHeap="true"></application> to my AndroidManifest.xml and this works fine, however I still don't know what was causing so much memory to be used.
{ "pile_set_name": "StackExchange" }
Q: Insert entry in WinEdt 8.1 How can I create a Insert menu entry for a new environment I created. For example, one can insert a figure by going to Insert > Objects > Figure. Of course, custom environments can be gotten by going to Insert > Environments > New Environment but I would like one that I can activate via a shortcut like CTRL+ALT+E or the like and even from the menu tab Insert. The result should look like the following: A: You can use this WinEdt macro, which inserts what you want on a new line in WinEdt: BeginGroup; InsLine; NewLine; Mark(1); Ins("\begin{example}{}%"); InsLine; Indent; InsertBullet; InsLine; Ins("\begin{solution}%"); InsLine; Indent; InsertBullet; InsLine; Unindent; Ins("\end{solution}%"); InsLine; Unindent; Ins("\end{example}"); Goto(1); NextBullet; EndGroup; Save it as example.edt in, say, %b\Local\Macros\. Then add to %b\ConfigEx\MainMenu.ini (you can edit it from the Options Interface), the following lines just between line 1332 (ITEM="-") and line 1333 (SUBMENU="Font>"): SUBMENU="Personal>" CAPTION="&Personal" CONFIG_FILTER="Default;MiKTeX;TeX Live;HTML" REQ_DOCUMENT=1 ITEM="Example" CAPTION="&Example" MACRO="Exe('%b\Local\Macros\example.edt');" REQ_DOCUMENT=1 END="Personal>" ITEM="-" Final step: save the new MainMenu.ini on clicking on the leftmost icon in the Options Interface, so that the modifications be written in WinEdt.dnt. You'll then have access to the macro example.edt either from the Insert -> Personal submenu, or with the Alt+I+P+E shortcut. Let me know if it doesn't work fine: it might depend on personal configurations, though I don't think so.
{ "pile_set_name": "StackExchange" }
Q: Is there any trigger to know if an attachment from an item in a list is downloaded? So I'm planning to make a sharepoint list system (with microsoft flow). There's this case, if someone downloaded an attachment from an item, there's this status column that'll change text to "File downloaded". Is there any way in microsoft flow or sharepoint itself to know if an attachment from an item in a list is downloaded by a user (who's permission is read only)? Or is there any way to know that information? Thank you. A: Through auditing, SharePoint can track file downloads. But auditing is a report rather than a real time trigger. I'm not sure you can catch the event in real time, if that's necessary?! Check out Logging people who download files in SharePoint.
{ "pile_set_name": "StackExchange" }
Q: Equal Comparisons Order of Sentence Troubles I am currently learning comparisons in which each item being compared is equal. When using a sentence with tan/tanto/a/os/as, I am having trouble knowing the correct order of each sentence: A text book section asks a question and wants the answer to be no. ?Tiene la Plaza San Martín más estatuas que la Plaza San Bolívar? Would the correct answer be: No, la Plaza San Martín tiene tantas estatuas como la Plaza San Bolívar. or No, tiene tantas estatuas la Plaza San Martín como la Plaza San Bolívar Another Question: Hay más tiendas en la calle Luna que en la calle Londres? Would the correct answer be: No, hay tantas tiendas en la calle Luna como en la calle Londres. I am trying to learn the sentence structure of these sentences and why it would be that way. A: Gramaticalmente son todas las respuestas validas pero te recomendaría que te quedes con: (suenan mejor para alguien de habla hispana) No, la Plaza San Martín tiene tantas estatuas como la Plaza San Bolívar. y No, en la calle Luna hay tantas tiendas como en la calle Londres.
{ "pile_set_name": "StackExchange" }
Q: Which converges faster, mean or median? If I draw i.i.d. variables from N(0,1), will the mean or the median converge faster? How much faster? To be more specific, let $x_1, x_2, \ldots $ be a sequence of i.i.d. variables drawn from N(0,1). Define $\bar{x}_n = \frac{1}{n}\sum_{i=1}^n x_i$, and $\tilde{x}_n$ to be the median of $\{x_1, x_2, \ldots x_n\}$. Which converges to 0 faster, $\{\bar{x}_n\}$ or $\{\tilde{x}_n\}$? For concreteness on what it means to converge faster: does $\lim_{n \to \infty} Var(\bar{X}_n)/Var(\tilde{X}_n)$ exist? If so, what is it? A: The mean and median are the same, in this particular case. It is known that the median is 64% efficient as the mean, so the mean is faster to converge. I can write more details but wikipedia deals with your question exactly.
{ "pile_set_name": "StackExchange" }
Q: Is there a simpler, more abstract proof of the Cayley-Hamilton theorem for matrices? The Cayley-Hamilton theorem is equivalent to: Let $R$ be a ring and let $M_n(R)$ be $n\times n$ matrices over $R$. Then the minimal polynomial of $A \in M_n(R)$ over $R$ divides the characteristic polynomial of $A$. For instance. In order to reduce the confusion of having $X = $ a matrix in a polynomial. Let $R'$ be the subring of matrices $\{ a I : a \in R\}$. It's clearly isomorphic to $R$. Now consider the characteristic polynomial as an element of $R'[X]$. A: This has no pretense to be "The" answer! I am no algebraist but I remember a nice proof I was taught when I was I student, I thought I'd share it. In a nutshell: True for diagonalizable matrices, then use "algebraic continuation". Let's write down some details. Lemma ("algebraic continuation"): Let $k$ be an infinite field. Let $P, Q \in k[X_1, \dots, X_n]$ be polynomials of $n$ variables with $Q \neq 0$ . If $P$ vanishes on the set $\{x \in k^n ~\colon~ Q(x) \neq 0\}$, then $P = 0$. This lemma expresses that "non-empty open sets are dense in the Zariski topology". It's not hard to show (I'll give you a hint if you want). Now: Theorem (Cayley-Hamilton): Let $R$ be a commutative unital ring. Let $A \in M_n(R)$ be a square matrix and denote by $\chi_A(X) \in R[X]$ its characteristic polynomial. Then $\chi_A(A)$ is the zero matrix. Let's give a proof when $R = k$ is an infinite field for the moment. By the "algebraic continuation" lemma, it is enough to show that the theorem is true when $A$ lies in some "dense open set". More precisely, each coefficient of the matrix $\chi_A(A)$ is a polynomial in the $n^2$ coefficients of $A$. It is enough to show that it vanishes on some set $\{Q \neq 0\}$, where $Q$ is a nonzero polynomial in $n^2$ variables. Let's take $Q(A) = \mathrm{Disc}(\chi_A)$ (the discriminant of the polynomial $\chi_A$). The set where $Q \neq 0$ consists precisely of matrices $A$ whose eigenvalues are all distinct in an algebraic closure $\bar{k}$ of $k$. Such matrices are diagonalizable over $\bar{k}$ so it is easy to check that $\chi_A(A)$ = 0 (I'll let you do that). We're done! Wait, how does this extend to an arbitrary unital ring? Well, each of the coefficients of the matrix $\chi_A(A)$ is actually a polynomial in the $n^2$ coefficients of $M$ with integer coefficients. These polynomials must be zero because we showed that Cayley-Hamilton holds for $\mathbb{Q}$ hence $\mathbb{Z}$. (NB: I think some people would say something like "$\mathbb{Z}$ is an initial object in the category of unital rings" or whatever). A: Here is one proof. I'll share the intuition behind it first: Intuition in a Nutshell: For any endomorphism $\Phi$, we have a factorization of the determinant $\text{det}(\Phi)$ into the adjugate and the matrix itself: $$ \text{det}(\Phi) = \text{adj}(\Phi) \Phi$$ We want to use this to get a factorization of the characteristic polynomial $p(t)$ of $\phi$ into some polynomial analogous to the adjugate and a linear term $t - \phi $: $$p(t) = f(t)(t - \phi)$$ These two factorizations are analogous, and in fact, if we get the formality right, we can view these as corresponding factorizations in isomorphic rings. Let's try to work this out a little more formally. The main question is, what are the two isomorphic rings I mentioned in which these are corresponding factorizations? Let $V$ be a finite dimensional vector space over a field $k$. One of the rings is $\text{End}_k(V)[t]$. The characteristic polynomial $p(t)$ of $\phi \in \text{End}_k (V)$ naturally lives in $\text{End}_k(V)[t]$. To see this, we view $t \text{Id}_V - \phi $ as having endomorphisms as coefficients, and then take the determinant, which is then in $\text{End}_k (V)[t]$. The other ring is $\text{End}_{k[t]}(V \otimes_k k[t])$. $\Phi := 1 \otimes t - \phi \otimes 1 $ is an element in this ring, and we have a factorization $\text{det}(\Phi) 1_{V \otimes_k k[t]} = \text{adj}(\Phi) \Phi$. In the isomorphism $$\text{End}_k ( V \otimes_k k[t]) \cong \text{End}_k (V)[t]$$ We have corresponding elements $$\Phi \leftrightarrow t - \phi$$ and $$\text{det}(\Phi) \leftrightarrow p(t)$$ Therefore, the factorization $\text{det}(\Phi) 1_{V \otimes_k k[t]} = \text{adj}(\Phi) \Phi$ corresponds to a factorization $p(t) = f(t)(t-\phi)$ in $\text{End}_k (V) [t]$. And that's the whole idea! If you want a more formal version, and a construction of the claimed isomorphism, read on! Theorem: Let $V$ be a finitely generated $k$-module. If $\phi : V \rightarrow V$ is a $k$-linear map, then the evaluation homomorphism $\text{ev}_{\phi} : k[t] \rightarrow \text{End}_k (V)$ sends the characteristic polynomial $\text{char}(\phi)$ to $0$. Let's start by constructing an isomorphism $F : \text{End}_{k} (V)[t] \rightarrow \text{End}_{k[t]} (V \otimes_k k[t])$ as follows. We have isomorphisms $$\text{End}_{k[t]} (V \otimes_k k[t]) \cong \text{Hom}_k (V, \text{Hom}_{k[t]}(k[t], V \otimes_k k[t])) \cong \text{Hom}_k(V, V \otimes_k k[t])$$ These isomorphisms can be established by creating canonical maps in both directions and showing that they are inverse to each other. Now we have a canonical map in a single direction, $$\text{End}_k (V) \otimes_k k[t] \rightarrow \text{Hom}_k(V, V \otimes_k k[t])$$ sending $\phi \otimes t^n$ to the map sending $v$ to $\phi(v)t^n$. This is injective, and surjective since $V$ is finitely generated. Composing these isomorphisms gives an isomorphism $F : \text{End}_{k} (V)[t] \rightarrow \text{End}_{k[t]} (V \otimes_k k[t])$. Now we argue as before. View $t - \phi$ as a $k[t]$-linear endomorphism of $V \otimes_k k[t]$. Under the isomorphism $F$, $\text{char}(\phi)$ maps to $\text{det} (t - \phi) 1_{V \otimes_k k[t]} )$ and $F ( t - \phi ) = t - \phi$. $t - \phi$ divides $\text{det}(t - \phi) 1_{V \otimes_k k[t]}$ in $\text{End}_{k[t]} (V \otimes_k k[t])$, since $\text{det} (t - \phi) 1_{V \otimes_k k[t]} = \text{adj}(t - \phi) (t - \phi)$, where $\text{adj}(t - \phi)$ is the adjugate matrix. Therefore, $t - \phi$ divides $\text{char}(\phi)$ in $\text{End}_{k}(V)[t]$. So $\text{char}(\phi)$ has $\phi$ as a root in $\text{End}_k(V)$, so that the evaluation homomorphism $\text{ev}_{\phi} : k[t] \rightarrow \text{End}_k (V)$ sends the characteristic polynomial $\text{char}(\phi)$ to $0$.
{ "pile_set_name": "StackExchange" }
Q: Searching by views Searching is hard to completely understand using SharePoint 2013. Is there a way to restrict search results to come from a certain view in document library? It is possible to build a query? I am thinking that I can restrict by Tag to make this happen, but I am not sure. Is it possible to produce search results from a certain view? A: Yes, you can. Try adding a search results webpart to you page, and edit the properties. Then click on "change query". You can specify a tag there. If you use SharePoint 2013 Enterprise you can also you the CSWP. Also you can do much more via the advanced view (Switch to Advanced Mode):
{ "pile_set_name": "StackExchange" }