pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
26,561,014 | 0 | <p>You can use <code>array_slice()</code> for slice and <code>array_sum()</code> to calculate total then average. An example here</p> <pre><code>$values = array(1,2,3,4,5,6,7,8,9,10); foreach($values as $k=>$v){ if($k > 4){ echo $ave = array_sum(array_slice($values, $k - 5, $k)) / 5 . '<br />'; } } </code></pre> |
38,950,843 | 0 | <p>You need to you something like: </p> <pre><code>foreach ($results as $value){ $allValues = implode('", "', $value); //the above line will give us something like ("1", "Henricho"....etc) $query ='Insert into(col1, col2, col3, col4, col5, col6, col7, col8) Values("'.$allValues.'")'; //You can now execute your query echo $query."<BR />"; } </code></pre> <p><a href="http://phpfiddle.org/lite?code=%3C?php%5Cn%5Cn$results%20=%20array(%5Cn%5Ct%200%20=%3E%20array(%5Cn%5Ct%5Ct%5Ct%5Ct%5Ct%201=%3E%20%221%22,%5Cn%202=%3E%20%22Henricho%22,%5Cn%203=%3E%20%22Bruintjies%22,%5Cn%204=%3E%20%2223%22,%5Cn%205=%3E%20%22Agn%22%20,%5Cn%206=%3E%20%2210.17A%22,%5Cn%207=%3E%20%22-0.2%22,%5Cn%208=%3E%20%228%22%5Cn%5Ct%5Ct%5Ct%5Ct%20),%5Cn%5Ct%201%20=%3E%20array(%5Cn%5Ct%5Ct%5Ct%5Ct%201=%3E%20%222%22,%5Cn%202=%3E%20%22Akani%22,%5Cn%203=%3E%20%22Simbine%22,%5Cn%204=%3E%20%2223%22%20,%5Cn%205=%3E%20%22Agn%22%20,%5Cn%206=%3E%20%2210.17A%22,%5Cn%207=%3E%20%22-0.2%22%20,%5Cn%208=%3E%20%228%22%5Cn%5Ct%5Ct%5Ct%5Ct%20)%5Cn%20);%5Cn%5Cnforeach%20($results%20as%20$value)%7B%5Cn%5Cn%5Ct$allValues%20=%20implode('%22,%22',%20$value);%5Cn%20//the%20above%20line%20will%20give%20us%20something%20like%20(%221%22,%20%22Henricho%22....etc)%5Cn%20$query%20='Insert%20into(col1,%20col2,%20col3,%20col4,%20col5,%20col6,%20col7,%20col8)%5Cn%20Values(%22'.$allValues.'%22)';%5Cn%20//You%20can%20now%20execute%20your%20query%5Cn%5Ctecho%20$query.%22%3CBR%20/%3E%22;%5Cn%7D%5Cn?%3E%5Cn" rel="nofollow"><kbd><strong>Check Demo Here</strong></kbd></a></p> |
35,138,248 | 0 | ActionController known Format <p>I am having an issue with this code. It is for uploading an audio file. When I upload it I get an error saying this:</p> <pre><code>ActionController::UnknownFormat at /users/1/audios/dfdfdsdsf ============================================================ > ActionController::UnknownFormat app/controllers/audios_controller.rb, line 67 --------------------------------------------- ``` ruby 62 if @audio.errors.empty? && @audio.update_attributes(update_audio_params) 63 respond_to do |format| 64 format.html { redirect_to user_audios_path(@user) } 65 end 66 else > 67 respond_to do |format| 68 format.html { render :edit } 69 format.js { render json: { result: :failed, errors: @audio.errors } } 70 end 71 end 72 end ``` App backtrace ------------- - app/controllers/audios_controller.rb:67:in `update' Full backtrace -------------- - actionpack (4.2.3) lib/action_controller/metal/mime_responds.rb:217:in `respond_to' - app/controllers/audios_controller.rb:67:in `update' - actionpack (4.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action' - actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/rendering.rb:10:in `process_action' - actionpack (4.2.3) lib/abstract_controller/callbacks.rb:20:in `block in process_action' - activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call' - activesupport (4.2.3) lib/active_support/callbacks.rb:553:in `block (2 levels) in compile' - activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call' - activesupport (4.2.3) lib/active_support/callbacks.rb:88:in `run_callbacks' - actionpack (4.2.3) lib/abstract_controller/callbacks.rb:19:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/rescue.rb:29:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' - activesupport (4.2.3) lib/active_support/notifications.rb:164:in `block in instrument' - activesupport (4.2.3) lib/active_support/notifications/instrumenter.rb:20:in `instrument' - activesupport (4.2.3) lib/active_support/notifications.rb:164:in `instrument' - actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:30:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/params_wrapper.rb:250:in `process_action' - activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:18:in `process_action' - actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process' - actionview (4.2.3) lib/action_view/rendering.rb:30:in `process' - rack-mini-profiler (0.9.8) lib/mini_profiler/profiling_methods.rb:106:in `block in profile_method' - actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch' - actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' - actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:76:in `dispatch' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:45:in `serve' - actionpack (4.2.3) lib/action_dispatch/journey/router.rb:43:in `block in serve' - actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `serve' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:821:in `call' - warden (1.2.3) lib/warden/manager.rb:35:in `block in call' - warden (1.2.3) lib/warden/manager.rb:34:in `call' - rack (1.6.4) lib/rack/etag.rb:24:in `call' - rack (1.6.4) lib/rack/conditionalget.rb:38:in `call' - rack (1.6.4) lib/rack/head.rb:13:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call' - rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' - rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call' - activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call' - activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' - activerecord (4.2.3) lib/active_record/migration.rb:377:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' - activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks' - actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' - better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call' - better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call' - better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' - web-console (2.2.1) lib/web_console/middleware.rb:39:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' - railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app' - railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged' - railties (4.2.3) lib/rails/rack/logger.rb:20:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call' - rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' - rack (1.6.4) lib/rack/runtime.rb:18:in `call' - activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' - rack (1.6.4) lib/rack/lock.rb:17:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call' - rack (1.6.4) lib/rack/sendfile.rb:113:in `call' - rack-mini-profiler (0.9.8) lib/mini_profiler/profiler.rb:282:in `call' - railties (4.2.3) lib/rails/engine.rb:518:in `call' - railties (4.2.3) lib/rails/application.rb:165:in `call' - rack (1.6.4) lib/rack/content_length.rb:15:in `call' - puma (2.12.2) lib/puma/server.rb:539:in `handle_request' - puma (2.12.2) lib/puma/server.rb:386:in `process_client' - puma (2.12.2) lib/puma/server.rb:269:in `block in run' - puma (2.12.2) lib/puma/thread_pool.rb:106:in `block in spawn_thread' </code></pre> <p>It might have to do with the respond_to block. Here is the code of that bellow:</p> <pre><code>def update if params[:audio][:attachment].blank? && update_image_params.present? @audio.update_audio_cover_picture update_image_params["photo"] end if @audio.errors.empty? && @audio.update_attributes(update_audio_params) respond_to do |format| format.html { redirect_to user_audios_path(@user) } end else respond_to do |format| format.html { render :edit } format.js { render json: { result: :failed, errors: @audio.errors } } end end end </code></pre> <p>This is a copy of the same code I use for my other project. It completely works on that app:</p> <pre><code>def update if params[:book][:attachment].blank? && update_image_params.present? @book.update_book_cover_picture update_image_params["photo"] end if @book.errors.empty? && @book.update_attributes(update_book_params) respond_to do |format| format.html { redirect_to user_books_path(@user) } format.json { render json: { result: :success, url: user_books_url(@user) } } end else respond_to do |format| format.html { render :edit } format.js { render json: { result: :failed, errors: @book.errors } } end end end </code></pre> |
36,473,069 | 0 | <pre><code>$('option:checked') </code></pre> <p>in my project, i used the above for instead.</p> <p><a href="http://jsbin.com/diqisa/edit?html,js" rel="nofollow">demo</a></p> |
7,909,009 | 0 | <p>Before I give my explanation, let me say that most pure REST extremists will deride it to the ends of the earth. I don't agree with them, as i'd rather get something done, but just so you know.</p> <p>WADL is a description of a web service API, a little like WSDL is for SOAP type web services, that is designed to be more in tune with RESTful interfaces (something WSDL is poor at).</p> <p>It's primary usage in my experience is to allow you to generate client code that can call the service (handy if it's a very large API, which literally saves hours of work). It also serves the purpose of documenting a REST-like interface.</p> |
8,946,212 | 0 | <p>try:</p> <pre><code>myWords=['some', 'supplied','words'] theTextContents='a string that might or might not have all of some supplied words' goodElements=[] splitted = theTextContents.split() if all(word in splitted for word in myWords): goodElements.append(theTextContents) </code></pre> |
31,280,214 | 0 | <p>If the global or local core.autocrlf setting is not getting the results that you want, you can set a git line ending attribute and force the result that you are looking for.</p> <pre><code># Set eol conversions on all text-based files to 'nothing' echo '* text' >> .gitattributes # Force git to re-scan dir rm .git/index git reset # Review current files git status </code></pre> <p>Note: Normally the eol setting would be:</p> <pre><code>* text=auto </code></pre> |
24,403,867 | 1 | Wait for song played outside of python to finish <p>I am trying to wait for a song to finish to play the next song. </p> <p>I am running python 3.4 on windows but am trying to be able to use it on Linux (<code>raspberry pi</code>). </p> <p>I have used the command <code>subprocess.call([PLAYER, SONG])</code> to open the mp3 file. It plays in vlc and then stops. I know that I have not incorporated anything for the program to tell python when its finished. </p> <p>That's where you guys come in. I want to find a command that will wait until the song has finished and when the song is finished, the rest of the code will process. </p> <p>I would like the command to be able to used on a Linux operating system and I am trying not to have to install any modules. </p> <p>If modules are definitely needed, I will install them. </p> |
20,950,069 | 0 | <p>If process terminates then Yes, but that does not happen very often. Android is designed to keep processes in background to start them quickly once user want to go back to you app. </p> <p>You should not rely that your app will be terminated to fix some memory leaks. There are tools to fix them, like dumping HPROF file and using memory analyzer, also using weak references, and using good programming practicies - mostly not leaking activities.</p> <p>[edit] - there are resources that are not always freed on process end, while working with android TTS apis, I found that after few app crashes I have to reset device to be able to use svox voices.</p> |
7,031,525 | 0 | <p>try this:</p> <p>var works = x.ToArray().Select(c => (byte)c).ToArray();</p> |
29,947,725 | 0 | <p>Hi your code looks correct. Here's an working example of my paging.</p> <pre><code>initComponent: function () { var me = this; me.store = Ext.create('Desktop.children.store.childrenStore'); me.columns = [ { text : 'Nachname', dataIndex: 'lastName', flex: 1 }, { text : 'Vorname', dataIndex: 'firstName', flex: 1 }, { text : 'Gruppe', //name: 'group_id', dataIndex: 'groupName', flex: 1 }, { text : 'Faktor', //name: 'group_id', dataIndex: 'factorName', flex: 1 }, { xtype: 'datecolumn', text : 'Geburtsdatum', dataIndex: 'birthdate', format: 'd.m.Y', flex: 1 }, { text : 'Status', //name: 'group_id', dataIndex: 'isActive', flex: 1 }, { xtype: 'actioncolumn', width: 60, menuDisabled: true, items: this.LoadControlBar() } ]; me.plugins = [{ ptype:'saki-gridsearch' ,searchText: 'Suchen' ,autoTipText: 'Mindestens zwei Zeichen' ,selectAllText: 'Selektiere alle' }]; me.bbar = me.paging = Ext.create('Ext.toolbar.Paging', { store:me.store ,displayInfo:true }); me.tbar = [ { xtype: 'button', id:'child_btn_add', text:'Kind hinzufügen', tooltip:'Neues Kind hinzufügen', iconCls:'add', hidden: (CheckPermission('Desktop.children.view.Mainwindow') != "WRITE"), handler:function(view, e){ this.fireEvent('AddChildren', view, e); } }, { xtype: 'button', id: 'btnChildExport', text: 'Liste exportieren', tooltip: 'Spezifische Liste exportieren', iconCls: 'exportList', handler: function(view, e){ this.fireEvent('ExportList', view, e); } } ]; me.callParent(); }, </code></pre> <p>store:</p> <pre><code>Ext.define('Desktop.children.store.childrenStore', { extend: 'Ext.data.Store', id: 'childrenStore', alias: 'widget.childrenStore', requires: [ 'Desktop.children.model.childrenModel', 'Ext.data.proxy.Memory', 'Ext.data.reader.Array' ], model: 'Desktop.children.model.childrenModel', //autoLoad:true, pageSize: 10, proxy: { type:'ajax', enablePaging: true, url:'resources/php/json.php', headers: { 'Content-Type': 'application/json' }, extraParams:{ data : JSON.stringify({ module : "children", action : "load", jsonObject : null}), start: 0, limit: 10, }, reader:{ type:'json', rootProperty: 'Anfang' } }, sorters: [{ property : 'lastName', direction:'ASC' }], }); </code></pre> |
37,736,662 | 1 | Django Best Practice for Handling Related Model Objects Between Apps <p>I have a project that has 2 different apps. One handles a site's performance metrics and the other estimates site's workload. The workload app has some dependencies on the performance app. However, I am trying to avoid creating a dependency from the metrics app to the workload app in order to better encapsulate the metrics app as stand-alone. For example, metrics has this model:</p> <pre><code># models.py in metrics app: class Site(models.Model): site_name = models.CharField(max_length=255) site_geography = models.CharField(max_length=255) slug = AutoSlugField(populate_from='site_name', unique=True, null=True) </code></pre> <p>Workload app has objects such as (some omitted for brevity):</p> <pre><code># models.py in workload app: class Resource (models.Model): name_first = models.CharField(max_length=60) name_last = models.CharField(max_length=60) address_street = models.CharField(max_length=80, blank=True) address_city = models.CharField(max_length=40, blank=True) address_state = models.CharField(max_length=2, blank=True) sites = models.ManyToManyField(metrics_models.Site, through='ResourceSiteRelationship', blank=True, related_name='resources') class Activity (models.Model): activity_name = models.CharField(max_length=255) hours = models.DecimalField(max_digits=5, decimal_places=2) travel = models.BooleanField() description = models.TextField(blank=True) class ResourceSiteRelationship (models.Model): roles = models.ManyToManyField(Role, blank=True, related_name='resource_site_relationships') resource = models.ForeignKey(Resource, on_delete=models.CASCADE, blank=True, null=True, related_name='resource_site_relationships') site = models.ForeignKey(metrics_models.Site, on_delete=models.CASCADE, blank=True, null=True, related_name='resource_site_relationships') </code></pre> <p>Site should also have the following field relationship:</p> <pre><code>activities = models.ManyToManyField(Activity, related_name='sites', blank=True) </code></pre> <p>Is it best to add that field to the metric's app's instance of Site? Is it better to create a one-to-one class for Site in the workload app and extend like so:</p> <pre><code>class Site(models.Model): site = models.OneToOneField(metrics_models.Site, on_delete=models.CASCADE) activities = models.ManyToManyField(Activity, related_name='sites', blank=True) </code></pre> <p>Or is there another way to do this?</p> |
26,613,338 | 0 | Fire a method after transclude has finished <p>I have an Angular directive that creates an accordion out of <code><ol></code> and <code><li></code> elements, with each <code><li></code>'s content being wrapped in a transcluded template. I need to fire a method to check if any of these <code><li></code> elements has an error, and open that accordion, but I can't find a way to fire the method <em>after</em> the elements have been transcluded. </p> <p>Is there a hook or directive config that will time this correctly?</p> |
12,277,308 | 0 | <p>I would suggest you to send a TVP (table value parameter) back to the server. After that your query could be done like:</p> <pre><code>SELECT p.ProductId, Name, Description, {other columns} FROM Products p left join @ExceptedProducts ep on p.ProductId=ep.ProductId WHERE where ep.ProductId is null </code></pre> <p>This should be the fastest and cleanest way.</p> |
31,366,881 | 0 | <p>Just remove .png from the image strings </p> <pre><code>let TopButtonImageNamesBlue = [ "Aquarium Icon Blue", "Bugs Icon Blue", "Ancient World Icon Blue", "World Cultures Icon Blue", "Dinosaurs Icon Blue", "Space Icon Blue"] </code></pre> <p>Here is my working code :</p> <pre><code> var images = ["01","02","03"] var image : UIImage? = UIImage(named: images[0]) if (image == nil) { println("null") } else{ var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, 50, 50) button.setImage(image, forState: .Normal) self.view.addSubview(button) println("image is available") } </code></pre> <p>Output is :</p> <blockquote> <p>image is available</p> </blockquote> <p><img src="https://i.stack.imgur.com/1JY6i.png" alt="enter image description here"></p> <p>You must give the name same as assets folder. </p> |
32,822,743 | 0 | <blockquote> <ul> <li><strong>demo:</strong> <a href="http://so.devilmaycode.it/filtering-model-on-client-angularjs/" rel="nofollow">http://so.devilmaycode.it/filtering-model-on-client-angularjs/</a></li> </ul> </blockquote> <p>please refer to demo source code.</p> |
28,719,897 | 0 | Create action with delayed_job <p>In my controller I am trying to move my create method into a background process, as it takes too much time. I can't get it right. </p> <p>My option 1:</p> <p>First I went with creating a self method for my controller so it looked like this:</p> <pre><code> def create MyController.delay.create_and_email(current_app_user) respond_to do |format| format.js {} end end def create_and_email(user) @user = AppUser.find_by(id: user.id) @link_share = @user.link_shares.build(link_share_params) @link_share.save end </code></pre> <p>I had to throw in the current_app_user as the self method could not see it, but I got totally puzzled on what to do with my link_share strong params, because the self method does not see the <strong>link_share_params</strong>. I guess I could make this option work, if anyone would point me how to throw in strong params into a self. controller method.</p> <p>My option 2:</p> <p>I then decided to move the whole action into my User model like this</p> <p>Contoller:</p> <pre><code> def create @user = current_app_user @user.delay.create_and_email(link_share_params) respond_to do |format| format.js {} end end </code></pre> <p>Model:</p> <pre><code> def create_and_email link_share = self.link_shares.build(**params**) link_share.save end </code></pre> <p>Again, trouble with the strong params. How would I go with importing my params into the model? Should I just chain them as arguments? </p> <p>Any advice appreciated</p> |
17,752,476 | 0 | <p>Generally this means that the parameter within the square brackets is optional; however, without a link to the specific documentation it's hard to say.</p> |
10,841,371 | 0 | <p>Re: Ahmad's code - a simpler approach with no recursion or pointers, fairly naive, but requires next to no computational power for anything short of really titanic numbers (roughly 2N additions to verify the Nth fib number, which on a modern machine will take milliseconds at worst)</p> <p>// returns pos if it finds anything, 0 if it doesn't (C/C++ treats any value !=0 as true, so same end result)</p> <pre><code>int isFib (long n) { int pos = 2; long last = 1; long current = 1; long temp; while (current < n) { temp = last; last = current; current = current + temp; pos++; } if (current == n) return pos; else return 0; } </code></pre> |
35,751,935 | 0 | <p>Try this and tell me:</p> <pre><code>SELECT a.seq_id, a.id, GROUP_CONCAT(cnt) AS cnt FROM music_artist AS a, ( SELECT ma.artist_id, CONCAT_WS('-', mgr.country_code, count(mgr.media_id)) AS cnt FROM music_album_artists AS ma JOIN media_geo_restrict AS mgr ON ma.album_id = mgr.album_id GROUP BY mgr.country_code ) AS count_table WHERE a.seq_id > 0 and a.seq_id < 10000 and a.id=count_table.artist_id group by a.id </code></pre> |
12,696,770 | 0 | <p>In addition to existing good answer by @Nominal Aminal it is an integer but it points to an entry of a structure in kernel called file descriptor table. That is at least the case with Linux. Of the several fields that are part of that struct, an interesting one is:</p> <pre><code>FILE * pointer; // descriptor to / from reference counts etc. </code></pre> <p>You might be interested in following api's which given one of FILE * or descriptor, return the other</p> <p><a href="http://stackoverflow.com/questions/4210966/c-how-can-i-change-from-file-descriptor-to-file-struct-and-visa-versa">How to obtain FILE * from fd and vice versa</a></p> |
28,712,540 | 0 | <p>I found <a href="https://www.nuget.org/packages/lightbuzz-smtp/" rel="nofollow">SMTP client for WinRT</a> which work for me</p> |
36,798,569 | 0 | <p>When the combobox loads initially, no item is selected. It then sets the selected item to "Keine Angabe" based on the IsSelected property. This then causes the selection change event to fire. If you remove it, you will see the event is not fired.</p> <p>You can re-use the method for other comboboxes by casting the sender to the combobox type: See below:</p> <pre><code>private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var combobox = sender as ComboBox; combobox.BorderBrush = new SolidColorBrush(new Color { R = 204, G = 204, B = 204, A = byte.MaxValue }); } </code></pre> |
4,424,999 | 0 | <p>Here is another approach to make a deck of cards</p> <pre><code>from itertools import product card_values = ( ("1", "1", 1), ("2", "2", 2), ("3", "3", 3), ("4", "4", 4), ("5", "5", 5), ("6", "6", 6), ("7", "7", 7), ("8", "8", 8), ("9", "9", 9), ("10" ,"10", 10), ("Jack", "J", 10), ("Queen", "Q", 10), ("King", "K", 10), ("Ace", "A", 11)) card_suits = ("Spades", "Clubs", "Hearts", "Diamonds") class Card(object): def __init__(self, name, short_name, rank, suit): self.name = name self.short_name = short_name self.rank = rank self.suit = suit cards = [] for (name, short_name, rank), suit in product(card_values, card_suits): cards.append(Card(name, short_name, rank, suit)) </code></pre> |
31,904,343 | 0 | How to start an activity from a custom ListView? <p>I have a custom listview in which I can add as many elements as I want. All of these elements must open an activity (which is called "Compile" in my project) with a few edittext stuff to fill. The problem is that I don't actually know what to write in my code to tell the app to open the Compile activity when one of the elements is clicked. </p> <p>//(Obviously every element must open its Compile activity with its relative informations. For example: element "Pizza" must open the activity Compile in which there are all the infos I previously put about Pizza.)//</p> <p>Thanks for the support </p> <p>This is my code for the listview:</p> <pre><code>public class Sheet extends Activity { private static final int DIALOG_ALERT = 10; ListView list; ImageView addBtn; EditText input; String[] items; MyListAdapter adapter; AlertDialog alert; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sheet); list = (ListView) findViewById(R.id.list); addBtn = (ImageView) findViewById(R.id.addPlanBtn); input = new EditText(this); items = new String[1]; alert = new AlertDialog.Builder(Sheet.this).create(); alert.setTitle("Activity name: "); alert.setMessage("Type a name for your activity: "); alert.setView(input); alert.setButton("add", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String value = input.getText().toString(); items[items.length - 1] = value; adapter = new MyListAdapter(Sheet.this, items); list.setAdapter(adapter); String[] temp = new String[items.length +1]; for(int i = 0; i< items.length; i++) temp[i] = items[i]; items = temp; alert.dismiss(); adapter.notifyDataSetChanged(); } }); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alert.show(); } }); } </code></pre> |
1,672,455 | 0 | <p>It depends on what <code>stringArray</code> is. If it's a <a href="http://www.j2ee.me/javase/6/docs/api/java/util/Collection.html" rel="nofollow noreferrer"><code>Collection</code></a> then fine. If it's a true array, you should make it a <code>Collection</code>. The <code>Collection</code> interface has a method called <a href="http://bit.ly/2o9fix" rel="nofollow noreferrer"><code>contains()</code></a> that will determine if a given <code>Object</code> is in the <code>Collection</code>.</p> <p>Simple way to turn an array into a <code>Collection</code>:</p> <pre><code>String tokens[] = { ... } List<String> list = Arrays.asList(tokens); </code></pre> <p>The problem with a <a href="http://www.j2ee.me/javase/6/docs/api/java/util/List.html" rel="nofollow noreferrer"><code>List</code></a> is that lookup is expensive (technically linear or <code>O(n)</code>). A better bet is to use a <a href="http://www.google.com.au/search?hl=en&rlz=1C1GGLS_enAU314AU317&q=java.util.set+6&btnG=Search&meta=&aq=f&oq=" rel="nofollow noreferrer"><code>Set</code></a>, which is unordered but has near-constant (<code>O(1)</code>) lookup. You can construct one like this:</p> <p>From a <code>Collection</code>:</p> <pre><code>Set<String> set = new HashSet<String>(stringList); </code></pre> <p>From an array:</p> <pre><code>Set<String> set = new HashSet<String>(Arrays.asList(stringArray)); </code></pre> <p>and then <code>set.contains(line)</code> will be a cheap operation.</p> <p><strong>Edit:</strong> Ok, I think your question wasn't clear. You want to see if the line contains any of the words in the array. What you want then is something like this:</p> <pre><code>BufferedReader in = null; Set<String> words = ... // construct this as per above try { in = ... while ((String line = in.readLine()) != null) { for (String word : words) { if (line.contains(word)) [ // do whatever } } } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } </code></pre> <p>This is quite a crude check, which is used surprisingly open and tends to give annoying false positives on words like "scrap". For a more sophisticated solution you probably have to use regular expression and look for word boundaries:</p> <pre><code>Pattern p = Pattern.compile("(?<=\\b)" + word + "(?=\b)"); Matcher m = p.matcher(line); if (m.find() { // word found } </code></pre> <p>You will probably want to do this more efficiently (like not compiling the pattern with every line) but that's the basic tool to use.</p> |
8,012,124 | 0 | <p>Object (the class from which all java objects ultimately inherit) defines it's own toString() method. Therefore, if you don't override the toString() method in your class, then it will use the one defined in Object() (or any intermediate classes between your class and Object).</p> <p>This is why, if you don't define a toString() method, you don't get an error from javac.</p> <p>This usually results in a String like</p> <pre><code>System.out.println("o=" + new Object().toString()) o=java.lang.Object@1176e5f </code></pre> |
6,576,281 | 0 | <p>The problem is NOT your texture coordinates.</p> <p>The problem is that you're loading the texture wrong. You're forgetting to remove the bitmap header, so all the real data is shifted over, and the end of each line is shifted onto the beginning of the next line.</p> <p>Texture wrapping would wrap pixels from the right back onto the same line, but the out-of-place region is shifted down one row. Texture wrapping also wouldn't occur with the "clamp to edge" mode you've enabled.</p> |
6,134,230 | 0 | continuously print the last line of a file Linux termin <p>Two questions, but only stuck on one. Feel that I need the first one so someone can help me make sense of it.</p> <p>4) Use cat and /dev/null to create an empty file.</p> <p>5) Start a background process that continuously prints the last line of the file created in #4..</p> <p>So what i did for number 4 was: </p> <pre><code>cat /dev/null > emptyfile </code></pre> <p>This created an empty file. Okay so I am happy with that. The next question however confuses me. How can I read the last line of an empty file? Better yet how do I continuously do this? Running it in the background isn't a problem. Anyone have any ideas? We haven't covered scripting yet so I don't think that plays a role. As always, thanks for the help.</p> |
31,098,176 | 0 | <p>Another possible solution is to add a constructor parameter and have a factory method;</p> <pre><code>public class Something extends SomethingElse { private Something(int arg) { super(arg); } public static Something getSomething() { return new Something(new Random().nextInt(10) + 5); } } </code></pre> |
25,370,498 | 0 | Validation for multiplying value at C++? <p>I have to make a test where a number has to be the <strong>multiple</strong> of 500,</p> <pre><code> do{ cout << "Input Price[price>0|price multiple of 500]: "; cin >> price; cin.sync(); cin.clear(); } while (price<1 || price>5000); </code></pre> <p>The code is still incomplete, I just have to add the following validation left. What do I do?</p> <p>and also what is the right term for that kind of validation? I had a hard time determining the title.</p> |
29,484,526 | 0 | <p><a href="http://examples.javacodegeeks.com/java-basics/exceptions/java-io-notserializableexception-how-to-solve-not-serializable-exception/" rel="nofollow">NotSerializableException</a> is thrown when an instance of a class must implement the Serializable interface.</p> <p>If the class that throws the exception does not belong to a third-party library, find the class and make it implement the serializable interface.</p> <p>If you do not want to serialize the objects in the class, you can mark the objects as <a href="http://stackoverflow.com/questions/910374/why-does-java-have-transient-variables">transient</a>, to make the serializable runtime ignore the objects.</p> <p>You can read about it <a href="http://examples.javacodegeeks.com/java-basics/exceptions/java-io-notserializableexception-how-to-solve-not-serializable-exception/" rel="nofollow">here</a></p> |
31,148,932 | 0 | Add JavaScript Through Acumatica Customization <p>I'm wondering if it's possible to add JavaScript code to an Acumatica web page through a customization.</p> <p>Thanks for your help!</p> <p>Fran Parker</p> |
4,803,873 | 0 | <p>I just love this in-depth article about Entity Framework 4 POCO, Repository and Specification Pattern</p> <p><a href="http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/" rel="nofollow">http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/</a></p> |
27,850,603 | 0 | <p>To convert from one date format to another, just modify the answer posted at <a href="http://stackoverflow.com/a/27659933/1745001">http://stackoverflow.com/a/27659933/1745001</a> to suit your input format.</p> |
39,311,853 | 0 | Android - force network requests go through wifi instead of mobile network <p>I have an app which connects to a hardware device Wi-Fi hotspot. It seems that Android forward requests over other networks (3G/4G for example) instead the hotspot, since my hot spot has no internet connection.</p> <p>Is there any way to force network stream to work on the wifi? I've come across the following function, but it's deprecated: <a href="https://developer.android.com/reference/android/net/ConnectivityManager.html#setNetworkPreference(int)" rel="nofollow">https://developer.android.com/reference/android/net/ConnectivityManager.html#setNetworkPreference(int)</a></p> |
33,710,914 | 0 | Generating sorted list of all possible coprimes <p>I need to generate infinite sorted list of all coprimes. The first element in each pair must be less than the second. The sorting must be done in ascending order -- by the sum of pair's elements; and if two sums are equal, then by the pair's first element.</p> <p>So, the resulting list must be </p> <pre><code>[(2,3),(2,5),(3,4),(3,5),(2,7),(4,5),(3,7),(2,9),(3,8),(4,7)...` </code></pre> <p>Here's my solution.</p> <pre><code>coprimes :: [(Int, Int)] coprimes = sortBy (\t1 t2 -> if uncurry (+) t1 <= uncurry (+) t2 then LT else GT) $ helper [2..] where helper xs = [(x,y) | x <- xs, y <- xs, x < y, gcd x y == 1] </code></pre> <p>The problem is that I can't take <code>n</code> first pairs. I realize that sorting can't be done on infinite lists.</p> <p>But how can I generate the same sequence in a lazy way?</p> |
29,012,663 | 0 | Can't save Jasypt encrypted password to .properties file <p>I'm trying to store some strings in a .properties file. Now i want to encrypt those strings with Jasypt. But when I try to save this to the .properties file it is missing the surrounding "ENC()". When i try to insert this manually, the string is stored in clear text. Why?</p> <pre><code>StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setPassword("123456789"); Properties prop = new EncryptableProperties(encryptor); prop.setProperty("key", "ENC(" + encryptor.encrypt("value") + ")"); prop.store(new FileOutputStream(System.getProperty("user.home") + "/.application-name/config.properties"), "Test"); </code></pre> |
23,996,375 | 0 | Can't resolve a Locale <p>I have a problem with Locale's. I'm trying to do a simple thing where I can choose english or german. So I have two property files called messages_en and messages_de. So far these files have a single line:</p> <pre><code> contactbook = Contact Book </code></pre> <p>and </p> <pre><code> contactbook = Adressbuch </code></pre> <p>respectively. </p> <p>Now in my JSP view I have this :</p> <pre><code> <spring:message code="contactbook"/> </code></pre> <p>The idea is that the message in the view changes depending on which locale we're using. Now the locale itself should be changed with this line:</p> <pre><code> <a href="?language=en">English</a>|<a href="?language=de">German</a> </code></pre> <p>If I remove the everything works great but of course it's not locale specified. So the rest of the view is good.</p> <p>In my dispatcher-servlet.xml file I have this:</p> <p> </p> <pre><code><bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"> <property name="defaultLocale" value="en" /> </bean> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="language" /> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" > <property name="interceptors"> <list> <ref bean="localeChangeInterceptor" /> </list> </property> </bean> </code></pre> <p>Again, without it everything works well. There's something wrong with my understanding here. The localeChangeInterceptor stops any change done to the locale and the ControllerClassNameHandlerMapping does what? I keep on looking at my controller and wondering should I add something to it but it seems to me that all these lines in the dispatcher should be enough.</p> <p>The exception I get is </p> <pre><code> No message found under code 'contactbook' for locale 'en' </code></pre> <p>Despite a myriad of examples out there I keep on failing to understand or resolve the problem. Any help would be greatly appreciated.</p> |
30,766,678 | 0 | <p>You can make search like this:</p> <pre><code>cable OR cable* </code></pre> <p>This way Solr will search the exactly term <code>cable</code> and your synonyms and <code>cable*</code> will search every terms that starts with <code>cable</code>.</p> |
9,567,879 | 0 | <p>As far as I know, the declaration reserves some memory according to how may bytes this specific type needs. These bytes could in theory be randomly filled with whatever was physically occupying those specific bytes of hardware.</p> |
31,122,222 | 0 | Quickfixj not honoring custom fields in a repeating group <p>I am using FIXT1.1 and FIX Application version 5.0SP2. </p> <p>I added some custom fields to the QuotSetAckGrp, part of MassQuoteAcknowledgement message. However, when quickfix reads the repeating group, it does not read the custom fields as part of the repeating groups. Instead, it treats the custom fields are regular parent-level fields and throws a "Tag appears more than once" session level reject. </p> <p>Appreciate any inputs to help resolve the issue.</p> |
34,744,443 | 0 | How to change connection type of SSRS report Data source dynamically <p>I have an application that binds the RDL file on report server to Report viewer control to produce reports. We use embedded data source in the RDL file. We have used expression based connection string for our embedded data source So that we will be able to change the data source dynamically.</p> <p>We wanted to access the report using both windows integrated security and SQL server authentication. Now if our data source is configured to use windows integrated security and we wanted to access the report using SQL authentication, then we are modifying the RDL file using web methods before producing the report.</p> <p>Is there any other way to do this?</p> |
14,598,407 | 0 | <p>All your mess is really goes from fact, that you don't know if cfg was allocated on heap or wasn't. Just calling malloc somewhere on startup means nothing -- libc calls malloc several times even for void program.</p> <p>Let me explain you how to determine where your data is.</p> <p>Lets start with your code, some modified:</p> <pre><code>#include "stdlib.h" class Config { public: Config(int spi) {_spi = &spi;} virtual ~Config() {;} private: int *_spi; }; Config cfg(2); int main(void) { int *x = new int(2); return 0; } </code></pre> <p>Now lets compile it with <code>g++ -g -O0 statstorage.cpp -static</code></p> <p>You got a.out file. Now we must look where your data are actually are. First call gdb with command line like this:</p> <pre><code>echo -e "start\nstep\np/x &cfg\np/x x\nquit" > .gdbinit && gdb a.out </code></pre> <p>You will got output like this:</p> <pre><code>$1 = 0x6add50 $2 = 0x6c5670 </code></pre> <p>Where 0x6add50 is address of your cfg, and 0x6c5670 is address of dynamically allocated x pointer.</p> <p>Now lets call readelf, like <code>readelf -S a.out</code></p> <p>And look where sections are. Output is (for my pc) 38 sections. All we need is Address field and Size field. I have:</p> <pre><code> Address Size [23] .bss ... 00000000006add00 ... 0000000000014d38 [24] __libc_freeres_pt ... 00000000006c2a38 ... 0000000000000030 </code></pre> <p>And __libc_freeres_pt is the last section with the biggest non-null address.</p> <p>We can see, that 0x6c5670 is outside loaded binary (in heap itself), and cfg is inside bss section.</p> <p>This yields, taht cfg <strong>was</strong> allocated statically.</p> |
37,831,309 | 0 | Testing Socket.IO with session <p>We have some functionality based on the Socket.IO. Socket.IO uses express-session and cookieParser. How can I test server side of Socket.IO in Node.js, not browser environment? Is there any way to pass cookies to io.connect() function?</p> |
34,061,473 | 0 | <p>You can convert with <code>strtotime()</code> to safely date-manipulating and then you can reorder the array:</p> <pre><code>$dates = array( '2015-02-13', '2015-04-21', '2015-08-18', '2015-11-26', '2015-09-15', '2015-01-07', '2015-02-11', '2015-07-14', '2015-03-02', ); $newArray = array(); foreach($dates as $value) { $newArray[] = strtotime($value); } sort($newArray); var_dump($newArray); </code></pre> |
18,119,464 | 0 | <p>The problem is case-sensitivity. MySQL identifiers are not case sensitive unless you enclose them in backticks. However, PHP array indexes <em>are</em>. </p> <p>Therefore if you have a column named <code>CourseName</code>, the following query <em>will</em> work:</p> <pre><code>SELECT * FROM course WHERE cOuRSEnaME = 'foo' ORDER BY courSEnAmE </code></pre> <p>But, referencing it in PHP as <code>$row['coursename']</code>, <code>$row['cOURsENamE']</code> or any other differing combination will not work, as these all refer to <em>different</em> keys. You must use <code>$row['CourseName']</code>.</p> <p>See also: <a href="http://stackoverflow.com/questions/1511230/php-array-are-array-indexes-case-sensitive">PHP array, Are array indexes case sensitive?</a></p> |
26,688,550 | 0 | <p><code>git config -l</code></p> <p>if current git repository's <code>core.precomposeunicode=true</code></p> <p>try this,</p> <p><code>git config core.precomposeunicode false</code></p> <p>and this is why. <a href="http://git-scm.com/docs/git-config">from here</a></p> <blockquote> <p>core.precomposeunicode This option is only used by Mac OS implementation of Git. When core.precomposeunicode=true, Git reverts the unicode decomposition of filenames done by Mac OS. This is useful when sharing a repository between Mac OS and Linux or Windows. (Git for Windows 1.7.10 or higher is needed, or Git under cygwin 1.7). When false, file names are handled fully transparent by Git, which is backward compatible with older versions of Git.</p> </blockquote> |
13,084,499 | 0 | <p>I came into this problem today. After some testing, I got this working, without using temorary element.</p> <p>In IE, it's easy to work it out with offsetLeft and offsetTop property of a TextRange object. Some effort is needed for webkit though.</p> <p>Here's a test, you can see the result. <a href="http://jsfiddle.net/gliheng/vbucs/12/">http://jsfiddle.net/gliheng/vbucs/12/</a></p> <pre><code>var getCaretPixelPos = function ($node, offsetx, offsety){ offsetx = offsetx || 0; offsety = offsety || 0; var nodeLeft = 0, nodeTop = 0; if ($node){ nodeLeft = $node.offsetLeft; nodeTop = $node.offsetTop; } var pos = {left: 0, top: 0}; if (document.selection){ var range = document.selection.createRange(); pos.left = range.offsetLeft + offsetx - nodeLeft + 'px'; pos.top = range.offsetTop + offsety - nodeTop + 'px'; }else if (window.getSelection){ var sel = window.getSelection(); var range = sel.getRangeAt(0).cloneRange(); try{ range.setStart(range.startContainer, range.startOffset-1); }catch(e){} var rect = range.getBoundingClientRect(); if (range.endOffset == 0 || range.toString() === ''){ // first char of line if (range.startContainer == $node){ // empty div if (range.endOffset == 0){ pos.top = '0px'; pos.left = '0px'; }else{ // firefox need this var range2 = range.cloneRange(); range2.setStart(range2.startContainer, 0); var rect2 = range2.getBoundingClientRect(); pos.left = rect2.left + offsetx - nodeLeft + 'px'; pos.top = rect2.top + rect2.height + offsety - nodeTop + 'px'; } }else{ pos.top = range.startContainer.offsetTop+'px'; pos.left = range.startContainer.offsetLeft+'px'; } }else{ pos.left = rect.left + rect.width + offsetx - nodeLeft + 'px'; pos.top = rect.top + offsety - nodeTop + 'px'; } } return pos; }; </code></pre> |
7,255,458 | 0 | How can i control output from crontab? <p>I am trying to run a test case via automation testing (sahi) , so I am running the command for it repeatedly after 1 hour (via crontab).<br> What I want is that is there any solution that <strong>whenever my test case fails i should receive the email otherwise not..</strong> Right now I am reciving mail whether it passes or fails.<br> In short, can i send mail to a person depending upon the output i get in terminal.<br> I want to send mail when output will be:<br> 1 scenario (1 failed) 4 steps (3 skipped, 1 failed) 0m2.476s </p> <p>Thanks.</p> |
21,486,879 | 0 | Anything Else Like An Iframe? I want to do Whatever we can do with Iframe <p>Really, i like to use iframe. because iframe will reduce the transferring data between server & client. We can display the static contents in out of iframe & dynamic content in iframe. But many developers are saying "iframe isn't good". I don't know whether it's correct or not. If anybody know about iframe please don't forget to answer. and i need to know any other ideas such as iframe. </p> |
17,747,238 | 0 | <p>The classpath of javac should refer to directories and jar files containing the root of compiled class files trees. It should not refer to Java files.</p> <p>Similarly, the source directory should refer to the root of the package tree of the source files. Not to directories corresponding to packages, inside the package tree.</p> <p>Your compile task should look like</p> <pre><code><target name="main-compile"> <javac includeantruntime="false" srcdir="src/main/java" destdir="${gen.bin.main.dir}" debug="on" includes="com/myapp/api/**/*.java, com/myapp/impl/core/FizzImpl/**/*.java"> <classpath refid="lib.main.path"/> </javac> </target> </code></pre> |
40,856,821 | 0 | Quanteda - Apply Function to DFM Over Document Variables <p>I am using R's quanteda package and the latest versions for both R and the package. I have a corpus of documents which number in the millions.</p> <p>Let's suppose I have a DFM generated from quanteda with each document having a docvar of the date. There are thousands of documents generated in a given day, but I want to obtain the DFMs applied to the documents by day (so that I have total word counts for each term by day). I know that quanteda is built using data.table, so it should be possible to do this, but I have found little in the "Getting Started with Quanteda" or on StackOverflow that gives a clean way of doing this.</p> <p>Any suggestions?</p> |
27,016,070 | 0 | <p>Try this:</p> <pre><code>foreach (string file in Directory.EnumerateFiles(folderPath, "*CustsExport*.xml")) { } </code></pre> <p>Or your can use regex:</p> <pre><code>Regex reg = new Regex(@".*CustsExport.*\.xml",RegexOptions.IgnoreCase); var files = Directory.GetFiles(yourPath, "*.xml") .Where(path => reg.IsMatch(path)) .ToList(); </code></pre> |
32,708,767 | 0 | <p>I experienced this problem and the fix, for me at least, was to set the HOME variable in the crontab to the path of the home directory of the user that the cronjob was being run as. It was previously being set to '/'. </p> |
1,350,931 | 0 | <p>In case you're using log4j breed of logging APIs you might be interested in looking at MDC - <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html" rel="nofollow noreferrer">mapped diagnostic context</a>. It was designed particularly for this type of problems. Check out <a href="http://www.moonlit-software.com" rel="nofollow noreferrer">logFaces</a> - it will let you <a href="http://www.moonlit-software.com/logfaces/web/features/index.php#mdc" rel="nofollow noreferrer">easily fish out</a> particular context data in real time or by doing queries. Otherwise, the ThreadLocal mentioned by Aaron seems reasonable too, it's just that you will have to do the coding yourself instead of using proved concept of MDC used in log4j for a long time and by many users.</p> <p><strong>Disclosure</strong>: I am the author of this product.</p> |
29,391,399 | 0 | <p>I finally got a solution for the problem. The code that works for me is the following:</p> <pre><code>override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.cyanColor() playButton.layer.backgroundColor = UIColor.whiteColor().CGColor playButton.layer.cornerRadius = 5 let initSignalExample = [0.0, 1.0, 2.0, 1.0, 0.0] lineChartSubView.frame = CGRectMake(0, 0, screenWidth, screenHeight) lineChartSubView.backgroundColor = UIColor.whiteColor() lineChartSubView.setXLabels(["0","1","2","3","4"], withWidth: 1) lineChartSubView.showCoordinateAxis = true lineChartSubView.showLabel = true lineChartSubView.delegate = self var signalObtainedValues = PNLineChartData() signalObtainedValues.color = UIColor.greenColor() signalObtainedValues.itemCount = UInt(initSignalExample.count) signalObtainedValues.getData = ({(index: UInt) -> PNLineChartDataItem in var yValue:CGFloat = CGFloat(initSignalExample[Int(index)]) var item = PNLineChartDataItem(y: yValue) return item }) lineChartSubView.chartData = [signalObtainedValues] lineChartSubView.strokeChart() } </code></pre> <p>Now the problem is that the graph does not fit in the subview, but maybe I will open another question since the original post is solved. Thank you very much!</p> |
33,811,276 | 0 | <p>You can simply configure profile recognition in Print&Share. This video example uses a profile with a Printer Channel and one with a File Printer Channel: <a href="https://www.youtube.com/watch?v=nvTly9qXQMI&list=PLDF2C2AD95B2B2FC2&index=38" rel="nofollow">https://www.youtube.com/watch?v=nvTly9qXQMI&list=PLDF2C2AD95B2B2FC2&index=38</a> </p> <p>You can easily create a profile with only Printer Channels, as you wish. This way you only have to print and the software will select the correct profile or A or B automatically (if you enable "Auto Send & Close" it will also print automatically without showing the user interface).</p> |
23,231,159 | 0 | <p>The second option allows you to do more complex formatting. With a <code>string</code>, there is little advantage, but if you were using a <code>double</code> value, for example, you could use the <a href="http://msdn.microsoft.com/en-us/library/txafckwd%28v=vs.110%29.aspx" rel="nofollow">composite format options</a> to specify the amount of precision to display or other options.</p> |
40,183,321 | 0 | <p>To reorder the items, a basic way could be as follows:</p> <pre><code>split_line = line.split(" ") column_mapping = [9,6,3,7,3,2,1] reordered = [split_line[c] for c in column_mapping] joined = ",".join(reordered) outfile.write(joined) </code></pre> <p>This splits up the string, reorders it according to <code>column_mapping</code> and then combines it back into one string (comma separated)</p> <p>(in your code don't include <code>column_mapping</code> in the loop to avoid reinitialising it)</p> |
10,285,635 | 0 | <p>Comparing user-visible strings is generally considered bad practice (and becomes tedious when you need to do i18n), especially with string literals since it's vulnerable to typos.</p> <p>If you're just going to <em>toggle</em> between two states, the easiest thing to do is to use the <code>UIControl.selected</code> property (corresponding to <code>UIControlStateSelected</code>):</p> <pre><code>// In init [myButton setTitle:@"test" forState:UIControlStateNormal]; [myButton setTitle:@"test2" forState:UIControlStateSelected]; [myButton setTitle:@"test2" forState:UIControlStateSelected|UIControlStateHighlighted]; // Toggle myButton.selected = !myButton.selected; </code></pre> <p>It also makes the code a lot cleaner when you when you decide to toggle the button image/background/text colours too.</p> <p>Note the slight gotcha: If you don't set the title for <code>UIControlStateSelected|UIControlStateHighlighted</code> it will use the title for <code>UIControlStateNormal</code> when the button is both selected and highlighted (touched).</p> |
3,480,842 | 0 | <p>I've set up EGit in Eclipse for a few of my projects and find that its a lot easier, faster to use a command line interface versus having to drill down menus and click around windows.</p> <p>I would prefer something like a command line view within Eclipse to do all the Git duties.</p> |
8,268,505 | 0 | Xcode: Error -> Build failed -> Please upgrade your Subversion client to use this working copy <p>I am using Xcode 4.2.1. and I have this problem running an existing application on the iOS simulator:</p> <pre><code>svn: The path '.' appears to be part of a Subversion 1.7 or greater working copy. Please upgrade your Subversion client to use this working copy. /Users/me/Library/Developer/Xcode/DerivedData/myproject-dxfzldckuqdmlrghowwkdrbgoigy/Build /Intermediates/myproject.build/Debug-iphonesimulator/MyProject.build/Script-9567AEA113C59633000AA291.sh: No Subversion revision found at /Users/me/Library/Developer/Xcode/DerivedData/myproject-dxfzldckuqdmlrghowwkdrbgoigy/Build/Intermediates/myproject.build/Debug-iphonesimulator/MyProject.build/Script-9567AEA113C59633000AA291.sh line 32. Building revision Command /bin/sh failed with exit code 1 </code></pre> <p>I have a Subversion server 1.7.1 installed and also on the client side I upgraded to 1.7.1. I did a <code>svn upgrade</code> and then I get this error in Xcode.</p> <p>If I repeat the <code>svn upgrade</code> on the terminal I get the message <code>Can't upgrade '...' as it is not a pre-1.7 working copy directory</code>.</p> <p>So what is wrong? How an I solve the problem?</p> <p>Best Regards Tim</p> |
18,743,618 | 0 | Error multiple highcharts while loading in carousel <p>I'm loading multiple charts in a bootstrap carousel, but I get always the following highcharts error:</p> <blockquote> <p>Highcharts Error #16</p> <p>Highcharts already defined in the page</p> <p>This error happens the second time Highcharts or Highstock is loaded in the same page, so the Highcharts namespace is already defined. Keep in mind that the Highcharts.Chart constructor and all features of Highcharts are included in Highstock, so if you are running Chart and StockChart in combination, you only need to load the highstock.js file.</p> </blockquote> <p>This is what I do in my html:</p> <pre><code><div id="myCarousel" class="carousel slide"> <div class="carousel-inner"> <?php for ($i = 1; $i <= $numquestions; $i++) { ?> <div class="item"> <h2><?php echo "de titel van de question"; ?></h2> <div id=<?php echo "container" . $i; ?>></div> </div> <?php } ?> </div> <!-- Controls (CHECK ICONS) --> <a class="left carousel-control" href="#myCarousel" data-slide="prev">&laquo;</a> <a class="right carousel-control" href="#myCarousel" data-slide="next">&raquo;</a> </div> </code></pre> <p>I create the number of items in my carousel.</p> <p>My javascript:</p> <pre><code><script type="text/javascript"> var categories = new Array(); var data = new Array(); var chart; var questionsandanswers = <?php echo json_encode($questionandanswers); ?>; for (var i = 0; i < questionsandanswers.length; i++) { questiontitle = ""; answers = ""; // Loop through questions var questiontitle = questionsandanswers[i].Text; var answers = questionsandanswers[i]['0']; createChart(i, questiontitle, answers); } // Create the Charts function createChart(i, questiontitle, answers){ chart=""; i++; // CHART OPTIONS var options = { chart: { type: 'bar', renderTo: 'container' + i }, xAxis: { categories: '', title: { text: null } }, yAxis: { min: 0, title: { text: 'Aantal keer gekozen', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { //valueSuffix: ' aantal keer gekozen' }, plotOptions: { bar: { dataLabels: { enabled: true, color: 'black', formatter: function() { if (this.y === 0) { return null; } else { return this.y; } } }, stacking: 'normal' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 100, floating: true, borderWidth: 1, backgroundColor: '#FFFFFF', shadow: true }, credits: { enabled: false }, series: [] } chart = new Highcharts.Chart(options); // Create new chart with general options for (var i = 0; i < answers.length; i++) { // add answers to categories array categories.push(answers[i].Text); data.push(answers[i]['0']); } // add categories to x-axis chart.xAxis[0].setCategories(categories); chart.addSeries({data:data,name:'Aantal keer gekozen'},false); chart.setTitle({ text: questiontitle }); // redraw chart chart.redraw(); categories = Array(); data = Array(); } </script> </code></pre> <p>As you can see I add the charts to the different containers but I still get an error. I know I add multiple highcharts in the same page but I need to ... . How can I fix this that I don't get that error?</p> |
31,532,924 | 0 | Use link function in directives to append different HTML elements <p><a href="https://jsfiddle.net/o76hxj69/1/" rel="nofollow"><strong>Fiddle</strong></a></p> <p>I have two buttons. When pressed it displays a modal, with som text. But I also want to add some html dynamically depending on which button is pressed.</p> <p>I have tried both <code>$observe</code> and <code>$watch</code> methods, but I'm having problems making it work. </p> <p>here is my code.</p> <pre><code>angular.module('TM', []) .controller('protocolCtrl', function(){ this.text = 'Now looking at the protocol part'; this.modalId = 'protocolModal'; }) .controller('categoryCtrl', function(){ this.text = 'Now looking at the category part'; this.modalId = "categoryModal"; }) .directive('modalDirective', function(){ return { restrict: 'E', scope: { ctrl: '=', modalId: '@', }, template: ['<div id="{{modalId}}" class="modal fade" role="dialog">', '<div class="modal-dialog">', '<div class="modal-content">', '<div class="modal-header">', '<h4 class="modal-title">Modal Header</h4>', '</div>', '<div class="modal-body">', '<p> {{ ctrl.text }} </p>', '</div>', '<div class="modal-footer">', '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>', '</div>', '</div>', '</div>', '</div>'].join(''), link: function(scope, element, attrs) { element.$observe('modalId', function(){ var modal = element.find('#{{modalId}}'); if(modal == 'protocolModal'){ element.find('#{{modalId}}').append('<div>this is a protocol test...</div>'); } else { element.find('#{{modalId}}').append('<div>this is a category test...</div>'); } }); } } }); </code></pre> |
38,885,225 | 0 | <p><code>grep</code> does not recognize <code>\d</code>. Try:</p> <pre><code>$ grep -E 'Info:.*took\s*[0-9.]*\s*[mhd]' logfile Info: Executed check 'bla', result 'pass', took 2.5 minutes. Info: Executed check 'foo', result 'pass', took 3.4 hours. Info: Executed check 'bar', result 'pass', took 2.7 days. </code></pre> <p>Or, better yet:</p> <pre><code>$ grep -E 'Info:.*took\s*[[:digit:].]*\s*[mhd]' logfile Info: Executed check 'bla', result 'pass', took 2.5 minutes. Info: Executed check 'foo', result 'pass', took 3.4 hours. Info: Executed check 'bar', result 'pass', took 2.7 days. </code></pre> <p>Notes:</p> <ol> <li><p><code>egrep</code> is deprecated. Use <code>grep -E</code> instead.</p></li> <li><p><code>grep</code> is supposed to support POSIX regular expressions. <code>\s</code> is a GNU extension and may not be portable. <code>\d</code> is not supported.</p></li> <li><p><code>[:digit:]</code> is unicode-safe which makes it a better choice than <code>0-9</code>.</p></li> <li><p>To match floating point numbers, one must allow a decimal point in addition to digits. Note that, outside of <code>[...]</code>, the period <code>.</code> is a wildcard. Inside <code>[...]</code>, by contrast, it only matches a period.</p></li> </ol> <h3>More portable version</h3> <p>For greps that do not support <code>\s</code>, try:</p> <pre><code>$ grep -E 'Info:.*took[[:space:]]*[[:digit:].]*[[:space:]]*[mhd]' logfile Info: Executed check 'bla', result 'pass', took 2.5 minutes. Info: Executed check 'foo', result 'pass', took 3.4 hours. Info: Executed check 'bar', result 'pass', took 2.7 days. </code></pre> |
13,547,057 | 0 | <p>This is not a trivial problem at all.</p> <p>One method you might find useful is pre-processing the data so that it can be represented in the form of a directed graph. You then assign appropriate costs to each leg depending on the desirability of taking that path from the point of view of the user (eg. how much does it cost to travel on the path in terms of dollars, time, distance, etc.) Having done this, you can apply algorithms such as Dijkstra's Algorithm to determine the best path for the user to take.</p> |
20,874,391 | 1 | Django / Python: Real time peer to peer chat messaging <p>I use Django and Gunicorn to power my front end iOS applications. Up until now, I've been using simple GET, PUT, POST requests to send and receive json data from my iOS application to my Django server and vice versa. </p> <p>This setup has been solid however, I would like to implement real time messaging. When I first started out, I used APNS (Apple's Push Notifications Service) to deliver messages real time to recipients. Here is an example of what I used to do:</p> <p>If UserA messaged UserB, I would send the message to the Django Server via JSON, process it in a Django view, use <a href="https://github.com/samuraisam/pyapns">pyAPNS</a> - a python wrapper for APNS and it would send a push notification to UserB (the recipient) along with a payload size of 256 bytes. This worked well however it also has a few cons. </p> <p>If the recipient chooses to disable push notifications, then they will not receive the message. When you implement core data in your iOS app, this can be quite messy if you cache objects.</p> <p>So this leaves me with another option. Building something that is socket based that can work with Django and send the payload as JSON. Any ideas?</p> |
12,142,356 | 0 | Send a Complex Object as a Parameter to Post Action in ASP.NET MVC3 <p>I try to send a parameter with <code>submit</code> button to post action so there is my sample:</p> <pre><code>@using(Html.BeginForm(actionName: "Search", controllerName: "MyController", routeValues: new { rv = "102" })) { ... <input type="submit" value="Search" /> } </code></pre> <p>And this is My Search Action:</p> <pre><code>[HttpPost] public virtual ActionResult Search(string rv, FormCollection collection) { ... } </code></pre> <p>So Every thing is fine until now, </p> <p>Then I try to Send a complex object like a <code>Dictionary<string, string></code></p> <p>So you can just replace <code>string</code> type of <code>rv</code> parameter with <code>Dictionary<string, string></code> and send a dictionary, but in this case the <code>rv</code> value always returned a dictionary with 0 count? where is the problem? How can I send a dictionary to post action? </p> <p><strong>Update</strong></p> <p>I Also try this one but not worked yet (Mean rv steel is a dictionary with 0 count):</p> <pre><code>@using(Html.BeginForm(actionName: "Search", controllerName: "MyController", routeValues: new { rv = Model.MyDictionary }, method: FormMethod.Post, htmlAttributes: new { @class = "FilterForm" })) { ... } [HttpPost] public virtual ActionResult Search(Dictionary<string, string> rv, FormCollection collection) { ... } </code></pre> |
14,171,481 | 0 | Virtualbox Headless: not starting via systemd <p>Already tried <a href="https://bbs.archlinux.org/viewtopic.php?id=147591" rel="nofollow">this Topic</a> but doesn't solved it</p> <p>I have placed a file called vbox.service under /lib/systemd/system/vbox.service with the following content:</p> <pre><code>[Unit] Description=Virtualbox Headless VM [Service] ExecStart=/usr/bin/VBoxHeadless --startvm 4decf7c1-7eda-461c-92aa-835d2405a22e ExecStop=/usr/bin/VBoxManage controlvm 4decf7c1-7eda-461c-92aa-835d2405a22e poweroff User=my_user [Install] WantedBy=muti-user.target </code></pre> <p>If I start and stop it via <code>sudo systemctl start vbox</code> and <code>sudo systemctl stop vbox</code>, everything works fine Then i entered the following: <code>sudo systemctl enable vbox</code>, but it wont start at boot Here is the output</p> <pre><code>sudo systemctl status vbox vbox.service - Virtualbox Headless VM Loaded: loaded (/usr/lib/systemd/system/vbox.service; enabled) Active: inactive (dead) CGroup: name=systemd:/system/vbox.service Jan 05 02:38:59 exia pulseaudio[1428]: [pulseaudio] main.c: Daemon startup failed. Jan 05 02:40:08 exia systemd[1]: Started Virtualbox Headless VM. Jan 05 02:42:02 exia systemd[1]: Stopping Virtualbox Headless VM... Jan 05 02:42:02 exia VBoxManage[1546]: 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100% Jan 05 02:42:02 exia VBoxHeadless[1375]: Oracle VM VirtualBox Headless Interface 4.2.6_OSE Jan 05 02:42:02 exia VBoxHeadless[1375]: (C) 2008-2012 Oracle Corporation Jan 05 02:42:02 exia VBoxHeadless[1375]: All rights reserved. Jan 05 02:42:02 exia VBoxHeadless[1375]: VRDE server is listening on port 3389. Jan 05 02:42:02 exia VBoxHeadless[1375]: VRDE server is inactive. Jan 05 02:42:02 exia systemd[1]: Stopped Virtualbox Headless VM. </code></pre> <p>/usr/bin/VBoxHeadless --startvm 4decf7c1-7eda-461c-92aa-835d2405a22e works fine Any ideas, though?</p> |
15,473,697 | 0 | <p>To update only <strong>coffee-script</strong>: </p> <blockquote> <p>sudo npm update coffee-script -g</p> </blockquote> |
36,315,549 | 0 | <p>I've had good luck with generic container functions:</p> <pre><code>template <class Map> void PrintMapToStream(std::ostream &stream, const Map &map) { for (auto &elem : map) stream << elem.second << ' '; stream << std::endl; } </code></pre> <p>Of course, this will fail with confusing error messages if you call it on something that doesn't allow you to iterate over pairs.</p> |
30,244,036 | 0 | How pass list<object> into webgrid <p>I'm trying to put into webgrid collection</p> <pre><code>public class MyClass() { List<Row> rows {get; set;} } public class Row() { public string code {get; set;} } grid.Column("Amount", format: @<text> @Html.TextBoxFor(model => model.rows.FirstOrDefault().code, new { @class = "edit-mode", size = 5 }) </text>), </code></pre> <p>Using <code>model.rows.FirstOrDefault().code</code> it works but returns first element of collection in each row. </p> <p><code>model.rows.GetEnumerator().Current.code</code> returns nothing</p> <p>How to get right desision to get each element of collection in own row</p> |
4,531,853 | 0 | <p>It sounds like your problem is more related to developing on Windows than the Android SDK itself. I got it up and running pretty quickly on my 64 bit Win7 box, but I really prefer to develop in Linux. Once I sorted some silly issues with eclipse dependencies out, it was incredibly simple to run and keep updated.</p> <p>I suspect most hardcore android devs (and the people who build the tools at Google) run Linux of some flavor on their boxes - so it isn't surprising that the tools work well there.</p> <p>Eclipse isn't really the alpha version of websphere - it's a perfectly usable and stable tool in it's own right. Fedora isn't the alpha for RHEL either - it's just more bleeding edge. You can run a perfectly stable Fedora system, but most companies go with RHEL because of the support options.</p> <p>The Android plugins and SDKs are certainly under active development, which is a good thing. That doesn't necessarily make them Beta quality.</p> <p>Eclipse is used incredibly widely. It's adequately tested. The Android SDKs work just fine for a majority of users. I'm sorry you had problems with them, but as you admitted, you're running an unusual configuration. </p> <p>Windows is designed to run with every user as an administrator - Development tools usually assume this, with hardware development tools doubly so. It's a reasonable assumption. Even under Linux, Android development really works better with root access. You're trying to do things with the underlying hardware that normal users shouldn't be able to do.</p> |
16,660,614 | 0 | Change php error reporting to hide warnings for specific site only <p>Imagine a couple of <code>sites-enabled</code> available from <code>/etc/apache2/sites-available</code>. (Only Debian-based distros work like this.)</p> <p>Is it possible to mute <code>warning</code> messages from php scripts from <em>a specific site</em>, without touching the actual <code>htdocs</code>?</p> <p>Normally there are a couple of solutions to achieve someting related:</p> <ol> <li>Add an <code>error_reporting()</code> directive e.g. <code>error_reporting(E_ERROR);</code> to the scripts executed.</li> <li>Set php_flags in <code>.htaccess</code> files like so: <code>php_flag display_errors off</code></li> <li>Use <code>ini_set</code> inside scripts:<br> <code>ini_set('display_errors', 'Off');</code><br> <code>ini_set('display_startup_errors', 'Off');</code><br> <code>error_reporting(0);</code></li> <li>Prepend <code>@</code> to functions that throw warnings or errors.</li> <li>Change <code>php.ini</code> to actually say<br> <code>error_reporting = E_ALL ^ E_WARNING</code><br> <code>display_errors = 1</code> </li> </ol> <p>However, these all mean touching the htdocs or having the change applied globally. Imagine the <code>htdocs</code> are mounted read-only. How would I suppress warnings (or notices) for certain sites only?</p> <p>I am assuming Debian/Ubuntu has <code>a2ensite</code> specific configurations for a reason and I am hoping I can alter those. There is a <code>log_level</code> directive in the example 'site available' configuration, but this handles the amount of messages logged. Not the messages output by the php scripts.</p> <p>Manually adding sections in <code>php.ini</code> or <code>apache2.conf</code> or <code>httpd.conf</code> will also work. If it is possible.</p> <p>See also:</p> <ul> <li><a href="http://www.php.net/manual/en/function.error-reporting.php" rel="nofollow">http://www.php.net/manual/en/function.error-reporting.php</a></li> </ul> |
14,936,999 | 0 | <p>Comma separates multiple selectors, so you were searching for inputs named "weekday" <em>and</em> elements of any type with value = 1.</p> <p>To combine both criteria in one selector, just add them after one another:</p> <pre><code>$('input[name=weekday][value=1]').attr("checked", "checked"); </code></pre> |
16,051,158 | 0 | How does CRM 2011 load and manage plugins in sandbox mode? <p>I have 2 plugin assemblies which are sharing the proxy code generated by crmsvcutil. The proxy code file tends to be large(14+ MB) and it seems to bloat up the Plugin Dlls.</p> <p>I am thinking that it might make sense to offset the proxy code into a separate assembly and deploy it to the GAC on the CRM server.This would reduce the bloat in the plugin assemblies and also reduce the memory footprint since only a single copy of the proxy code would be loaded into the process space.</p> <p>The question is, how does CRM load individual plugin assemblies? Are they all loaded into the same process space or are they loaded into separate app domains?</p> <p>If they are loaded into separate app domains then it defeats the purpose of having a separate assembly containing the generated proxy code since it will be loaded separately into both app domains anyways.</p> <p>Any thoughts appreciated</p> |
1,896,709 | 0 | <p>If you really mean ASCII, you can't possibly rescue Hebrew characters. ASCII is only the 7-bit character set up to <code>\x7F</code>.</p> <p>So what kind of strings does this Windows program read? If it's ASCII, or Latin-1, you'll never get Hebrew. More likely it's “the current system code page”, also (misleadingly but commonly) known in Windows as ‘ANSI’.</p> <p>If that's the case you will have to set the system code page on every machine that runs the Windows program to Hebrew (code page 1255). I believe shp files have no character encoding information at all, so the shapefiles will only ever work correctly on machines with this code page set (the default only in the Israel locale). (Apparently <code>.dbf</code> exports can have an accompanying <code>.cpg</code> file to specify the encoding, but I've no idea if the program you're using supports that.)</p> <p>Then you'd have to export the data as code page 1255, or the nearest you're going to get in Postgres, ISO-8859-8. Since the export script doesn't seem to have any option to do anything but take direct bytes from the database, you'd have to create a database in the ISO-8859-8 encoding and transfer all the data from the UTF-8 database to the 8859-8 one, either directly through queries or, perhaps easier, using <code>pgdumpall</code> and loading the SQL into Notepad then re-saving it as Hebrew instead of UTF-8 (adjusting any encoding settings listed in SQL DDL as you go).</p> <p>I wonder if the makers of the Windows program could be persuaded to support UTF-8? It's a bit sad to be stuck with code-page specific software in this century.</p> |
18,759,997 | 0 | How does iOS handle local Notification in background mode? <p><code>didReceiveLocalNotification</code> is called when a notification is fired in active mode but how does iOS handles notification in background mode (not active mode, application is terminated may be) before app is active by swiping or clicking the notification.</p> <p>Or</p> <p>Mainly I want to know how to conditionally handle local notification to be on/off (off means not to cancel previous notification but just don't fire it) in background Mode?</p> <p>I am currently checking this condition in <code>didReceiveLocalNotification</code> but that way I am not able to handle it in background mode?</p> |
15,152,564 | 0 | Changing textField border color iOS <p>I want to change <strong>UITextField border</strong> color. Is it possible to customize the color of border? I searched all options in <code>xib</code> but I did not found any option to change <code>border color</code>.</p> |
18,374,951 | 0 | <p>There is a nice MX bean for this:</p> <pre><code>OperatingSystemMXBean.getSystemLoadAverage() </code></pre> <p>that gets the overall load average. You can then divide this by the number of CPUs for the average per-CPU load.</p> |
29,668,115 | 0 | <p>I think the problem is float precision.</p> <p>Basically you use a very big float (4 billion) in a division and expect a very small one (0-1) as a result. But the big float is so imprecise compared to the range (0-1) that the result you get is just noise. </p> <p>What you need to do is get those two ranges closer. You can either use a 16 bits int texture instead or you can divide the texture sample with an integer division before converting it to float (and then divide by a smaller float). </p> |
22,396,406 | 0 | Cordova Android 4.3 Ajax Status 404 <p>I am writing an Android app using <code>Cordova 3.4.0</code>.</p> <p>In the app I make the following ajax request using jquery...</p> <pre><code>$.ajax ({ url: 'http://www.[mydomain].com/api/v1', type: 'GET', username: id, password: pwd, xhrFields: { withCredentials: true }, }) .done (function (response) { doSomethng(); }) .fail (function (response) { console.log(response); }); </code></pre> <p>On <code>Android 4.4.x</code> the request works as expected, however on <code>Android 4.3</code> (both emulator and device) it fails and the following is logged to the console...</p> <pre><code>readystate: 4 status: 404 statusText: "error" </code></pre> <p>I have <code><access origin="*" /></code> in the <code>config.xml</code> and </p> <p><code><uses-permission android:name="android.permission.INTERNET" /></code> </p> <p>in the AndroidManifest.xml. I can also confirm that the request is not making it to my web service and nothing is logged on that end.</p> <p>I am at a loss as to what might be blocking the request. I know that the WebView component is different in <code>4.4.x</code> than in previous versions but I am not sure if that has anything to do with it. Any help would be appreciated. </p> |
39,956,077 | 0 | reading in csv file and storing in arrays <p>the practice question i got says that i need to</p> <p>create a java code that reads in csv file with name and height. </p> <p>to read a file you must get a file name from user as string. </p> <p>then you must store contents of file into two arrays one for name (string) and height(real number).</p> <p>You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).</p> <p>then prompt the user for name you want height of. it should output the height for userinput.</p> <p>example csv file is </p> <p>chris,180</p> <p>jess,161</p> <p>james, 174</p> <p>its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation</p> <pre><code>import.java.util.*; private class StudentNameHeight private void main (string [] args) { String filename; Scanner sc = new scanner(system.in); System.out.println("enter file name") filename = sc.nextline(); readFile (filename); } private void readFile (String filename) { FileInputStream fileStrm = null; InputStreamReader rdr; BufferedReader bufRdr; try { fileStrm = new FileInputStream(filename); rdr = new InputStreamReader(fileStrm); bufRdr = new BufferedReader(rdr); // ? catch (IOException e) { if (fileStrm != null) { try {fileStrm.close(); } catch (IOException e2){} } System.out.println("error in processing" + e.getMessage()); } } </code></pre> <p>im new to java so, any small tip or help would be great </p> <p>thanks</p> |
32,378,194 | 0 | <blockquote> <p>the error messages are "expected illegal start of type" on writeUTF method.</p> </blockquote> <p>The problem is that you have put statements into a class body.</p> <p>The those statements need to go into a method. Your text book or tutorial should explain this.</p> |
21,977,444 | 0 | Asp.Net MVC validation messages overriding client side validations <p>In my Asp.Net Mvc application I have a scenario where I have to </p> <ol> <li>Check if control value is not null</li> <li>value entered in control is not "Search"</li> </ol> <p>How can I achieve this with validation attributes?</p> <p>I tried [Required] attribute on top of modal property and wrote a client side validation for "search". But error message shown by [required] attribute is overriding client side validation. any help? </p> |
11,914,693 | 0 | <p>How about adding a query string parameter <code>hl=en</code>? Google supports it on some of its websites, chances are that Google Play website supports it too.</p> <p>If I call Google Play website with:</p> <p><a href="https://play.google.com/store?hl=en">https://play.google.com/store?hl=en</a></p> <p>I got english locales. If I call it with</p> <p><a href="https://play.google.com/store?hl=de">https://play.google.com/store?hl=de</a></p> <p>I got German locales etc.</p> |
28,939,109 | 0 | How to compare the Data in CSV file with Data in the Oracle table? <p>Here we are having one table in Oracle and i have copies that table data into CSV file. Now we have to compare whether data is correct or not.</p> |
26,643,484 | 0 | <p>So thanks to Guffa I realized that even though I had broken the push statement into different lines, it was treated as one. I had thought the problem was with my .push implementation, but rather it was a problem with one of the variables being pushed. </p> <p>It turns out I had missed a return on </p> <pre><code>var callExtData = checkCallExtensions(campaign); </code></pre> <p>and so callExtData was empty, hence undefined. </p> <p>Thanks!</p> |
18,091,654 | 0 | <p>This is a specific case of the general CSV parsing problem. The general solution is provided by Lorance Stinson (google <code>Stinson awk CSV parser</code>) but IMHO the simplest way to deal with this specific issue is to convert newlines within double quotes to some other character, do whatever you want with the file in single-line-per-record format, then convert back, e.g.:</p> <pre><code>$ cat file "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" </code></pre> <p>To convert to single line:</p> <pre><code>$ awk -v FS= '{for (i=1;i<=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file "Test_data1" "Test_data2" "1s" "452" "Test♥data643" "♥" "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test♥data754" "♥" "5d" "Non System" "Association" </code></pre> <p>and to convert back is a simple <code>tr</code>:</p> <pre><code>$ awk -v FS= '{for (i=1;i<=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file | tr '♥' ' \n' "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" </code></pre> <p>The above uses control-C as a replacement for the newline within quotes, pick whatever character you like (or string if you want to use awk or sed rather than tr to convert back to newlines).</p> <p>Just insert the command to do whatever you want with your original file in between the awk and the tr, e.g. sort in reverse:</p> <pre><code>$ awk -v FS= '{for (i=1;i<=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file | sort -r | tr '♥' '\n' "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" </code></pre> |
25,863,380 | 0 | angularjs Rest API <p>I've read up many articles on angularjs and REST but could not found any solution. Through java script I am calling api method, which is routed method as:</p> <pre><code>[Route("api/Comments/{docId}/comment/{revId}/get/{size}/getNumber/{number}")] [HttpPost] public IEnumerable<Student> Get(int docId,int revId,int size, int number) { // loadienter code hereng list here return list.ToList(); } //java script code var url='api/students/' + docId + '/student/' + revId + '/get/'+size+'/getNumber/'+number'; $http.get(url).success(function (response) { if (callback) callback(response.result); }; </code></pre> <p>But the method in controller class is not executing..How to solve this issue? P Please give me some suggestions..</p> |
36,906,494 | 0 | <p>Default namespaces for new queries are stored in <code>%AppData%\LINQPad\DefaultQuery.xml</code></p> <p>As of v5.06.02, LINQPad lets you copy/move this file into the LINQPad.exe directory, and if present, it will take precedence over the copy in <code>%AppData%\LINQPad</code>.</p> <p>This means you can now share default namespaces with a team, as long as you run LINQPad.exe from the same shared folder. You can share other data in a similar manner, including <a href="https://www.linqpad.net/PortableDeployment.aspx" rel="nofollow">queries, drivers, plug-ins, connections and default references</a>.</p> |
18,871,073 | 0 | Enabling link in yii <p>My question is how to enable a particular link for multiple user class. Currently I am doing in the following way for one user class </p> <p>in layouts/main.php</p> <pre><code>array('label'=>'Users', 'url'=>array('/user/index'), 'visible'=>Yii::app()->user->checkAccess('admin')) </code></pre> <p>But what if I want to allow another class called superadmin then how should I do it? I can't do it like this</p> <pre><code>array('label'=>'Users', 'url'=>array('/user/index'), 'visible'=>Yii::app()->user->checkAccess('admin'), 'visible'=>Yii::app()->user->checkAccess('superadmin')) </code></pre> |
10,502,259 | 0 | <p>It depends on your skills on converting PSD to WordPress Template. Usually for a basic design I took 5hrs only. It includes the WordPress installation and setting-up the theme. Following are the factors to be considered when calculating the time:</p> <ol> <li>Complexity of PSD Design</li> <li>jQuery animations</li> <li>No. of pages/content</li> <li>Additional features needed by the client.</li> </ol> <p>Hope this will help.</p> |
7,098,736 | 0 | <p>The default resizing method used by <code>thumbnail</code> is NEAREST, which is a really bad choice. If you're resizing to 1/5 of the original size for example, it will output one pixel and throw out the next 4 - a one-pixel wide line has only a 1 out of 5 chance of showing up <em>at all</em> in the result!</p> <p>The surprising thing is that BILINEAR and BICUBIC aren't much better. They take a formula and apply it to the 2 or 3 closest pixels to the source point, but there's still lots of pixels they don't look at, and the formula will deemphasize the line anyway.</p> <p>The best choice is ANTIALIAS, which appears to take all of the original image into consideration without throwing away any pixels. The lines will become dimmer but they won't disappear entirely; you can do an extra step to improve the contrast if necessary.</p> <p>Note that all of these methods will fall back to NEAREST if you're working with a paletted image, i.e. <code>im.mode == 'P'</code>. You must always convert to 'RGB'.</p> <pre><code>from PIL import Image im = Image.open(fn) im = im.convert('RGB') im.thumbnail(size, Image.ANTIALIAS) </code></pre> <p>Here's an example taken from the electronics.stackexchange site <a href="http://electronics.stackexchange.com/questions/5412/easiest-and-best-poe-ethernet-chip-micro-design-for-diy-interface-with-custom-ard/5418#5418">http://electronics.stackexchange.com/questions/5412/easiest-and-best-poe-ethernet-chip-micro-design-for-diy-interface-with-custom-ard/5418#5418</a></p> <p>Using the default NEAREST algorithm, which I assume is similar to the results you had:</p> <p><img src="https://i.stack.imgur.com/mcmmd.png" alt="NEAREST"></p> <p>Using the ANTIALIAS algorithm:</p> <p><img src="https://i.stack.imgur.com/zgYAx.png" alt="ANTIALIAS"></p> |
32,811,632 | 0 | <p><a href="https://developer.android.com/training/basics/actionbar/styling.html" rel="nofollow">https://developer.android.com/training/basics/actionbar/styling.html</a></p> <p>Here you have everything explained in detail about styling the Action Bar.</p> <p>Best regards</p> |
30,734,868 | 0 | <p>You can use <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instp/NSString/hash" rel="nofollow"><code>NSString.hash</code></a>, or yes, other languages' characters are also represented by numbers: if you don't mind the size, you can contact them. <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">Base64</a> also creates (hexadecimal) numbers from strings.</p> |
24,887,930 | 0 | <p>The answer of you question...<code>You can't.</code></p> <blockquote> <p>Some other help:</p> </blockquote> <p>You can select all IDs once by </p> <pre><code> public String getId() { String ids = ""; String[] culumns = new String[] {ID,..}; Cursor c = ourDatabase.query(LOCATER_TABLE, culumns, null, null, null,null, null); int id = c.getColumnIndex(ID); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { ids = ids + "\n"+c.getColumnIndex(LOCATER_ID); } return ids; } </code></pre> <p>Or a particular Id through some same row item/reference..like <code>select id where name = ..</code> or something like this.</p> |
25,921,375 | 0 | <p>This is meant to complement Richard's, as it felt a little too substantial to simply edit into his.</p> <p>A typical code pattern for this sort of thing would be:</p> <pre><code>#Initialize an empty list of the desired length dfs <- vector("list",3) #Fill the list with data frames, naming as we go for (i in seq_along(dfs)){ dfs[[i]] <- data.frame(x = runif(5),y = runif(5)) names(dfs)[[i]] <- paste0("df",i) } </code></pre> <p>where the use of <code>assign</code> is typically frowned upon as bad (stylistically). If the naming of the data frames is very regular, you don't even need to do it in the loop:</p> <pre><code>names(dfs) <- paste0("df",seq_along(dfs)) </code></pre> <p>you can do it in a vectorized fashion as above. And as I mentioned below Richard's answer, even though having them all in a list is never worse, and usually better, than having them as separate objects, you can convert the list to separate objects via:</p> <pre><code>list2env(dfs,envir = .GlobalEnv) </code></pre> |
9,422,906 | 0 | MP3 doesn't play when I press stream <p>I am trying to play a MP3 from a stream but the issue is after I press play it would automatically play. Also the play button doesn't play the audio it just sets it to stream. How can I make my MP3 automatically play?</p> <pre><code> play.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (!mediaPlayer.isPlaying()) { try { mediaPlayer.setDataSource(url); mediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); if(!mediaPlayer.isPlaying()){ mediaPlayer.start(); play.setImageResource(R.drawable.ic_media_pause); }else { mediaPlayer.pause(); play.setImageResource(R.drawable.ic_media_play); } primarySeekBarProgressUpdater(); } }}); sb.setMax(99); sb.setOnTouchListener(this); mediaPlayer = new MediaPlayer(); mediaPlayer.setOnBufferingUpdateListener(this); mediaPlayer.setOnCompletionListener(this); } private void primarySeekBarProgressUpdater() { sb.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); if (mediaPlayer.isPlaying()) { notification = new Runnable() { public void run() { primarySeekBarProgressUpdater(); } }; handler.postDelayed(notification,1000); } } public boolean onTouch(View v, MotionEvent event) { if(v.getId() == R.id.progress_bar){ /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/ if(mediaPlayer.isPlaying()){ SeekBar sb = (SeekBar)v; int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress(); mediaPlayer.seekTo(playPositionInMillisecconds); } } return false; } public void onCompletion(MediaPlayer mp) { play.setImageResource(R.drawable.ic_media_play); mediaPlayer.stop(); } public void onBufferingUpdate(MediaPlayer mp, int percent) { sb.setSecondaryProgress(percent); } } </code></pre> <p>Am I doing anything wrong? I click play and I see my seekbar filling up but it wont play. </p> <p>I also get this message:</p> <pre><code>E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) </code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.