pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
16,775,346 | 0 | <p>This will work:</p> <pre><code>var re = /^FIXED(?:-[a-zA-Z0-9]{4}){3}$/; </code></pre> <p>You could as well use the charactergroup <code>\w</code> which usually is pretty much equivalent to <code>[a-zA-Z0-9]</code> but that might contain several characters (ASCII <> UTF) you might not want to have.</p> |
27,465,985 | 0 | Accessing Output From C# Code <p>I am running this code in C# in VS2013 which I got from here: <a href="http://tda.codeplex.com/" rel="nofollow">http://tda.codeplex.com/</a>. The code is supposed to gather data from my TD Ameritrade 401k account. The code is running fine but where is the outputted data from the code below being saved at? How do I access it? </p> <pre><code>namespace TDAmeritrade.Samples { using System; using TDAmeritrade; class Program { static void Main() { // Initialize TD Ameritrade client, provide additional config info if needed var client = new TDAClient(); // Log in to the TD Ameritrade website with your user ID and password client.LogIn("jessicasusername", "jessicaspassword"); // Now 'client.User' property contains all the information about currently logged in user var accountName = client.User.Account.DisplayName; // Get stock quotes snapshot. var quotes = client.GetQuotes("GOOG, AAPL, $SPX.X, DUMMY"); // 'quotes.Error' contains a list of symbols which have not been found var errors = quotes.Errors; // Find symbols matching the search string var symbols = client.FindSymbols("GOO"); // Get historical prices var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1)); } } } </code></pre> <p><strong>Update: Placed this code below</strong>:</p> <pre><code>PM> Install-Package Newtonsoft.Json // Change the file path to wherever you wish to save the results const string SaveFileToLocation = @"C:\Users\jessica\Desktop\json_data"; string json = JsonConvert.SerializeObject(prices, Formatting.Indented); using (StreamWriter writer = new StreamWriter(SaveFileToLocation)) { writer.Write(json); } </code></pre> |
30,647,476 | 0 | Extracting specific registry key from REG QUERY based on search string <p>I am trying to extract the key value of a registry entry. I only want the key which I have been trying to concatenate using FOR /F, however had no luck.</p> <p><strong>Eg: the command</strong></p> <p>REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall /s /f chrome</p> <p><strong>returns</strong></p> <p>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{157F97DF-A001-36FB-A90C-55949FA130CA} DisplayName REG_SZ Google Chrome</p> <p>End of search: 1 match(es) found.</p> <hr> <p>All that I want from this result is <strong>157F97DF-A001-36FB-A90C-55949FA130CA</strong></p> <p>How can I do this using FOR /F or other similar methods?</p> <p>Many thanks!!</p> |
34,001,277 | 0 | pip install in Cygwin cannot find file error <p>I am on a Mac OS El Capitan, running a Windows 10 64-bit VM inside Parallels. I have Cygwin installed and Anaconda3. I would like to install two packages (pyrsistent and rpy2) using pip. Both of them throw an error "error: [WinError 2] The system cannot find the file specified" without specifying the file it can't find.</p> <p>Here's the output:</p> <pre><code>$ pip install pyrsistent Collecting pyrsistent Using cached pyrsistent-0.11.9.tar.gz Requirement already satisfied (use --upgrade to upgrade): six in c:\anaconda3\lib\site-packages (from pyrsistent) Building wheels for collected packages: pyrsistent Running setup.py bdist_wheel for pyrsistent Complete output from command C:\Anaconda3\python.exe -c "import setuptools;__file__='C:\\cygwin64\\tmp\\pip-build-sqcinj9m\\pyrsistent\\setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\cygwin64\tmp\tmpn25raothpip-wheel-: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.5 copying _pyrsistent_version.py -> build\lib.win-amd64-3.5 creating build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_checked_types.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_field_common.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_helpers.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_immutable.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pbag.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pclass.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pdeque.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_plist.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pmap.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_precord.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pset.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pvector.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_transformations.py -> build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\__init__.py -> build\lib.win-amd64-3.5\pyrsistent running build_ext building 'pvectorc' extension error: [WinError 2] The system cannot find the file specified ---------------------------------------- Failed building wheel for pyrsistent Failed to build pyrsistent Installing collected packages: pyrsistent Running setup.py install for pyrsistent Complete output from command C:\Anaconda3\python.exe -c "import setuptools, tokenize;__file__='C:\\cygwin64\\tmp\\pip-build-sqcinj9m\\pyrsistent\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\cygwin64\tmp\pip-_wbdiief-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py running build_ext building 'pvectorc' extension error: [WinError 2] The system cannot find the file specified ---------------------------------------- Command "C:\Anaconda3\python.exe -c "import setuptools, tokenize;__file__='C:\\cygwin64\\tmp\\pip-build-sqcinj9m\\pyrsistent\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\cygwin64\tmp\pip-_wbdiief-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\cygwin64\tmp\pip-build-sqcinj9m\pyrsistent </code></pre> <p>Both python3 and pip are in the path:</p> <pre><code>$ which pip /cygdrive/c/Anaconda3/Scripts/pip $ which python /cygdrive/c/Anaconda3/python </code></pre> <p>The error is identical when trying to install rpy2 so it's not something particular to the package I'm trying to install. Does anyone have ideas of the problem or ideas for troubleshooting? I've tried debugging into the install.py but the code throwing the error is in C. I've tried doing the install in verbose mode, but it still doesn't say what file it cannot find in that case. (and if you're wondering why I haven't used conda, it's because it doesn't install pyrsistent, and for the rpy2 install, it insists on linking it to its own install of R, and even when specifying my own install, something doesn't link correctly. I've already been down that road and would like to stick to pip).</p> |
40,115,021 | 0 | <p>I followed the <a href="http://support.sas.com/kb/53/105.html" rel="nofollow">support link</a> you provided, which states the following:</p> <blockquote> <p>With SAS® 9.3, the following message occurs in your SAS log when you use aliases for the value of SMTP MAIL FROM:email address and your SMTP server does not support aliases.</p> </blockquote> <p>The code above does not appear to contain a value for the FROM email address. Try configuring the following <a href="http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002135033.htm" rel="nofollow">option</a> at the start of your process:</p> <pre><code>options emailid="[email protected]"; /* adjust as appropriate */ </code></pre> <p>Alternatively, try adding it to your filename as follows:</p> <pre><code>filename mymail email to=("&[email protected]") from="[email protected]" TYPE = "TEXT/PLAIN" SUBJECT = "Report Status"; </code></pre> |
23,093,858 | 0 | <ul> <li><p>You could expose an event on your mediator so it notifies all listeners (eg your second VM) that its values have changed. .NET has a standard way of doing this: you could implement the <code>INotifyPropertyChanged</code><br> interface:<br> <a href="http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged" rel="nofollow">http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged</a> </p> <p>An example/tutorial: <a href="http://www.dreamincode.net/forums/topic/208833-using-the-inotifypropertychanged-functionality/" rel="nofollow">http://www.dreamincode.net/forums/topic/208833-using-the-inotifypropertychanged-functionality/</a></p></li> <li><p>The easiest way would be to use a messenger implementation, please<br> read this answer: <a href="http://stackoverflow.com/a/16149579/690178">http://stackoverflow.com/a/16149579/690178</a></p></li> </ul> |
17,452,084 | 0 | <p>Very good question.</p> <p><strong>Event handlers are executed in order of initialization.</strong></p> <p>I haven't really thought about this before, because my handlers never needed to know which one run first, but by the look of you fiddle I can see that the handlers are called in the same order in which they are initialized.</p> <p>In you fiddle you have a controller <code>controllerA</code> which depends on two services, <code>ServiceA</code> and <code>ServiceB</code>:</p> <pre class="lang-js prettyprint-override"><code>myModule .controller('ControllerA', [ '$scope', '$rootScope', 'ServiceA', 'ServiceB', function($scope, $rootScope, ServiceA, ServiceB) {...} ] ); </code></pre> <p>Both services and the controller define an event listener.</p> <p>Now, all dependencies need to be resolved before being injected, which means that both services will be initialized before being injected into the controller. Thus, handlers defined in the services will be called first, because service factories are initialized before controller.</p> <p>Then, you may also observe that the services are initialized in order they are injected. So <code>ServiceA</code> is initialized before <code>ServiceB</code> because they are injected in that order into the controller. If you changed their order inside the controller signature you'll see that their initilization order is also changed (<code>ServiceB</code> comes before <code>ServiceA</code>).</p> <p>So, after the services are initialized, the controller gets initialized as well, and with it, the event handler defined within.</p> <p>So, the end result is, on $broadcast, the handlers will be executed in this order: <code>ServiceA</code> handler, <code>ServiceB</code> handler, <code>ControllerA</code> handler.</p> |
29,145,198 | 0 | Error while implementing XSSF example <p>I want to read large Excel files (.xlsx) with java. Apache has an example how to go this <a href="http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api" rel="nofollow">here</a>. So I just copied the whole class, added the path to my .xlsx file and tried to execute it but I get this error:</p> <pre><code>Error:(96, 69) java: cannot access org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst class file for org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst not found </code></pre> <p>This error is triggered in this line in the method <code>endElement()</code>:</p> <pre><code>lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); </code></pre> <p>I use this dependency for maven:</p> <pre><code><dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> </code></pre> <p>How do I fix this error?</p> |
7,856,401 | 0 | TTLauncherView move item to other page <p>I have a TTLauncherView in my ios app. I have allowed users to edit and move their items around, however it does not appear that you can move the item from one screen to another, does anyone know how to do this?</p> |
7,368,750 | 0 | How to set the cursor position at the end of a string in a text field using jQuery? <p>I am using jQuery 1.6 and I have a text field for which I would like the cursor to be positioned at the end of the string\text after the field receives focus. Is there a trivial or easy to do this?</p> <p>At this time I am using the following code:</p> <pre><code>$jQ('#css_id_value').focus(function(){ this.select(); }); $jQ('css_id_value').focus(); </code></pre> |
40,261,458 | 0 | <p>Can u try to rename the file to log4j.properties and also </p> <pre><code>log4j.rootLogger=DEBUG,ERROR stdout, file </code></pre> <p>line should have either debug or error not both</p> |
5,248,219 | 0 | about number of bits required for Fibonacci number <p>I am reading a algorithms book by S.DasGupta. Following is text snippet from the text regarding number of bits required for nth Fibonacci number.</p> <blockquote> <p>It is reasonable to treat addition as a single computer step if small numbers are being added, 32-bit numbers say. But the nth Fibonacci number is about 0.694n bits long, and this can far exceed 32 as n grows. Arithmetic operations on arbitrarily large numbers cannot possibly be performed in a single, constant-time step.</p> </blockquote> <p>My question is for eg, for Fibonacci number F1 = 1, F2 =1, F3=2, and so on. then substituting "n" in above formula i.e., 0.694n for F1 is approximately 1, F2 is approximately 2 bits, but for F3 and so on above formula fails. I think i didn't understand propely what author mean here, can any one please help me in understanding this?</p> <p>Thanks</p> |
31,710,546 | 0 | Responsive divs without using flexbox <p>I'm working on a chat interface at the moment and currently have the viewport height to 100vh, with a header/navbar, a "main content" section, and the footer where the input field is located - (see fiddle <a href="http://jsfiddle.net/2L8q3r5h/15/" rel="nofollow">here</a>)</p> <p>The way I have it currently coded has the "main" section receive content from the AJAX calls made via the input field in the footer. Once enough messages are added in, only this section will become scrollable as to having the entire page become scrollable. </p> <p>My question is concerning how I could replicate this feature to make it function the same way in older legacy browsers, while still maintain the ability to have the chat section take up the remaining space between the header and footer without affecting the viewport height. My css for the chat section utilizes flexbox and currently looks like this:</p> <pre><code>.chat-section { -ms-flex: 1; -moz-flex: 1; -o-flex: 1; -webkit-flex: 1; flex: 1; background-color: #f8f8f8; border-top: 1px solid #A8A8AC; border-bottom: 1px solid #A8A8AC; overflow-y: scroll; overflow-x: hidden; } </code></pre> |
26,466,621 | 1 | AttributeError: 'int' object has no attribute 'rindex' <p><strong>Setup</strong></p> <p>I'm using Scrapy 0.24.4 and <a href="https://github.com/knockrentals/scrapy-elasticsearch" rel="nofollow">Scrapy-ElasticSearch 0.5</a> to scrape a website and store the results in an elasticsearch instance I have running.</p> <p>I've used <a href="http://blog.florian-hopf.de/2014/07/scrapy-and-elasticsearch.html" rel="nofollow">this blog post</a> to set it all up, with the minor modification that I documented <a href="http://blog.florian-hopf.de/2014/07/scrapy-and-elasticsearch.html?showComment=1413801748670#c1092074214387731109" rel="nofollow">here</a>.</p> <p><em>settings.py</em></p> <pre><code>BOT_NAME = 'blah' SPIDER_MODULES = ['blah.spiders'] NEWSPIDER_MODULE = 'blah.spiders' ITEM_PIPELINES = [ 'scrapyelasticsearch.scrapyelasticsearch.ElasticSearchPipeline', 100 ] ELASTICSEARCH_SERVER = 'localhost' ELASTICSEARCH_PORT = 9200 ELASTICSEARCH_INDEX = 'scrapy' ELASTICSEARCH_TYPE = 'items' </code></pre> <p><strong>Problem</strong></p> <p>If I run the following command to scrape a website:</p> <pre><code>scrapy crawl wiki -o wiki.json </code></pre> <p>With ITEM_PIPELINES commented out - then it works correctly and exports all results to a wiki.json file.</p> <p>With ITEM_PIPELINES uncommented (e.g. set to enable piping results to elasticsearch) - I get the following error:</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 34, in load_object dot = path.rindex('.') AttributeError: 'int' object has no attribute 'rindex' </code></pre> <p><strong>Notes</strong></p> <ul> <li>May or may not be relevant. I actually had to change my local copy of ElasticSearchPipeline python file to comment out <a href="https://github.com/knockrentals/scrapy-elasticsearch/blob/master/scrapyelasticsearch/scrapyelasticsearch.py#L39" rel="nofollow">this block</a> which was causing syntax errors at the point at which it was indexing using uniq_id.</li> </ul> <p>Any help hugely appreciated.</p> |
36,544,976 | 0 | JQuery not working after null ajax responce <p>I have Jquery code</p> <pre><code>$(document).ready(function(){ $('#login').click( function () { $.post('/profile/ajax/login', { username: $('#username').val(), password: $('#password').val(), }, function (res) { if (res != null) { $.each(res, function (i, val) { $('#login-error').html('<div class="alert alert-danger fade in"><a class="close" data-dismiss="alert" href="#">×</a>' + val + '!</div>'); return false; }); } else { location.reload(); } }, 'json' ); } ); } </code></pre> <p>And have PHP code</p> <pre><code>if($_POST) { $username = $_POST['username']; $password = $_POST['password']; $post = Validation::factory($_POST); $post->rule('username', 'not_empty'); $post->rule('password', 'not_empty'); if($post->check()) { if(!Auth::instance()->login($username, $password, true)) { echo json_encode(array('Неверный Логин или Пароль')); } } else { $errors = $post->errors('validation'); echo json_encode($errors); } } </code></pre> <p>If Ajax return some text with errors (res != null) - Jquery work normally. If Ajax returned without any information nothing happens in "else" block.</p> <p>How I can solve this problem?</p> |
1,142,354 | 0 | <p>If you're talking about large volumes of data (millions of rows+), then you will get have a benefit from using different tables to store them in. </p> <p>e.g. basic example 50 million log entries, assuming 5 different "types" of log table Better to have 5 x 10 million row tables than 1 x 50 million row table </p> <ul> <li><p>INSERT performance will be better with individual tables - indexes on each table will be smaller and so quicker/easier to be updated/maintained as part of the insert operation</p></li> <li><p>READ performance will be better with individual tables - less data to query, smaller indexes to traverse. Also, sounds like you'd need to store an extra column to identify what type of Log entry a record is (Product, Shipping....)</p></li> <li>MAINTENANCE on smaller tables is less painful (statistics, index defragging/rebuilding etc)</li> </ul> <p>Essentially, this is about partitioning data. From SQL 2005 onwards, it has built in support for partitioning (see <a href="http://msdn.microsoft.com/en-us/library/ms345146(SQL.90).aspx" rel="nofollow noreferrer">here</a>) but you need Enterprise Edition for that, which basically allows you to partition data in one table to improve performance (e.g. you'd have your one Log table, and then define how the data within it is partitioned)</p> <p>I listened to an interview with one of the eBay architects recently, who stressed the importance of partitioning when needing performance and scalability and I strongly agree based on my experiences.</p> |
35,327,644 | 0 | <p>It turns out that a naïve approach is fairly easy; the following (<em>complete</em> <code>.travis.yml</code>) works for my purposes:</p> <pre><code>language: R install: - Rscript -e 'install.packages(c("devtools", "testthat"))' - Rscript -e 'devtools::install_github("klmr/modules")' script: make test </code></pre> <p>However, I’d still prefer a solution that can actually use the Travis declarations (<code>r_binary_packages</code>, etc.) instead of having to install dependencies manually.</p> |
36,785,961 | 0 | How to make React Native's ScrollView initial zoom to not be 1? <p>I want to put content (multiple images vertically arranged) in a React Native ScrollView (iOS only for now, Android will come later) that is bigger than the phone's screen, and start zoomed out so that it is all visible at the same time.</p> <p>Are there any good examples of using ScrollView.scrollResponderZoomTo in a componentDidMount call that zooms out to fit content in the screen, something like</p> <pre><code><ScrollView style={{width: 500, height: 1000}} // + whatever other properties make this work required way > <View style={{width: 2000, height: 5000}}> <Image style={{width: 2000, height: 2000}} source={.....}/> <Image style={{width: 2000, height: 3000}} source={.....}/> </View> </ScrollView> </code></pre> <p>I tried setting the 'zoomScale' property, but that seems to be ignored and always uses the value 1.</p> <p>According to this issue (<a href="https://github.com/facebook/react-native/issues/2176">https://github.com/facebook/react-native/issues/2176</a>) there is a scrollResponderZoomTo function that can be used, but when I try to use it, it seems that no matter what values I give it it zooms out much too far and off center.</p> <p>The F8 sample app has a ZoomableImage module (<a href="https://github.com/fbsamples/f8app/blob/b5df451259897d1838933f01ad4596784325c2ad/js/tabs/maps/ZoomableImage.js">https://github.com/fbsamples/f8app/blob/b5df451259897d1838933f01ad4596784325c2ad/js/tabs/maps/ZoomableImage.js</a>) which uses the Image.resizeMode.contain style to make an image fit the screen, but that loses the quality of image, so when you zoom in it gets blurry.</p> |
10,781,974 | 0 | <p>just use</p> <pre><code>$("#edit_form").validate({ rules: { re_password: { equalTo: "#password" } }, messages: { re_password: { equalTo: "Password does not match" } } }); </code></pre> <p>without use class "required" in input field</p> <pre><code><input id="password" type="password" name="password" class="TextBox"> <input id="re_password" type="password" name="re_password" class="TextBox"> </code></pre> |
34,833,883 | 0 | Configure Solr to index metadata included in seed.txt <p>I am currently running Nutch 1.10 and solr 5.3.1, and I am attempting to crawl and index a few sites. These sites have an id and name associated (on the same line as the url in the seed.txt file) which I would like to be included along side other fields in the solr search results (such as host, segment, etc). Is this possible? If so, would I need to modify any files other than the seed.txt and schema-solr4?</p> <p>Example of what I have in seed.txt: </p> <p>www.exampleSite.com id=3 name=exampleSite</p> |
19,217,964 | 0 | <p>For version 2.0</p> <p>create c# code to invoke power shell and execute 1st command for mailbox creation then dispose and write another set of c# code to invoke and execute the Active sync command and dispose.</p> <p>Note: the Domain controller should be the same for mailbox creation and Active sync.</p> |
21,164,297 | 0 | <p>This is how to do it:</p> <p>You need to send a special APDU to ask for the remaining data and look for status 0x61xx cl, ins, p1, p2, = (0x00, 0xa5, 0x00, 0x00)</p> <pre><code>def _cmd_ok(self, *args, **kwargs): data, status = self._cmd(*args, **kwargs) #get high bits low = status & 0xFF; high = status >> 8; if status != 0x9000: if high != 0x61: raise Exception('APDU error: 0x%04x' % status) else: while status != 0x9000: part, status = self._cmd(0x00, 0xa5, 0x00, 0x00) data = data + part return ''.join(map(chr, data)) </code></pre> |
33,061,176 | 0 | <p>New in iOS 9, <code>CMSensorRecorder</code>(<a href="https://developer.apple.com/library/prerelease/ios/documentation/CoreMotion/Reference/CMSensorRecorder_class/index.html#//apple_ref/occ/clm/CMSensorRecorder/isAuthorizedForRecording" rel="nofollow">doc link</a>) has a class method to check if your app is authorized for Motion & Fitness: </p> <ul> <li>Switft <code>class func isAuthorizedForRecording() -> Bool</code></li> <li>Objective-c <code>+ (BOOL)isAuthorizedForRecording</code></li> </ul> |
26,104,872 | 0 | Java won't write UTF8 characters in MySQL through a JNDI datasource <p>I have configured JNDI to access a MySQL database with the UTF-8 server charset. My JNDI URL in Tomcat's context file is <code>jdbc:mysql://127.0.0.1:3306/my_db?useUnicode=true&amp;characterEncoding=UTF-8"</code> The database server, the database and its table are all set to utf-8 using the instructions in this site.</p> <p>By debugging the JDBC connection it appears to use UTF-8. However an e grave character is written in the database as 0x C3 83 C2 A8. Clearly, the UTF-8 string for e grave, which is 0x C3 A8 has been misinterpreted by the server as Latin1 and 0xC3 in Latin-1 is 0xC3 83 in UTF-8, and similarly 0xA8 in Latin-1 is 0xC2 A8 in UTF-8.</p> <p>If the database is properly configured as per <a href="http://stackoverflow.com/questions/21092007/why-java-strings-are-not-saved-as-utf-8-in-mysql">Why java strings are not saved as UTF-8 in MYSQL?</a> why is the server converting the input UTF-8 string from the driver into Latin-1 and then back into UTF-8 (the encoding for the database and table I am using).</p> |
7,649,881 | 0 | <p>According to <a href="http://www.php.net/manual/en/function.is-numeric.php">http://www.php.net/manual/en/function.is-numeric.php</a>, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.</p> <p>preg_match can be slow, and you can have something like 0000 or 0051.</p> <p>I prefer using ctype_digit (works only with strings, it's ok with $_GET).</p> <pre><code><?php $id = $_GET['id']; if (ctype_digit($id)) { echo 'ok'; } else { echo 'nok'; } ?> </code></pre> |
6,017,290 | 0 | <p>It isn't remembering the last used set on the directory, it's loading the gemset from the <code>.rvmrc</code> file in that directory</p> <p><a href="https://rvm.io/workflow/rvmrc/" rel="nofollow">https://rvm.io/workflow/rvmrc/</a></p> |
15,758,078 | 0 | <p>Performance GET or POST depends on how it is implemented on server side.</p> <p>You should more concerned about RESTful convention here.</p> <p>GET : Retrieve a representation of the entry specified by the url.</p> <p>POST: Create a new entry. </p> <p>Look more <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="nofollow">here.</a></p> |
16,904,739 | 0 | Canvas not drawing image from spritesheet <p>Ok So I have managed to draw one image that is the player, but Now I am trying to draw an enemy and it just wont work. I have added alerts and it shows that the program is doing the draw enemy function but it still wont draw? </p> <p>Here is the thing running: <a href="http://www.taffatech.com/DarkOrbit.html" rel="nofollow">http://www.taffatech.com/DarkOrbit.html</a> Entire code: <a href="http://www.taffatech.com/Source.js" rel="nofollow">http://www.taffatech.com/Source.js</a></p> <p>If anyone can help me with this I would be very grateful!</p> <p>Here are my data functions:</p> <pre><code>function Player() //Object { //////Your ships values this.PlayerHullMax = 1000; this.PlayerHull = 1000; this.PlayerShieldMax = 1000; this.PlayerShield = 347; this.SpaceCrystal = 2684; this.Speed = 10; //should be around 2 pixels every-time draw is called by interval, directly linked to the fps global variable //////////// ///////////flags this.isUpKey = false; this.isDownKey = false; this.isLeftKey = false; this.isRightKey = false; ///////////// //////////extra ///////////// ////Pick Ship this.type = "Cruiser"; this.srcX = PlayerSrcXPicker(this.type); this.srcY = PlayerSrcYPicker(this.type); this.drawX = PlayerdrawXPicker(this.type); this.drawY = PlayerdrawYPicker(this.type); this.playerWidth = PlayerWidthPicker(this.type); this.playerHeight = PlayerHeightPicker(this.type); //// } Player.prototype.draw = function() { ClearPlayerCanvas(); ctxPlayer.globalAlpha=1; this.checkDirection(); //must before draw pic to canvas because you have new coords now from the click ctxPlayer.drawImage(spriteImage,this.srcX,this.srcY,this.playerWidth,this.playerHeight,this.drawX,this.drawY,this.playerWidth,this.playerHeight); }; Player.prototype.checkDirection = function() //these functions are in the PLayer class { if(this.isUpKey == true)//if true { if(Player1.drawY >= (0 + this.Speed)) { this.drawY -= this.Speed; } } if(this.isRightKey == true) { if(Player1.drawX <= (canvasWidthPlayer - this.playerWidth)) { this.drawX += this.Speed; } } if(this.isDownKey == true) { if(Player1.drawY <= (canvasHeightPlayer - this.playerHeight)) { this.drawY += this.Speed; } } if(this.isLeftKey == true) { if(Player1.drawX >= (0 + this.Speed)) { this.drawX -= this.Speed; } } }; ///////////////////END PLAYER DATA//////////////////////////////////////////////// function Enemy() //Object { //////Your ships values this.EnemyHullMax = 1000; this.EnemyHull = 1000; this.EnemyShieldMax = 1000; this.EnemyShield = 347; this.SpaceCrystalReward = 2684; this.EnemySpeed = 10; //should be around 2 pixels every-time draw is called by interval, directly linked to the fps global variable //////////// ////Pick Ship this.type = "Hover"; this.srcX = EnemySrcXPicker(this.type); this.srcY = EnemySrcYPicker(this.type); this.drawX = EnemydrawXPicker(this.type); this.drawY = EnemydrawYPicker(this.type); this.enemyWidth = EnemyWidthPicker(this.type); this.enemyHeight = EnemyHeightPicker(this.type); //// } Enemy.prototype.draw = function() { ClearEnemyCanvas(); ctxEnemy.globalAlpha=1; ctxEnemy.drawImage(spriteImage,this.srcX,this.srcY,this.playerWidth,this.playerHeight,this. drawX,this.drawY,this.playerWidth,this.playerHeight); } //////////START ENEMY DATA////////////////// function PlayerSrcXPicker(type) //these functions can be used by player and enemy { if (type == "Cruiser") { return 0; } } function PlayerSrcYPicker(type) { if (type == "Cruiser") { return 1385; } } function PlayerdrawXPicker(type) { if (type == "Cruiser") { return 100; } } function PlayerdrawYPicker(type) { if (type== "Cruiser") { return 400; } } function PlayerWidthPicker(type) { if (type == "Cruiser") { return 148; } } function PlayerHeightPicker(type) { if (type == "Cruiser") { return 85; } } function EnemySrcXPicker(type) { if (type == "Hover") { return 906; } } function EnemySrcYPicker(type) { if (type == "Hover") { return 601; } } function EnemydrawXPicker(type) { if (type == "Hover") { return 800; } } function EnemydrawYPicker(type) { if (type== "Hover") { return 300; } } function EnemyWidthPicker(type) { if (type == "Hover") { return 90; } } function EnemyHeightPicker(type) { if (type == "Hover") { return 75; } } </code></pre> <p>My init() is:</p> <pre><code>function init() { drawBackground(); Player1 = new Player(); Enemy1 = new Enemy(); drawBars(); setUpListeners(); StartDrawingShips(); } </code></pre> <p>My interval:</p> <pre><code>function UpdateShips() { Player1.draw(); Enemy1.draw(); } function StartDrawingShips() { StopDrawing(); drawInterval = setInterval(UpdateShips,fps); // redraw player every fps } function StopDrawing() { clearInterval(drawInterval); } </code></pre> <p>If you need any other information then just ask!</p> |
33,691,557 | 0 | <p>Part of the <code>Type</code> logic is moved to <code>TypeInfo</code>(<a href="https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo(v=vs.110).aspx">MSDN</a>) in Windows Runtime.</p> <pre><code>using System.Reflection; ... bool isSubClassOf = typeof (Dog).GetTypeInfo().IsSubclassOf(typeof (Animal)); </code></pre> |
3,474,582 | 0 | <p>The timeout suggested above worked around the issue on Chrome. Not issue existed on IE8 or FF3. Thanks for the tip as always. My code that to set focus that worked is: <code>window.setTimeout(function() { document.form1.password.focus(); },0);</code></p> |
2,172,295 | 0 | <p>See <a href="http://blogs.msdn.com/bimusings/archive/2005/12/14/503648.aspx" rel="nofollow noreferrer">Rendering HTML in Reporting Services Text Boxes in SQL Server 2008</a></p> <p>I've not tried it and may not apply to rdlc etc, so YMMV</p> |
16,510,567 | 0 | <p>Just remove the <code>setContentView(R.layout.activity_main)</code> line in addTextView() method. Because it always sets the layout to the screen.</p> |
10,245,064 | 0 | <p>You can use these rules of thumb to decide what storage model will work for your app.</p> <ul> <li>If the data fits in memory entirely and is relatively unstructured, use plist</li> <li>If the data fits in memory entirely and has tree-like structure, use XML</li> <li>If the data does not fit in memory and has a structure of a graph, and the app does not need extraordinary query capabilities, use Core Data</li> <li>If the data does not fit in memory, has a complex structure, or the app benefits from powerful query capabilities provided by relational databases, use sqlite</li> <li>If the data must be secret (e.g. a password), use <a href="https://developer.apple.com/library/ios/#documentation/security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html">keychain</a>.</li> </ul> <p>Note that these choices often overlap, because multiple storage models will fit the same app. Your final decision depends on your personal preferences - you pick a technology that you understand better.</p> <p>There was a <a href="http://stackoverflow.com/questions/523482/core-data-vs-sqlite-3">very good question about sqlite vs. Core Data</a> on Stack Overflow, you may want to read through the answers to that question.</p> |
36,845,177 | 0 | <p>Using <code>split()</code> without parameters will result in splitting after a space example <code>"test1 test2".split()</code> results in <code>["test1", "test2"]</code></p> <p>instead, try this:</p> <pre><code>newLine = line.split("|") </code></pre> |
31,023,958 | 0 | <p><code>m.Attributes</code> can consist of a combination of some flag values, and <code>FileAttributes.Hidden</code> is one of them.(The complete list can be seen in <a href="https://msdn.microsoft.com/en-US/library/system.io.fileattributes.aspx" rel="nofollow">MSDN</a>)</p> <p>So, the predicate of the first statement: </p> <pre><code> m.Attributes <> FileAttributes.Hidden </code></pre> <p>tests "not (<code>m.Attributes</code> consists of only one flag <code>Hidden</code>)", that is even true for the value of the combinations of <code>Hidden</code> and <code>ReadOnly</code>, or <code>Hidden</code> and <code>System</code>, etc.</p> <p>The second statement:</p> <pre><code>(m.Attributes And FileAttributes.Hidden) = 0 </code></pre> <p>tests "pick up the partial value of <code>Hidden</code> from <code>m.Attribute</code>, and see if not set", that is true at least if the value doesn't have <code>Hidden</code> set, and the other flags are ignored. Hence that is false for the combinations of <code>Hidden</code> and <code>ReadOnly</code>, or <code>Hidden</code> and <code>System</code>, etc.</p> <hr> <p>As a side note, <code>.Select(Function(k) k)</code> does nothing and can be omitted. </p> <pre><code>subFolder.GetFiles().Where(Function(m) (m.Attributes And FileAttributes.Hidden) = 0).Count </code></pre> |
6,942,014 | 0 | <p>There is a blog post about using activity indicators here: <a href="http://www.edumobile.org/iphone/iphone-programming-tutorials/use-activityindicator-in-iphone/" rel="nofollow">http://www.edumobile.org/iphone/iphone-programming-tutorials/use-activityindicator-in-iphone/</a></p> <p>The most important pieces of code are:</p> <pre><code>[activityView startAnimating]; [activityView stopAnimating]; //To Test for a Conditional [activityView isAnimating]; </code></pre> |
13,795,380 | 0 | Rails find by condition <p>Just wondering if there is any function that allows to do that:</p> <pre> MyModel.find_by_conditon(method_a - method_b > 0)</pre> <p> <code>MyModel.class</code></p> <pre> def method_a next_service_date.to_i end def method_b last_service_date.to_i end </pre> <pre> def next_service_date service_date.present? ? calculated_time_estimation : row_time_estimation end def calculated_time_estimation service_date + calculated_service_period end def calculated_service_period case(service_frequency_period) when 'Year' service_frequency_number.to_i.year when 'Month' service_frequency_number.to_i.month when 'Week' service_frequency_number.to_i.day * 7 when 'Day' service_frequency_number.to_i.day end end </pre> <p><code>service_frequency_number</code>, <code>service_frequency_period</code>, <code>service_date</code> are attributes for MyModel</p> |
10,195,868 | 0 | Inserting value into an array using key value <p>I have already fetched both key and value in array.how can I insert that value into another array in the same key position using that fetched key value.</p> <p>Here my coding </p> <pre><code>$key=array_search($s_str,$opis_split); //key value $value=a; //array value $push=array_push($value,$key); var_dump($push); </code></pre> |
19,682,978 | 0 | <p>Maybe this could help? <a href="http://mottie.github.io/tablesorter/docs/example-locale-sort.html" rel="nofollow">jQuery Plugin: Tablesorter</a></p> <p>You may have to modify it slightly if the special character you are using is not supported but it should at least get you started.</p> |
2,289,003 | 0 | <blockquote> <p>So, the "inheritance" of static members merely looks like namespace pollution</p> </blockquote> <p>That's right, except that one guy's pollution is another guy's added spicy flavouring.</p> <p>I think Martin Fowler, in his work on DSLs, has suggested using inheritance in this way to allow convenient access to static methods, allowing those methods to be used without class name qualification. So the calling code has to be in a class that inherits the class in which the methods are defined. (I think it's a rotten idea.)</p> <p>In my opinion, static members should not be mixed into a class with a non-static purpose, and the issue you raise here is part of the reason why it's important not to mix them.</p> <p>Hiding private static <em>mutable</em> data inside the implementation of an otherwise "instancey" class is particularly horrible. But then there are static methods, which are even worse mixers. Here's a typical use of static methods mixed into a class:</p> <pre><code>public class Thing { // typical per-instance stuff int _member1; protected virtual void Foo() { ... } public void Bar() { ... } // factory method public static Thing Make() { return new Thing(); } } </code></pre> <p>It's the static factory method pattern. It's pointless most of the time, but even worse is that now we have this:</p> <pre><code>public class AnotherThing : Thing { } </code></pre> <p>This now has a static <code>Make</code> method which returns a <code>Thing</code>, not a <code>AnotherThing</code>.</p> <p>This kind of mismatch strongly implies that anything with static methods should be sealed. Static members fail to integrate well with inheritance. It makes no sense to have them heritable. So I keep static things in separate static classes, and I gripe about redundantly having to declare every member static when I've already said that the class is static.</p> <p>But it's just one of those too-late-now things. All real, working languages (and libraries, and products) have a few of them. C# has remarkably few.</p> |
27,130,355 | 0 | <p>In assumption that you're on a windows pc it sounds like you're experiencing a loop unrolling bug in <a href="https://code.google.com/p/angleproject/" rel="nofollow">ANGLE</a>.</p> <p>To verify this start your browser with <code>--use-gl=desktop</code>. This flag forces your browser to <em>not use</em> the ANGLE DirectX conversion layer. When your problem is indeed ANGLE based take a look at the compiled HLSL code using <a href="http://www.ianww.com/2013/01/14/debugging-angle-errors-in-webgl-on-windows/" rel="nofollow">getTranslatedShaderSource</a> and debug from there.</p> <p>Unfortunately if it is an angle based issue your only chance to get it running is either fiddling around until its converted correctly or file a bug on the angle project page.</p> |
25,057,174 | 1 | Scrapy crawl in order <p>I can't figure out how to make scrapy crawl links in order I've got a page with articles and in each one there is a title but the article doesn't match the title Also in settings.py I added:</p> <pre><code>DEPTH_PRIORITY = 1 SCHEDULER_DISK_QUEUE = 'scrapy.squeue.PickleFifoDiskQueue' SCHEDULER_MEMORY_QUEUE = 'scrapy.squeue.FifoMemoryQueue' </code></pre> <p>I've got something like this:</p> <pre><code>class Getgot(Spider): name = "getem" allowed_domains = ["somesite.us"] start_urls = ["file:local.html"] el = '//div[@article]' def parse(self,response): hxs = HtmlXPathSelector(response) s = hxs.select('//article') filename = ("links.txt") filly = open(filename, "w") for i in s: t = i.select('a/@href').extract() filly.write(str(t[0])+'\n') yield Request(str(t[0]),callback=self.parse_page) def parse_page(self,res): hxs = HtmlXPathSelector(res) s = hxs.select('//iframe').extract() if s: filename = ("frames.txt") filly = open(filename, "a") filly.write(str(s[0])+'\n') else: filename = ("/frames.txt") filly = open(filename, "a") filly.write('[]\n') </code></pre> |
22,996,315 | 0 | <p><code>SpringApplication</code> has a property <code>webEnvironment</code>. It defaults to true if Tomcat is on the classpath but you can set it to false (programmatically or with <code>spring.main.webEnvironment</code>).</p> |
7,573,528 | 0 | Data binding - Visual Studio 2010 <p>I am working with Visual Studio 2010.</p> <p>Scenario:</p> <p>I have 2 comboboxes. Contents of first combobox:</p> <p>PC</p> <p>DB...</p> <p>Contents of Second combobox:</p> <p>Password reset</p> <p>Hardware problem</p> <p>SQL</p> <p>My question:</p> <p>When I select 'PC' in the first combo box I want 'Password Reset' and 'Hardware Problem' to show up.</p> <p>When I select 'DB' in first combobox I want 'SQL' to show up in the second combo box.</p> <p>Does anyone know how I can bind data from one combo box to the other ?</p> <p>Also when I click on 'DB' ->'SQL' then a 3rd list box with data under these two combo items should be populated.</p> <p>I feel this relates to data binding but not sure how to go about it.</p> <p>ANy idea or link I could refer to??</p> <p>Please help.</p> <p>Thank you.</p> |
19,697,700 | 0 | How to speed up rbind? <p>I'm supposed to download a table from MS-SQL server.</p> <p>The number of row is larger than 6million. The server cannot return entire data at once.</p> <p>So, I wrote a code that downloads 10,000 rows at a time. and, it binds rows in the loop.</p> <p>Assume that <code>getData()</code> function returns a data frame contains 10000 rows at a time. (Pseudo Code)</p> <pre><code>for(i in 1:600) { tempValue <- getData() wannagetValue <- rbind(wannagetValue,tempValue) print(i) } </code></pre> <p>The problem is that it gets slower as time goes by.</p> <p>I think using rbind like that way is not a good idea.</p> <p>Any advice will be very helpful. Thank you in advance.</p> |
8,481,610 | 0 | R - Customizing X Axis Values in Histogram <p>I want to change the values on the x axis in my histogram in R. </p> <p>The computer currently has it set as </p> <pre><code>0, 20, 40, 60, 80, 100. </code></pre> <p>I want the x axis to go by 10 as in: </p> <pre><code>0,10,20,30,40,50,60,70,80,90,100. </code></pre> <p>I know to get rid of the current axis I have to do this</p> <pre><code>(hist(x), .... xaxt = 'n') </code></pre> <p>and then</p> <pre><code>axis(side = 1) ..... </code></pre> <p>But how do I get it to show the numbers that I need it to show? </p> <p>Thanks.</p> |
20,733,107 | 0 | <p>As far as I know , some goals are yet not available with the tomcat7 mojo and <code>mvn tomcat7:list</code> is one of them. <code>mvn tomcat6:list</code> is available for the tomcat6 mojo.</p> |
26,423,414 | 0 | <pre><code>public static int yourFunction(ArrayList<Integer> list){ String numbers = ""; // fill a string with your numbers for(Integer i : list){ numbers += String.valueOf(i); } // could be nicer with java8 lambda function String tmp_numbers; // temporary string needed while(numbers.length() > 2){ tmp_numbers = ""; for(int i = 0; i < numbers.length()-1; ++i){ // add two following numbers // substring to read digit by digit int v = Integer.parseInt(numbers.substring(i,i+1)); // first digit v += Integer.parseInt(numbers.substring(i+1,i+2)); // + second tmp_numbers = tmp_numbers + String.valueOf(v); // and fill the tmp string with it } numbers = tmp_numbers; // set the tmp string to our new beginning } return Integer.parseInt(numbers); } </code></pre> |
1,541,941 | 0 | <p>Possible the Handle is not created, you can test this with IsHandleCreated. See <a href="http://stackoverflow.com/questions/1364116/avoiding-the-woes-of-invoke-begininvoke-in-cross-thread-winform-event-handling">this question</a> for numerous issues on IvokeReqired usage. You can see the my own answer was far from simple to acually make it work reliably. </p> <p>I would recommend first not threading the UI. If you must use the .Net reflector to see what those API calls are really doing.</p> <p>Update:</p> <p>@karthik, your sample isn't complete enough for me to be able to fix it. I can't tell when or on what thread the form might have been created. I can tell you that if you just call this from any-old-thead it won't work, it needs a message pump. There are thee ways to get a message pump on a thread:</p> <ol> <li>Call Application.Run</li> <li>Call Form.ShowModalDialog</li> <li>Call Application.DoEvents in a loop</li> </ol> |
11,216,443 | 0 | <p>You can achieve that by using css overflow-x: auto; please see example <a href="http://jsfiddle.net/Xa8yB/6/" rel="nofollow">http://jsfiddle.net/Xa8yB/6/</a></p> |
19,756,944 | 0 | <p>you can use simply this code:</p> <pre><code>div{ width:100vw; height:100vh; } </code></pre> <p>this code work like a charm... <code>:)</code></p> <p><a href="http://jsfiddle.net/mohsen4887/m3BSk/" rel="nofollow"><strong>jsFiddle</strong></a></p> |
8,782,240 | 0 | <p><em>EDIT - The following will convert UTF-16 with BOM. I don't think it works with any of the other UTF formats. I know it doesn't work for UTF-8. I'm not sure about UTF-32 with BOM</em></p> <pre><code>for %%F in (*.txt) do type "%%F" >"%%~nF.converted" </code></pre> <p>If run from the command line then use single percent <code>%</code> instead of double percent <code>%%</code>.</p> <p>After you verify the converted files are correct, you can</p> <pre><code>del *.txt ren *.converted *.txt </code></pre> |
30,132,413 | 0 | <blockquote> <p>Are these the right schema types for generating the search results snippet shown in the picture?</p> </blockquote> <p>If these are rejected in GWT, then snippets will never appear. If proper <code>schema.org</code> is implemented, then Google may display it if it trusts your site enough and if it <a href="https://developers.google.com/structured-data/" rel="nofollow">supports</a> these schema types.</p> |
27,733,794 | 0 | QML can't open file dialog <p>I'm trying to create a simple File dialog using the QML:</p> <pre><code>import QtQuick 2.2 import QtQuick.Dialogs 1.0 FileDialog { id: fileDialog title: "Please choose a file" onAccepted: { console.log("You chose: " + fileDialog.fileUrls) Qt.quit() } onRejected: { console.log("Canceled") Qt.quit() } Component.onCompleted: visible = true } </code></pre> <p>However, when I try to preview it I receive following errors/warnings:</p> <pre><code>QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: No such file or directory Invalid URL: QUrl( "" ) Invalid URL: QUrl( "" ) Invalid URL: QUrl( "" ) Invalid URL: QUrl( "" ) kf5.kio.core: KLocalSocket(0x1a51cf0) Jumbo packet of 35946 bytes </code></pre> <p>As far as I understand, settings the QUrl is not needed to display the dialog. If so, is it possible to set it to the user's home folder in a cross-platform way? I also tried to start the ibus daemon as I found on google that it's causing that first error line but it's still not working.</p> <p>I'm using Arch (fully updated) with KF5 and QT5.4 installed.</p> <p>Thanks for help!</p> |
14,507,173 | 0 | Copy TabControl Tab <p>I searched the internet for this but i couldn't find how to do it with C#</p> <p>What i am trying to do is make it so that when i click on my <code>NewTab</code> button, a new tab appears with the same controls that were on the first tab. I saw some information on how to add a <code>UserControl</code> to your form, but C# doesn't have anything like that.</p> <p>And for everyone who would say "Post your code", i don't have any, so don't bother saying that, the only code i have is the code for the program and that wouldn't help anyone.</p> |
4,053,417 | 0 | Problem with NSStrings and UIAlertView <p>I have having a very odd issue when utilizing this UIAlertView. When viewing a Physician they have several offices. Upon selecting one you get an alert that offers to call this location or display it on a map. To create the alert and to have data at the ready when the alert is dismissed, I declared 4 NSStrings (although I probably only need 2) in the header file. (alertTitle, alertText, alertNumber, and alertAddress) </p> <p>When looking at the code, the problem is where the alertAddress is involved. Also keep alertNumber in mind. I had a lot of this code condensed but have expanded it to help myself find the problem!</p> <pre><code> -(IBAction)address1ButtonPressed:(id) sender { Formatter *pnf = [Formatter alloc]; alertTitle = [physician objectForKey:ADDRESS1DESC_KEY]; NSString *a = [physician objectForKey:ADDRESS1A_KEY]; NSString *b =[physician objectForKey:ADDRESS1CITY_KEY]; NSString *c =[physician objectForKey:ADDRESS1STATE_KEY]; NSString *d = [physician objectForKey:ADDRESS1ZIP_KEY]; NSString *p = [physician objectForKey:PHONE1A_KEY]; alertAddress = [[NSString stringWithFormat:@"http://maps.google.com/maps?q=%@,+%@,+%@+%@",a,b,c,d] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",alertAddress); alertText = [NSString stringWithFormat:@"%@\n%@, %@ %@\n%@",a,b,c,d,[pnf stringFromPhoneNumber:p]]; alertNumber = [p stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [pnf release]; UIAlertView *phoneAlert = [[UIAlertView alloc] initWithTitle:alertTitle message:alertText delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Call",@"View Map",nil]; [phoneAlert show]; } </code></pre> <p>All is well until we reach the point where we handle the alert dismissal. alertNumber seems to come across just fine, I can use it to trigger the phone call and Log it to the console. </p> <p>alertAddress however is not at all happy about doing the same thing. even trying to Log it to the Console causes a EXC_BAD_ACCESS. alertAddress logs the data correctly before the alert is involved but accessing this data at all when handling the alert button dismissal causes a problem. I have even used the alertNumber it is place and the code functions perfectly. </p> <p>Why are both exact same NSString variables behaving so differently when used the exact same way?</p> <pre><code>- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { NSLog(@"Dialing: %@",alertNumber); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",alertNumber]]]; } if (buttonIndex == 2) { NSLog(@"Map Selected"); NSLog(@"alertAddress contains: %@",alertAddress); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://maps.google.com/maps?q=%@",alertAddress]]]; } } </code></pre> <p>Here are the related declarations in the header file too...</p> <pre><code>@interface PhysicianDetailViewController: UIViewController { ... NSString *alertTitle; NSString *alertText; NSString *alertNumber; NSString *alertAddress; ... } @property (nonatomic, retain) NSString *alertTitle; @property (nonatomic, retain) NSString *alertText; @property (nonatomic, retain) NSString *alertNumber; @property (nonatomic, retain) NSString *alertAddress; ... </code></pre> <p>And here is the console output during this process if it helps....</p> <pre><code> > 2010-10-29 11:09:17.954 [2672:307] http://maps.google.com/maps?q=123%20Main%20Street%0ASuite%20A,+Tampa,+FL+11111 > 2010-10-29 11:09:21.657 [2672:307] Map Selected > Program received signal: “EXC_BAD_ACCESS”. > kill quit </code></pre> |
8,164,576 | 0 | <pre><code>$var = '<a href="http://amazon.com/dp/' . $v . '">http://amazon.com/dp/' . $v.'</a>'; </code></pre> |
18,408,785 | 0 | Fatal error: Cannot use string offset as an array Not making any sense at all <p>I have the fatal error coming up in the error log but it is not affecting the application at all for some reason. This is the code that is running and it makes no sense why it generating the PHP error.</p> <pre><code>for ($i = 1; $i <= $tournament['num_score_fields']; $i++) { $scoresArrayTemp = array( 'score', 'dist', 'dateShot', 'tens', 'nines' ); foreach($scoresArrayTemp AS $val){ if(empty($scores[$i][$val])){ $scores[$i][$val] = ''; } } } </code></pre> <p>The error is generated by this line</p> <pre><code>$scores[$i][$val] = ''; </code></pre> <p>Any help would be greatly appreciated thanks!</p> <p>Based on answer 1 I changed code to this:</p> <pre><code>for ($i = 1; $i <= $tournament['num_score_fields']; $i++) { $scoresArrayTemp = array( 'score'=>'', 'dist'=>'', 'dateShot'=>'', 'tens'=>'', 'nines'=>'' ); if(!is_array($scores[$i])){ $scores[$i] = $scoresArrayTemp; } echo $scores[$i]['score']; } </code></pre> <p>Still gets the error on the last line when echoing out the variable</p> |
38,501,090 | 0 | How can I debug the source code of .Net Core (not ASP.net Core)? <p>I see that there is a simple solution to enable me to debug ASP.Net Core source Code (<a href="http://stackoverflow.com/a/38450697/6618773">http://stackoverflow.com/a/38450697/6618773</a>). But for me this doesn't work for the .Net Core assemblies from the corefx repository on Github. Is there a solution for this? Thanks a lot.</p> |
35,646,989 | 0 | <p>On Linux, at least certain versions, <code>st_atime</code> and some other time fields in <code>struct stat</code> are inside <code>struct timespec</code> and contain proper timestamps with full nanosecond precision. On those systems <code>st_atime</code> is a define to something else. On my CentOS machine it is defined to <code>st_atim.tv_sec</code>.</p> <p>Throw your code into the preprocessor to see what it is on your system:</p> <pre><code>$ cat foo.c #include <sys/stat.h> void foo(void) { struct stat st; (void)st.st_atime; } $ cc -E foo.c | tail -7 void foo(void) { struct stat st; (void)st.st_atim.tv_sec; } </code></pre> <p>Gdb doesn't know about preprocessor defines, so it can't know how your code got preprocessed. It only knows about the real definition of the struct.</p> |
39,372,636 | 0 | Slow Small Webpack 2 Build - Tree Shaking - Sass - Chunking <p>I've put together a very basic webpack 2 build, but it seems to be slow for the project size. The three things I wanted have were:</p> <ol> <li>Chunking (js & scss)</li> <li>SCSS compiling</li> <li>Tree Shaking</li> </ol> <p>Webpack seemed to be a good choice for being able to do these things. I've been using Gulp and Rollup, but the SCSS/Chunking along side of the tree shaking is a nice thing. </p> <p>It takes around 4000 - 5000ms to compile the build, which wouldn't be the end of the world except the project is so small, so I'm worried about that becoming much larger as a project grows.</p> <p>I've tried a couple things to improve the speed.</p> <pre><code>resolve : { root: path.resolve(__dirname,'src') } </code></pre> <p>This did help, reducing the time by a couple hundred ms, so that was great. I tried to take this further by also resolving alias, but that didn't really show any gains as far as I could tell.</p> <p>I set devTool to eval as well. Beyond this I haven't really been able to improve things, but I'm sure it's something in the way I've set things up. It's worth noting that while 'webpack' compiles the build, running the webpack-dev-server doesn't. It's starts up, hangs on the compile and then crashes. This may or may not be a separate issue, but I thought it was worth including. </p> <p>I'm also using ES6 System.import for chunking (just as a note).</p> <p>I put the project up on git, so feel free to pull it down: <a href="https://github.com/loriensleafs/trying-out-webpack2" rel="nofollow">https://github.com/loriensleafs/trying-out-webpack2</a></p> <p>The webpack.config.js is:</p> <pre><code>var path = require('path'), webpack = require('webpack'), CleanPlugin = require('clean-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin'), production = process.env.NODE_ENV === 'production'; var plugins = [ new ExtractTextPlugin({ filename: 'bundle.css', allChunks: true}), new webpack.optimize.CommonsChunkPlugin({ name : 'vendor', children : true, minChunks : 2 }) ]; if (production) { plugins = plugins.concat([ new CleanPlugin('builds'), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 51200, // ~50kb }), new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false, // Suppress uglification warnings }, }), new webpack.DefinePlugin({ __SERVER__ : !production, __DEVELOPMENT__ : !production, __DEVTOOLS__ : !production, 'process.env': { BABEL_ENV: JSON.stringify(process.env.NODE_ENV), } }) ]); } module.exports = { // debug : !production, devTool : production ? false : 'eval', entry : './src', output : { path : 'builds', filename : 'bundle.js', chunkFilename : 'chunk.js', publicPath : 'builds/' }, resolve : { root: path.resolve(__dirname,'src') }, plugins : plugins, module : { loaders: [ { test : /\.(png|gif|jpe?g|svg)$/i, loader : 'url', query : { limit: 10000 } }, { test : /\.js$/, include : /src/, exclude : /node_modules/, loader : 'babel' }, { test : /\.scss$/, include : /src/, exclude : /node_modules/, loader : ExtractTextPlugin.extract(['css','sass']) }, { test : /\.html$/, loader : 'html' } ] } }; </code></pre> <p>Thanks for any advice/help folks have on this. If there's any other helpful info I can post on here please let me know.</p> |
15,093,480 | 0 | <pre><code>function updateObject(object, newValue, path){ var stack = path.split('>'); while(stack.length>1){ object = object[stack.shift()]; } object[stack.shift()] = newValue; } </code></pre> |
12,155,327 | 0 | <ol> <li>Find Ruby installation path. Maybe something like "C:\Ruby193...". There is a bin dir under that.</li> <li>Add the bin dir to your PATH env. </li> </ol> |
33,292,092 | 0 | <p>You can print "test->data" correctly because that's an int. The issue is that "test->left" and "test->right" are pointers, and pointers are basically numbers that refer to where another object is stored.</p> <p>If you wanted to print the left node's data, you'd have to do this:</p> <pre><code>cout << "left: " << test->left->data << endl; </code></pre> <p>And then you'd have to do the same for the right node.</p> |
25,319,584 | 0 | <p>i think it's not a javascript problem but more a server side issue.</p> <p>You should try to add <code>header('Content-Type: application/json');</code> before your echo in your php file</p> |
12,207,419 | 0 | R: How do I use coord_cartesian on facet_grid with free-ranging axis <p>Consider some <code>facet_grid</code> plot</p> <pre><code>mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() mt + facet_grid(vs ~ am, scales = "free") </code></pre> <p><img src="http://had.co.nz/ggplot2/graphics/3cece11dd9b535143ff97d3d2a8a5c2e.png" alt=""></p> <p>Imagine I just want to zoom on <strong>just the top row</strong> in the plots above to only show the y-axes values between 3 and 4. I could do this with <code>coord_cartesian()</code> if they weren't faceted or if I wanted to zoom on all plots, but don't have a good solution in this case. I suppose I could subset the data first, but that is taboo for good reason (e.g. would throw off any statistical layer, etc). </p> <p>(Note that the question is related to this: <a href="http://stackoverflow.com/questions/6574188/r-ggplot2-how-can-i-independently-adjust-the-x-axis-limits-on-a-facet-grid">R: {ggplot2}: How / Can I independently adjust the x-axis limits on a facet_grid plot?</a> but the answer there will not work for this purpose.)</p> |
28,318,309 | 0 | Embedding pyqtgraph into tab widget Pyqt <p>I am bit new to Pyqt4 and pyqtgraph. I have tab widget with me and I want to add pyqtgraph into tab widget, so that this graph will be displayed inside (tab1) widget. Can any one tell me how can I do it? where should I add my pyqtgrapgh code in tab widget code. Corresponding code for tab widget and pyqtgraph is as follows. code for tab widget :</p> <pre><code>from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(728, 507) self.centralWidget = QtGui.QWidget(MainWindow) self.centralWidget.setObjectName(_fromUtf8("centralWidget")) self.tabWidget = QtGui.QTabWidget(self.centralWidget) self.tabWidget.setGeometry(QtCore.QRect(20, 70, 691, 371)) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab = QtGui.QWidget() self.tab.setObjectName(_fromUtf8("tab")) self.tabWidget.addTab(self.tab, _fromUtf8("")) self.tab_2 = QtGui.QWidget() self.tab_2.setObjectName(_fromUtf8("tab_2")) self.tabWidget.addTab(self.tab_2, _fromUtf8("")) self.label = QtGui.QLabel(self.centralWidget) self.label.setGeometry(QtCore.QRect(320, 20, 71, 41)) font = QtGui.QFont() font.setPointSize(14) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtGui.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 728, 21)) self.menuBar.setObjectName(_fromUtf8("menuBar")) MainWindow.setMenuBar(self.menuBar) self.mainToolBar = QtGui.QToolBar(MainWindow) self.mainToolBar.setObjectName(_fromUtf8("mainToolBar")) MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar) self.statusBar = QtGui.QStatusBar(MainWindow) self.statusBar.setObjectName(_fromUtf8("statusBar")) MainWindow.setStatusBar(self.statusBar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("MainWindow", "plot_1", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("MainWindow", "plot_2", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", " PLOTS", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>Code for pyqtgrapgh:</p> <pre><code>from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg app = QtGui.QApplication([]) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) win.setWindowTitle('pyqtgraph example: Plotting') # Enable antialiasing for prettier plots pg.setConfigOptions(antialias=True) p6 = win.addPlot(title="My Plot") curve = p6.plot(pen='r') data = np.random.normal(size=(10,10)) ptr = 0 def update(): global curve, data, ptr, p6 curve.setData(data[ptr%10]) if ptr == 0: p6.enableAutoRange('xy', False) ## stop auto-scaling after the first data set is plotted ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(500) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() </code></pre> <p>I have tried the way you have suggested me but now I am getting two windows popped up with none of them showing me the plots. I got one plotWidget in my tab Widget but how can I get rid of other plot window? Will you please tell me where I am exactly going wrong. The modified code which I am trying is as follows.</p> <pre><code>from PyQt4 import QtCore, QtGui from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): global win,curve MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(728, 507) self.centralWidget = QtGui.QWidget(MainWindow) self.centralWidget.setObjectName(_fromUtf8("centralWidget")) self.tabWidget = QtGui.QTabWidget(self.centralWidget) self.tabWidget.setGeometry(QtCore.QRect(20, 70, 691, 371)) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab = QtGui.QWidget() self.tab.setObjectName(_fromUtf8("tab")) ### self.tabWidget.insertTab(3, self.win, "plot") ### self.tabWidget.addTab(self.tab, _fromUtf8("")) self.tab_2 = QtGui.QWidget() self.tab_2.setObjectName(_fromUtf8("tab_2")) self.tabWidget.addTab(self.tab_2, _fromUtf8("")) self.label = QtGui.QLabel(self.centralWidget) self.label.setGeometry(QtCore.QRect(320, 20, 71, 41)) font = QtGui.QFont() font.setPointSize(14) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtGui.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 728, 21)) self.menuBar.setObjectName(_fromUtf8("menuBar")) MainWindow.setMenuBar(self.menuBar) self.mainToolBar = QtGui.QToolBar(MainWindow) self.mainToolBar.setObjectName(_fromUtf8("mainToolBar")) MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar) self.statusBar = QtGui.QStatusBar(MainWindow) self.statusBar.setObjectName(_fromUtf8("statusBar")) MainWindow.setStatusBar(self.statusBar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("MainWindow", "plot_1", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("MainWindow", "plot_2", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", " PLOTS", None, QtGui.QApplication.UnicodeUTF8)) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) win.setWindowTitle('pyqtgraph example: Plotting') # Enable antialiasing for prettier plots pg.setConfigOptions(antialias=True) p6 = win.addPlot(title="My Plot") curve = p6.plot(pen='r') data = np.random.normal(size=(10,10)) ptr = 0 def update(): global curve, data, ptr, p6 curve.setData(data[ptr%10]) if ptr == 0: p6.enableAutoRange('xy', False) ## stop auto-scaling after the first data set is plotted ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(500) if __name__ == "__main__": import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>I am also getting an error like - NameError: global name 'curve' is not defined Segmentation fault (core dumped) Will you please tell me how to get rid of this error.</p> |
5,042,647 | 0 | <p>I store all data in the database (including last crawl date and post dates) and take all dates I need from database.</p> |
35,851,670 | 0 | <p>Access to a KML file can not be done locally each service based on google it must be made by means of a publicly accessible server on the Internet. it tries to place your file on a server accessible from the internet (there are also free services)</p> <p>this form google maps developer </p> <blockquote> <p>Your file is hosted publicly on the internet. This is a requirement for all applications loading KML into a KMLLayer. Google's servers need to be able to find and retrieve the content in order to display it on the map - this also means that the file can't be on a password-protected page.</p> </blockquote> <p><a href="https://developers.google.com/maps/tutorials/kml/#your_kml_file" rel="nofollow">https://developers.google.com/maps/tutorials/kml/#your_kml_file</a></p> |
7,070,626 | 0 | Multiple primary keys with Doctrine 1 and Symfony 1? <p>I already know that's not possible to work with multiple primary keys in Symfony 1 and Doctrine 1, but do you guys know any good workarounds?</p> |
14,108,374 | 0 | The condition doesn't seem to work. (while (dAmount != (2*dbAmount))) Also, the first calculation isn't correct o.O <p>My friend and I are learning C++, and we can't seem to get this program running as it should be. So basically, what we are now attempting, is a tasks that requires us to script a program in which the user is asked two variables. One of these variables is a tax percentage (in the form of 1.X) and the other is any positive, real number. Now what it is we need to know, is why our condition isn't prompting? We would really appreciate an answer to our question. Here is the code:</p> <pre><code> #include <iostream> #include <iomanip> #include <ctype.h> #include <math.h> #include <cstdlib> using namespace std; int main() { double dTax; double dbAmount; double dAmount; cout << "Tax? (In the form of 1.05)" << endl; cin >> dTax; cout << "Amount?" << endl; cin >> dbAmount; cout << dbAmount << " is the amount without taxes incalculated." << endl; dAmount = (dbAmount*dTax); while (dAmount != (2*dbAmount)) { dAmount = (dAmount*dTax); cout << dAmount << " is the next amount, with taxes incalculated." << endl; break; } cin.get(); return 0; } </code></pre> |
3,291,396 | 0 | What is an attached event? <p>I am learning WPF, and I've run into a term called "Attached Event". I have not been able to find a good resource that isn't confusing.</p> <p>Can anyone tell me what an attached event is and what it does?</p> |
5,051,877 | 0 | <p>To return javascript to be executed directly in the client, like the Rails erb.js template, the best method would be to return a JavaScriptResult from the controller method</p> <pre><code>public ActionResult AjaxMethod() { /* do stuff */ return JavaScript(script); </code></pre> <p>}</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.javascriptresult.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.web.mvc.javascriptresult.aspx</a></p> |
35,192,846 | 0 | How to style a WordPress widget area? <p>I registered a couple new widget areas above my content and below entries, and I'm having trouble styling them. The classes are <code>above_content</code> and <code>after_entry</code> but making an <code>.above_content</code> and <code>.after_entry</code> class in my stylesheet isn't affecting them. Any ideas? I'm just trying to align then and add padding. <a href="http://gleefulthings.com/WPtestblog" rel="nofollow">My test site</a></p> <p>This is the code I used to register the widget area</p> <pre><code>genesis_register_sidebar( array( 'id' => 'after_entry', 'name' => __( 'After Entry', 'domain' ), 'description' => __( 'After Entry', 'domain' ), ) ); add_action( 'genesis_entry_footer', 'your_widget2' ); function your_widget2() { if ( is_active_sidebar('after_entry') ) { genesis_widget_area( 'after_entry', array( 'before' => '<div class=“after_entry widget-area">', 'after' => '</div>', ) ); } } </code></pre> |
34,956,067 | 0 | <p>Solved by using a different plugin: <a href="http://fengyuanchen.github.io/cropper/" rel="nofollow">http://fengyuanchen.github.io/cropper/</a></p> |
39,008,840 | 0 | <p>when the browser gets smaller you add col-sm-1 and col-xs-1 in to all class.</p> <pre><code> <div class="row wrapper"> <span class="prev-slide col-md-1 col-sm-1 col-xs-1"/> <ul class="tab-container row col-md-10"> <li class="col-md-1 col-sm-1 col-xs-1">Slide 1</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 2</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 3</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 4</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 5</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 6</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 7</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 8</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 9</li> <li class="col-md-1 col-sm-1 col-xs-1">Slide 10</li> </ul><span class="next-slide col-md-1 col-sm-1 col-xs-1">></span> </div> </code></pre> |
16,236,337 | 0 | <p>Create 2 OLE DB Connection Managers. Name them Production and Archive and have them point to the correct servers and database. These CMs are what SSIS uses to push and pull data from the databases.</p> <p>Add a Data Flow Task. A DFT is the executable that will allow row by row manipulation of the data. Double click on the Data Flow Task. Once inside, add an OLE DB Source and and OLE DB Destination to the canvas. The OLE DB Source is where the data will come from while the OLE DB Destination provides the insert power. </p> <p>The logic you would want to implement is a <a href="http://stackoverflow.com/questions/15503959/ssis-foreach-through-a-table-insert-into-another-and-delete-the-source-row/15508174#15508174">Delete first</a> approach, much as I outlined in the other answer.</p> <pre><code>DELETE DF OUTPUT DELETED.* FROM dbo.DeleteFirst AS DF WHERE DF.RecordDate > dateadd(y, 3, current_timestamp); </code></pre> <p>This query will delete all the rows older than 3 years <em>and</em> push them into the dataflow. In your OLE DB Source, make the following configuration changes</p> <ol> <li>change the Connection Manager from <code>Archive</code> to <code>Production</code></li> <li>change the query type from "Table or View" to "Query" </li> <li>paste your query and click the Columns tab to double check the query parsed</li> </ol> <p>Connect the OLE DB Source to the OLE DB Destination. Double click on the OLE DB Destination and configure it</p> <ol> <li>Verify the Connection Manager is the <code>Archive</code></li> <li>Ensure the Access Mode is "Table or View - Fastload" (name approximate)</li> <li>You might need to check the Retain IDs based on your table design - if you have identity column, then do check it if you want ID 10 from the production system to be ID 10 in the Archive system</li> <li>Select the actual table</li> <li>On the Mapping tab, ensure that all the columns mapped. It does this automatically by matching names so there shouldn't be a problem.</li> </ol> <p>If you do not need to span an instance, the above logic can be condensed into a single <code>Execute SQL Task</code></p> <pre><code>DELETE DF OUTPUT DELETED.* INTO ArchiveDatabase.dbo.DeleteFirst FROM dbo.DeleteFirst AS DF WHERE DF.RecordDate > dateadd(y, 3, current_timestamp); </code></pre> <p>Also note with this approach that if you have identity columns you will need to provide an explicit column list and turn on and off the IDENTITY_INSERT property.</p> |
6,042,564 | 0 | ConfirmationDialog Primefaces <p>..Now I come across a question.</p> <pre><code><tabview> <tab>... </tab> <tab>... </tab> <tab>... </tab> <tab id="p"> <h:form id="qorm"> <h:panelGroup > <p:commandButton value="Save" actionListener="#{...}" update="priorityDataTable" /> <p:commandButton id="cancelButton" value="Cancel" onclick="confirmation.show()" type="button" /> </h:panelGroup> <p:dataTable id="priorityDataTable" styleClass="priorityDataTable" selection="#{...selectedJobQueue}" rowSelectListener="#{...onRowSelect}" selectionMode="single" value="#{....priorityList}" var="priority" > <p:column> <f:facet name="header"> Request<br />Number </f:facet> <h:outputText value="#{priority.reworkRequest.requestNumber}" /> </p:column> <p:column> <f:facet name="header"> # </f:facet> <h:outputText value="#" /> </p:column> <p:column> <f:facet name="header"> Status </f:facet> <h:outputText value="#{priority.priorityStatus.getTextValue()}" /> </p:column> </p:dataTable> <h:panelGroup class="queuePriorityActionButton"> <p:commandButton id="moveUpButton" value="Move Up" actionListener="#{....moveUp()}" /> <p:commandButton id="moveDownButton" value="Move Down" actionListener="#{....moveDown()}" /> </h:panelGroup> </h:form> <h:form> <p:confirmDialog message="All updates since your last save will be lost. Are you sure you want to exit?" modal="true" header="Initiating destroy process" severity="alert" widgetVar="confirmation"> <p:commandButton value="Yes Sure" update="queuePriorityForm:priorityDataTable " oncomplete="confirmation.hide()" actionListener="{....resetBack()}" /> <p:commandButton value="Not Yet" onclick="confirmation.hide()" type="button" /> </p:confirmDialog> </h:form> </tab> </tabview> </code></pre> <p>when user change the priority of the table, and the user moves a request(s) and then selects another tab without saving the request.Must display a confirmationDialog. So I don't know how to do it.AnyOne can help me</p> |
22,515,737 | 0 | <p><a href="http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python">This</a> will help you to list all the files in the directory. </p> <p>Then for each file, </p> <ol> <li>Iterate thru all the lines</li> <li>See if the current line starts with CONCLUSION:</li> <li>Do a substring on that line to get all the contents after the word CONCLUSION:</li> </ol> |
6,523,827 | 0 | <p>If you want to draw directly on the form, there are many tutorials and examples:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/aa287594%28v=vs.71%29.aspx" rel="nofollow">Code: Drawing Graphics on a Windows Form (Visual C#)</a></li> <li><a href="http://www.techotopia.com/index.php/Drawing_Graphics_in_C_Sharp" rel="nofollow">Techtopia: Drawing Graphics in C Sharp</a></li> <li><a href="http://www.homeandlearn.co.uk/csharp/csharp_s15p1.html" rel="nofollow">Graphics in Visual C# .NET</a></li> <li><a href="http://www.codeguru.com/csharp/csharp/cs_graphics/customizinguserinterfaces/article.php/c6147" rel="nofollow">Codeguru: Getting Graphics to stay on a Form (C#)</a></li> </ul> <p>If you are just trying to set a form to use a particular image, you might consider placing a <code>PictureBox</code> and setting its .Image property to that of your generated graphic:</p> <pre><code>pictureBox1.Image = myBitmap; </code></pre> <p>There is also the form's <code>.BackgroundImage</code> property:</p> <pre><code>form1.BackgroundImage = myBitmap; </code></pre> <p>The white background with red cross means that the requested resource is unavailable or not in a recognized format.</p> <p>Do you need to generate a new graphic every time the form is redrawn? If so, then the <code>Paint</code> event is fine, but that may be why things are taking a long time; i.e. lots of redraws whenever the form is invalidated. If the map doesn't need to change then one of the above suggestions would probably be better.</p> <p>If redrawing the graphic is the intention, then it would be necessary to discuss how you are generating the graphic in order to diagnose the problem. Because of the red "X" problem you are having, it's possible the graphic is not in the correct format, so it may help to post some of that code for further assistance.</p> |
38,899,314 | 0 | Highcharts thinks all dates are 1970-01-01, despite them being valid epoch times <p>I'm working with this simple chart:</p> <p><a href="https://jsfiddle.net/w7uyghqn/2/" rel="nofollow">https://jsfiddle.net/w7uyghqn/2/</a></p> <p>My dates are in the format: <code>Date(1447793679000)</code>, which translates correctly to <code>Thu Aug 11 2016 10:26:59 GMT-0400 (EDT)</code>. </p> <pre><code>var seriesOptions = [ { "data":[ [Date(1447793679000), 7.8494623656], [Date(1450913358000), 5.4140127389], [Date(1460475392000), 6.015037594], [Date(1460648544000), 3.75], [Date(1460753244000), 2.1015761821], [Date(1460985174000), 3.0141843972], [Date(1460988174000), 5.2264808362], [Date(1461874589000), 1.5100671141] ], "name":"Product 1" }, { "data":[ [Date(1450729647000), 2.9850746269], [Date(1452184898000), 4.1666666667], [Date(1454616863000), 4.1749502982], [Date(1455206741000), 2.6717557252], [Date(1458062356000), 2.4], [Date(1459868909000), 3.8461538462], [Date(1459882015000), 3.3955857385], [Date(1459968893000), 4.1832669323], [Date(1460574864000), 4.973357016], [Date(1460665314000), 5.2032520325] ], "name":"Product 2" } ] </code></pre> <p>However, as you can see on the x-axis, this is all Jan 1st 1970. Can anyone spot what's wrong?</p> <p>I've tried so many different formats and I'm totally tearing my hair out. </p> |
27,392,894 | 0 | How to find data by dynamic conditions on Rails? <p>I am using Rails 3.2.13 now.</p> <p>I made this method:</p> <pre><code>def search search_conditions = [] search_conditions << ["id = ?", params[:id]] if params[:id] != '' search_conditions << ["name LIKE ?", "%#{params[:name]}%"] if params[:name] != '' @users = User.find(:all, :conditions => search_conditions) end </code></pre> <p>But the result was:</p> <pre><code>undefined method `%' for ["name LIKE ?", "%tes%"]:Array </code></pre> <p>Can't I set multiple conditions in a nice way?</p> |
24,897,853 | 0 | <p>Check again <code>FieldError</code> constructor, according to JavaDocs, 3rd parameter is rejected field value:</p> <pre><code>rejectedValue - the rejected field value </code></pre> <p>The exact part of code which overrides value is in <code>AbstractBindingResult</code> class:</p> <pre><code>public Object getFieldValue(String field) { FieldError fieldError = getFieldError(field); // Use rejected value in case of error, current bean property value else. Object value = (fieldError != null ? fieldError.getRejectedValue() : getActualFieldValue(fixedField(field))); // Apply formatting, but not on binding failures like type mismatches. if (fieldError == null || !fieldError.isBindingFailure()) { value = formatFieldValue(field, value); } return value; } </code></pre> <p>So while you provide <code>FieldError</code> class with null <code>rejectedValue</code>, the form field is cleared. As or me, I've always used <code>rejectValue</code> instead of <code>addError</code>:</p> <pre><code>result.rejectValue( "field", "errorCode" ); </code></pre> |
18,483,419 | 0 | Selenium sendkeys drops character with Chrome Driver <p>Selenium sendkeys with Chrome Driver drops character "2" and "4". Other characters are OK. When I use other browser (IE or FF), everything is OK.</p> <p>code:</p> <pre><code>WebElement name = driver.findElement(localizator); name.clear(); name.sendKeys("1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"); </code></pre> <p>result: input box is filled with</p> <pre><code>13567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ </code></pre> <p>Characters <code>2</code> and <code>4</code> are missing, other characters are filled correctly.</p> <p>I use Windows 7 64bit, Chrome version 29.0.1547.57 m, ChromeDriver win32 (v2.2.215849.dyu) - the newest one.</p> |
18,002,992 | 0 | <p>You could try to put it in a document.ready call. And as Samuel Reid pointed out, a hover function is what you need. Like so:</p> <pre><code>$(document).ready(function () { $('.baixo-tudo').find('.botao').each(function (i) { var imge = $('img'); var t = $('.botao'), src1 = t.find('.src1').text(), src2 = t.find('.src2').text(); imge.hover(function () { t.attr('src', src1); }, function () { t.attr('src', src2); }); }); }); </code></pre> <p>EDIT, building on your fiddle.</p> <p>I am guessing <a href="http://jsfiddle.net/NnUe6/5/" rel="nofollow">this</a> is what you want?</p> <pre><code>$('.baixo-tudo').find('.botao').each(function (i) { var t = $(this), imge = t.children("img"), src1 = t.children('.src1').text(), src2 = t.children('.src2').text(); imge.mouseover(function () { imge.attr('src', src1); }); imge.mouseout(function () { imge.attr('src', src2); }); }); </code></pre> <p>And even <a href="http://jsfiddle.net/NnUe6/6/" rel="nofollow">shorter</a>.</p> <pre><code>$('.baixo-tudo').find('.botao').each(function (i) { var t = $(this), imge = t.children("img"), src1 = t.children('.src1').text(), src2 = t.children('.src2').text(); imge.hover(function () { imge.attr('src', src1); }, function () { imge.attr('src', src2); }); }); </code></pre> |
485,780 | 0 | <blockquote> <p>I have heard somewhere that a computer can have multiple IP addresses. I want the one that other programs on different computers can use to connect to the computer.</p> </blockquote> <p>Well... that could be any of them. If a computer has multiple IP addresses it can be accessed on any one of them. Of course one of them could be subject to different firewall rules or they could be on two completely different segments but there's no way to detect any and all of these circumstances.</p> |
28,884,674 | 0 | If statement checking if current date equals string date <p>trying to retrieve users from an ArrayList that string bookingdate equals the current date. my problem is I don't believe I am formatting my if statement correctly. the returned users will then be displayed on a datatable in a xhtml file.</p> <pre><code> public ArrayList<User> getDinner() throws ParseException { Date today = new Date(); DateFormat formatter; Date date; formatter = new SimpleDateFormat("dd/MM/yy"); date = formatter.parse(bookingdate); ArrayList<User> subset = new ArrayList<User>(); for (User user : userList) { if (((today.equals(date))) && (1700 < user.bookingtime)) { subset.add(user); } } return subset; } </code></pre> <p>above is where I am having the problem below is the rest of the file.</p> <pre><code>import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import java.io.Serializable; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ValueChangeEvent; @ManagedBean(name = "user") @SessionScoped public class UserData implements Serializable {private static final long serialVersionUID = 1L; private String name; private String last; private String email; private String phone; private String size; Integer bookingtime; String bookingdate; private String requirements; private String table; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLast() { return last; } public void setLast(String last) { this.last = last; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public Integer getBookingtime() { return bookingtime; } public void setBookingtime(Integer bookingtime) { this.bookingtime = bookingtime; } public String getBookingdate() { return bookingdate; } public void setBookingdate(String bookingdate) { this.bookingdate = bookingdate; } public String getRequirements() { return requirements; } public void setRequirements(String requirements) { this.requirements = requirements; } public void settable(String table) { this.table = table; } public String gettable() { return table; } private static final ArrayList<User> userList = new ArrayList<User>(Arrays.asList( new User("Janet", "Harris", "[email protected]", "07714662361", "3", 1910, "12/05/2015", "Flowers", null), new User("Amy", "Harris", "[email protected]", "07714662361", "4", 1930, "05/03/2015", "Vegan", null), new User("Louise", "Hardbattle", "[email protected]", "01512242901", "6", 1600, "13/05/2015", "Friends birthday", null), new User("Mark", "Jenkins", "[email protected]", "07866406591", "2", 1900, "13/05/2015", "N/A", null), new User("Peter", "Lunn", "[email protected]", "01514422398", "2", 1930, "13/05/2015", "First time here", null), new User("Lee", "Allen", "[email protected]", "07861106591", "2", 1945, "13/05/2015", "N/A", null), new User("Jess", "Maloney", "[email protected]", "07713980273", "5", 1300, "14/05/2015", "18th birthday party - please provide balloons", null), new User("Christian", "Riley", "[email protected]", "01514442938", "4", 1400, "14/05/2015", "N/A", null), new User("Carl", "Lunt", "[email protected]", "07844408012", "2", 1430, "14/05/2015", "N/A", null), new User("Peter", "Moore", "[email protected]", "01512324289", "2", 1830, "14/05/2015", "Anniversary", null ))); public ArrayList<User> getCustomers() { return userList; } public ArrayList<User> getDinner() { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); ArrayList<User> subset = new ArrayList<User>(); for (User user : userList) { if (( user.bookingdate.equals(df) ) &&(1700 < user.bookingtime)) { subset.add(user); } } return subset; } public ArrayList<User> getLunch() { ArrayList<User> subset = new ArrayList<User>(); for (User user : userList) { if (1700 > user.bookingtime) { subset.add(user); } } return subset; } public ArrayList<User> getSearch() { ArrayList<User> subset = new ArrayList<User>(); for (User user : userList) { if (userName.equals(user.bookingdate) || user.bookingdate == null) { subset.add(user); } } return subset; } public String saveAction() { //get all existing value but set "editable" to false for (User user : userList) { user.setEditable(false); } //return to current page return null; } public String editAction(User user) { user.setEditable(true); return null; } public String deleteAction(User user) { userList.remove(user); return null; } public String addAction() { User user = new User(this.name, this.last, this.email, this.phone, this.size, this.bookingtime, this.bookingdate, this.requirements, null); userList.add(user); return null; } </code></pre> |
16,287,000 | 0 | <p>I think the easiest way is to map the id to the name directly where you use it, as follows:</p> <pre><code>svg.selectAll("text") [...] .text( function(d) { return namesMap[d.name]; }); </code></pre> <p>assuming that <code>namesMap</code> converts <code>node_id</code> to <code>node_name</code>.</p> <p>Now you just have to create aforementioned <code>namesMap</code>, e.g. like this:</p> <pre><code>d3.csv("nodes.csv", function(names) { var namesMap = {}; names.forEach(function(d) { namesMap[d.node_id] = d.node_name; }); // code using namesMap goes here }); </code></pre> <p>A slighly modified code (with the csv data loading from <code><pre></code> nodes in HTML) is available in <a href="http://jsfiddle.net/v2UHg/1/" rel="nofollow">this fiddle</a>.</p> |
10,777,770 | 0 | How can I declare a global require in NodeJS? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/5447771/node-js-global-variables">node.js global variables?</a> </p> </blockquote> <p>How can i include a file or a script in node js, that i can access it global. I would like to extend the standard Array Object with some functions, but i dont like to do this in app.js and wenn i declare it in a module, it is not possible to access it global.</p> <p>Is there a possibility with a other command to do this?</p> |
27,337,715 | 0 | how do I create search bar which will update search on typing <p>I created an application with the search on button click. How do I create search bar which will update search on typing letter? Something similar like in a google chrome. I was looking for an answer but I could not find it. Tnx a lot! </p> <p>SearchableDictionary.java </p> <pre><code>package com.bogdanskoric.searchdictionary; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class SearchableDictionary extends Activity { private TextView mTextView; private ListView mListView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.text); mListView = (ListView) findViewById(R.id.list); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction())) { // handles a click on a search suggestion; launches activity to show word Intent wordIntent = new Intent(this, WordActivity.class); wordIntent.setData(intent.getData()); startActivity(wordIntent); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // handles a search query String query = intent.getStringExtra(SearchManager.QUERY); showResults(query); } } /** * Searches the dictionary and displays results for the given query. * @param query The search query */ private void showResults(String query) { Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null, new String[] {query}, null); if (cursor == null) { // There are no results mTextView.setText(getString(R.string.no_results, new Object[] {query})); } else { // Display the number of results int count = cursor.getCount(); String countString = getResources().getQuantityString(R.plurals.search_results, count, new Object[] {count, query}); mTextView.setText(countString); // Specify the columns we want to display in the result String[] from = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION }; // Specify the corresponding layout elements where we want the columns to go int[] to = new int[] { R.id.word }; // Create a simple cursor adapter for the definitions and apply them to the ListView SimpleCursorAdapter words = new SimpleCursorAdapter(this, R.layout.result, cursor, from, to); mListView.setAdapter(words); // Define the on-click listener for the list items mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Build the Intent used to open WordActivity with a specific word Uri Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class); Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI, String.valueOf(id)); wordIntent.setData(data); startActivity(wordIntent); finish(); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searchable_dictionary, menu); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.search: onSearchRequested(); return true; default: return false; } } } </code></pre> <p>DictionaryDatabase.java</p> <pre><code>package com.bogdanskoric.searchdictionary; import android.app.SearchManager; import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; public class DictionaryDatabase { private static final String TAG = "DictionaryDatabase"; //The columns we'll include in the dictionary table public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1; public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2; private static final String DATABASE_NAME = "dictionary"; private static final String FTS_VIRTUAL_TABLE = "FTSdictionary"; private static final int DATABASE_VERSION = 2; private final DictionaryOpenHelper mDatabaseOpenHelper; private static final HashMap<String,String> mColumnMap = buildColumnMap(); public DictionaryDatabase(Context context) { mDatabaseOpenHelper = new DictionaryOpenHelper(context); } private static HashMap<String,String> buildColumnMap() { HashMap<String,String> map = new HashMap<String,String>(); map.put(KEY_WORD, KEY_WORD); map.put(KEY_DEFINITION, KEY_DEFINITION); map.put(BaseColumns._ID, "rowid AS " + BaseColumns._ID); map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); return map; } public Cursor getWord(String rowId, String[] columns) { String selection = "rowid = ?"; String[] selectionArgs = new String[] {rowId}; return query(selection, selectionArgs, columns); } public Cursor getWordMatches(String query, String[] columns) { String selection = KEY_WORD + " MATCH ?"; String[] selectionArgs = new String[] {query+"*"}; return query(selection, selectionArgs, columns); } private Cursor query(String selection, String[] selectionArgs, String[] columns) { SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(FTS_VIRTUAL_TABLE); builder.setProjectionMap(mColumnMap); Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(), columns, selection, selectionArgs, null, null, null); if (cursor == null) { return null; } else if (!cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } private static class DictionaryOpenHelper extends SQLiteOpenHelper { private final Context mHelperContext; private SQLiteDatabase mDatabase; private static final String FTS_TABLE_CREATE = "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3 (" + KEY_WORD + ", " + KEY_DEFINITION + ");"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mHelperContext = context; } @Override public void onCreate(SQLiteDatabase db) { mDatabase = db; mDatabase.execSQL(FTS_TABLE_CREATE); loadDictionary(); } /** * Starts a thread to load the database table with words */ private void loadDictionary() { new Thread(new Runnable() { public void run() { try { loadWords(); } catch (IOException e) { throw new RuntimeException(e); } } }).start(); } private void loadWords() throws IOException { Log.d(TAG, "Loading words..."); final Resources resources = mHelperContext.getResources(); InputStream inputStream = resources.openRawResource(R.raw.definitions); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String line; while ((line = reader.readLine()) != null) { String[] strings = TextUtils.split(line, "-"); if (strings.length < 2) continue; long id = addWord(strings[0].trim(), strings[1].trim()); if (id < 0) { Log.e(TAG, "unable to add word: " + strings[0].trim()); } } } finally { reader.close(); } Log.d(TAG, "DONE loading words."); } public long addWord(String word, String definition) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_WORD, word); initialValues.put(KEY_DEFINITION, definition); return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE); onCreate(db); } } } </code></pre> <p>DictionaryProvider.java</p> <pre><code>package com.bogdanskoric.searchdictionary; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public class DictionaryProvider extends ContentProvider { String TAG = "DictionaryProvider"; public static String AUTHORITY = "com.bogdanskoric.searchdictionary.DictionaryProvider"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); // MIME types used for searching words or looking up a single definition public static final String WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.bogdanskoric.searchdictionary"; public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.bogdanskoric.searchdictionary"; private DictionaryDatabase mDictionary; // UriMatcher stuff private static final int SEARCH_WORDS = 0; private static final int GET_WORD = 1; private static final int SEARCH_SUGGEST = 2; private static final int REFRESH_SHORTCUT = 3; private static final UriMatcher sURIMatcher = buildUriMatcher(); /** * Builds up a UriMatcher for search suggestion and shortcut refresh queries. */ private static UriMatcher buildUriMatcher() { UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); // to get definitions... matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS); matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD); // to get suggestions... matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT); return matcher; } @Override public boolean onCreate() { mDictionary = new DictionaryDatabase(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Use the UriMatcher to see what kind of query we have and format the db query accordingly switch (sURIMatcher.match(uri)) { case SEARCH_SUGGEST: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return getSuggestions(selectionArgs[0]); case SEARCH_WORDS: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return search(selectionArgs[0]); case GET_WORD: return getWord(uri); case REFRESH_SHORTCUT: return refreshShortcut(uri); default: throw new IllegalArgumentException("Unknown Uri: " + uri); } } private Cursor getSuggestions(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, (only if you want to refresh shortcuts) */ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWordMatches(query, columns); } private Cursor search(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWordMatches(query, columns); } private Cursor getWord(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWord(rowId, columns); } private Cursor refreshShortcut(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWord(rowId, columns); } @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { case SEARCH_WORDS: return WORDS_MIME_TYPE; case GET_WORD: return DEFINITION_MIME_TYPE; case SEARCH_SUGGEST: return SearchManager.SUGGEST_MIME_TYPE; case REFRESH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; default: throw new IllegalArgumentException("Unknown URL " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } } </code></pre> <p>searchable.xml</p> <pre><code><?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android ="http://schemas.android.com/apk/res/android" android:label="@string/search_label" android:hint ="@string/search_hint" android:searchSuggestAuthority="searchdictionary.DictionaryProvider" android:searchSuggestIntentAction="android.intent.action.VIEW" android:searchSuggestIntentData="content://searchdictionary.DictionaryProvider/dictionary" android:searchSuggestSelection=" ?" android:searchSuggestThreshold="1" android:includeInGlobalSearch="true" android:searchSettingsDescription="@string/settings_description" > </searchable> </code></pre> <p>raw/definition.txt</p> <pre><code>Adikcija - Podložnost nekoj štetnoj navici, najcešce, psihofiziološka zavisnost od droge ili alkohola (toksikomanija, alkoholizam). Adolescencija - Period prelaska iz detinjstva u zrelo doba obeležen biološkim rastom, seksualnim.. etc. </code></pre> |
19,404,880 | 0 | <p>You can't parameteterize table name with PDO and MySQLi prepared statements, because SQL server needs basic information to prepare the query before executing actual query. </p> |
34,741,206 | 0 | <p>Ok, I finally used a piece of code that uses ctypes lib to provide some kind of killing thread function. I know this is not a clean way to proceed but in my case, there are no resources shared by the threads so it shouldn't have any impact ...</p> <p>If it can help, here is the piece of code that can easily be found on the net:</p> <pre><code>def terminate_thread(thread): """Terminates a python thread from another thread. :param thread: a threading.Thread instance """ if not thread.isAlive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), exc) if res == 0: raise ValueError("nonexistent thread id") elif res > 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) raise SystemError("PyThreadState_SetAsyncExc failed") </code></pre> |
4,825,949 | 0 | <p>Set the PuTTY charset to UTF-8 in the options.</p> |
13,789,208 | 0 | <p>Try this, this should work if any of the fields are empty.</p> <pre><code>if (temprature == 0 || methane == 0 || ethane == 0 || propane == 0 || nbutane == 0 || ibutane == 0 || oxygen == 0 || npetane == 0 || ipetane == 0 || nhexane == 0 || nitrogen == 0) { outputText.text = @"Please enter all values"; } else { outputText.text = resultString; } </code></pre> |
35,160,883 | 0 | Vagrant is not picking up laravel/homestead box <p>I've downloaded the homestead box manually because of much slow downloading via terminal. But after adding the box, vagrant is not finding it and attempting to download again.</p> <p><a href="https://i.stack.imgur.com/73jRU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/73jRU.jpg" alt="Vagrant find error"></a></p> |
20,370,985 | 0 | <p>As a starting point, use <code>int</code> which is probably native to the architecture and you'll avoid possible implicit conversions when comparing <code>i</code> with other bits and pieces. So my bet is that both <code>byte</code> and <code>short</code> will wind up being <em>slower</em>.</p> <p>A far cuter optimisation would be to use <code>++i</code> rather than <code>i++</code>, as the former will never be slower than the latter. (Conceptually <code>i++</code> has to return a copy even though it will be optimised out by a good java compiler).</p> |
1,887,979 | 0 | <p>In Python, you can use """ (triple-quoted strings) to embed long runs of text data in your program.</p> <p>In your case, however, don't waste time on this.</p> <p>If you have an object you've pickled, you'd be much, much happier dumping that object as Python source and simply including the source.</p> <p>The <code>repr</code> function, applied to most objects, will emit a Python source-code version of the object. If you implement <code>__repr__</code> for all of your custom classes, you can trivially dump your structure as Python source.</p> <p>If, on the other hand, your pickled structure started out as Python code, just leave it as Python code. </p> |
9,278,626 | 0 | <p>Why Can't you do some thing like below, Just fetch the user inside the closure.</p> <pre><code>Login.withNewSession { def user = grails.admin.User.read(appCtx.springSecurityService.currentUser.id) login = new Login(user: user) } </code></pre> <p>OR </p> <pre><code>Login.withTransaction{ def user = grails.admin.User.read(appCtx.springSecurityService.currentUser.id) login = new Login(user: user) } </code></pre> |
9,533,408 | 0 | Converting time so it can used in a Integer <p>I'm working on some code in VB that can get the average time from the speed of button press. I've got the maths done however I'm having a problem converting a TimeSpan declaration into a Integer where it can be divided and made into a average. Can you please help. Thanks!</p> <p>Maths for code:</p> <p><strong>2nd click</strong></p> <pre><code>click count = 2 average= current time / 1 so current = time \ click count - 1 </code></pre> <p><strong>3rd click</strong></p> <pre><code>adveragetime + Current Time \ clickcount - 1 </code></pre> <p><strong>4th click</strong></p> <pre><code>average time * (click count -2) + Current Time \ clickcount -1 </code></pre> |
23,344,254 | 0 | <p>[Adding this here since you want a way to do it purely in XAML. I think that insisting on pure XAML here is not essential and @bit's answer is the right way to go, IMO.]</p> <p>You can use style to have triggers that do the change.</p> <p>Let's say your UC is called <code>MyUC</code> and currently you have an instance of it similar to: <code><local:MyUC/></code> in some other view/UC/window. You can change the instance to look like so:</p> <pre><code><local:MyUC> <local:MyUC.Style> <Style TargetType="{x:Type local:MyUC}"> <Setter Property="DataContext" Value="{Binding SelectedItem, ElementName=MyDataGrid}"/> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=MyCheckbox, Path=IsChecked}" Value="True"> <Setter Property="DataContext" Value="{Binding APerson}"/> </DataTrigger> </Style.Triggers> </Style> </local:MyUC.Style> </local:MyUC> </code></pre> <p>I'm changing here the data context property, but you can change any other dependency property on <code>MyUC</code>.</p> <p>Again, I think this is a less favorite approach to tackle this functionality, but it's pure XAML.</p> |
Subsets and Splits