text
stringlengths
15
59.8k
meta
dict
Q: PowerShell How to use -and in Where-Object I want to filter a command result using two conditions. Here are my commands $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property ConfigurationFlags -NotLike '*DISABLED*' | ft Name, InstanceId -AutoSize and the next filter is $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize both of them works separately but I want to join them using and command. I tried to use -AND as following command but it keeps raising errors Get-PnpDevice | Sort-Object -Property Name | Where-Object{ ( ConfigurationFlags -NotLike '*DISABLED*') -and ( FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize A: Simply use the The $_ automatic variable in your Where-Object to reference the property names: Get-PnpDevice | Sort-Object -Property Name | Where-Object{ ( $_.ConfigurationFlags -NotLike '*DISABLED*') -and ( $_.FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize A: You can pipe 'Where' clauses together... it's simpler syntax and easier to read Get-PnpDevice | Sort-Object -Property Name | Where ConfigurationFlags -NotLike '*DISABLED*' | Where FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize
{ "language": "en", "url": "https://stackoverflow.com/questions/56297144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pay with paypal and recurring using billing agreement API I just want to understand that how can I redirect user to PayPal account ==> login ==> agreed to payment teand based on selection I can call my Billing Agreement Rest API. Do I need to setUp My Own UI to process payment ? A: The most important thing here is that you cannot sign a billing agreement without a billing plan So the first thing you need to consider is how you could create a plan. Its very simple just trigger this api: https://developer.paypal.com/docs/api/payments.billing-plans/v1/ Now you have your plan Id now you can subscribe a user with this plan id by triggering this API https://developer.paypal.com/docs/api/payments.billing-agreements/v1/#billing-agreements_create
{ "language": "en", "url": "https://stackoverflow.com/questions/48515848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sending email with delayed job within Rails_admin causes an error I have a custom collection action in Rails Admin as follows: require 'rails_admin/config/actions' require 'rails_admin/config/actions/base' module RailsAdminSendNewsletter end module RailsAdmin module Config module Actions class SendNewsletter < RailsAdmin::Config::Actions::Base # Is the action on a model scope (Example: /admin/team/export) register_instance_option :collection? do true end register_instance_option :link_icon do 'icon-share' end register_instance_option :pjax? do false end register_instance_option :controller do Proc.new do if request.xhr? resources = Resource.where(:for_newsletter => true) subscriber = Subscriber.all.each do |subscriber| NewsletterMailer.delay.newsletter(subscriber, resources) end resources.each do |resource| resource.update_column(:sent_on, Time.now) end end flash[:success] = "The Newsletter has successfully been sent." redirect_to back_or_index end end end end end end produces the following error: ArgumentError (wrong number of arguments (2 for 1)): lib/rails_admin_send_newsletter.rb:30:in `block (3 levels) in <class:SendNewsletter>' lib/rails_admin_send_newsletter.rb:29:in `each' lib/rails_admin_send_newsletter.rb:29:in `block (2 levels) in <class:SendNewsletter>' Here is the newsletter mailer: class NewsletterMailer < ActionMailer::Base default from: ' "Agile Designers" <[email protected]>' def newsletter(subscriber, resources) @subscriber = subscriber @resources = resources @twitter = "https://twitter.com/agiledesigners" mail(:to => subscriber.email, :subject => "Agile Designer Newsletter") end end I don't understand what causes it Any help appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/14831316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone SDK have a different title on the tab bar and the navigation bar I have a simple question (maybe not a simple answer). Currently I have an iPhone app and I tab bar and navigation set up on it. When I set the self.title it puts it in both the tab bar and the navigation bar. I was wondering if there was a way to have a different title on the navigation bar and tab bar? A: You're setting the title of the whole view, which in turn automatically sets the title of the tabBar and the nav controller. To set the title of them each individually, You first set the nav bar by accessing the nav item: [[self navigationItem] setTitle:(NSString *)]; Then you set the tabBar title by accessing the tab bar item and setting its title like so: [self.tabBarItem setTitle:(NSString *)]; Good Luck! A: use self.navigationItem.title for the navigation bar. A: This is a common mistake and happened to me so many times. To get around this, every ViewController comes with a navigationItem property giving you even further options. Use following line inside your ViewControllers to set the title: self.navigationItem.title = @"Your Desired Title";
{ "language": "en", "url": "https://stackoverflow.com/questions/7394864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Event not working on templated dojo widget My widget makes the form but the event that is suposed to happen doesn't. When the button is clicked it is supposed to grab the value in the input box then put it into URL that is being requested then paste that page into the results div. EDIT NOTE: Found out that if I have the searchNode WITHOUT the dijit Button type the event works but if I apply the dojo-data-type it doesn't. Widget: /** * Widget for creating a quick search form. */ define([ "dojo/_base/declare", "dojo/request", "dijit/_WidgetBase", "dijit/_OnDijitClickMixin", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "dijit/form/Button", "dijit/form/TextBox", "dojo/text!./templates/quickSearch.html" ],function(declare, request, _WidgetBase, _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin, Button, TextBox, template){ return declare("js/widget/SASearch", [_WidgetBase, _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin], { // set our template templateString: template, // some properties baseClass: "searchWidget", // define an onClick handler _onClick: function() { var query = this.queryNode.value; alert(query); request("quick/" + query).then( function(text) { this.resultsNode.innerHTML = text; alert(text); }, function(error) {} ); } }); }); Template: <div class="${baseClass}"> <div class="${baseClass}Query" data-dojo-attach-point="queryNode" data-dojo-type="dijit/form/TextBox"></div> <div class="${baseClass}Search" data-dojo-attach-point="searchNode" data-dojo-type="dijit/form/Button" data-dojo-attach-event="ondijitclick:_onClick">Search</div><br /> <div class="${baseClass}Results" data-dojo-attach-point="resultsNode"></div> </div> A: Your event has to be data-dojo-attach-event="onClick:_onClick" On the button. Also for the returns on the request, your going to have to use dojo.hitch to hitch this. http://jsfiddle.net/theinnkeeper/qum452gm/
{ "language": "en", "url": "https://stackoverflow.com/questions/31834948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to automatically generate java classes from Neo4j graph database In my application, we choosen Neo4j as database. We have designed the database with all the required nodes and relationships. We are trying to integrate the in our springboot java program with reactive neo4j repository. Now we are planning to create equivalent entities. Is there any way to automatically generate java classes from Neo4j graph database which will be equivalent to @Node and @RelationshipProperties used entities as we create manually. A: No there is no tool for this and this is in general a good thing when it comes to "complex" data in the graph. Spring Data Neo4j (6) does only fetch the relationships and properties of a node that you define in your model. If you would map your graph 1:1 you might end up with ones you do not need. They will pollute your code base and create unnecessary long Cypher statements / data transfers. I would say that there is -in contrast to the usage of RDBMS- a lot of "shared database" usage in the graph world. The partial match of a domain model in the application to the graph model is no exception here. Also a tool that blindly converts your data into a model can only make assumptions. E.g. multiple labels: You can define them in multiple ways depending on your use-case in Spring Data Neo4j. But which one is the right one for the tool? This can produce code that is not your desired outcome and you would have to manually refactor it after creation. Imagine having such a tool in a build chain: You would have to manually fine-tune the resulting model over and over again.
{ "language": "en", "url": "https://stackoverflow.com/questions/63242304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android onLoadCompleteListener how to implement? I have a custom class called "Sound" with SoundPool, I want to implement the loading complete listener so that my activity can play an intro sound and display the "start" button once loading is complete. How would I go about implementing the listener and then testing for the complete status from my activity to make sure everything is loaded then go on to do the above. A small example would be appreciated. MyActivity creates an instance of my class "Sound" so that it can call various sound methods from it. Sound mySound = new Sound(); Most of these are not a problem, because by the time they are called, the loading has completed, however, I need for MyActivity to be able to check if loading has completed before calling mySound.playIntro(); (for example). Maybe the OnLoadCompleteListener isn't the best solution, I'm still learning, so I'm open to ideas, this is just the way I guessed it should be done. Thanks A: It would look somthing like this: SoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener(){ @override onLoadComplete(SoundPool soundPool, int sampleId, int status) { // show button and play intro sound here }}); You should read the android guide for developers. And more specificly for this problem: SoundPool Edit - Corrected a typo, "listner" to "listener"
{ "language": "en", "url": "https://stackoverflow.com/questions/3908756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compare two arrays in PowerShell I try to compare two arrays, but it won't work. #System.Data.DataSet -> $Dataset.Tables.Identifier #System.Xml.XmlElement -> $xmlarray #$Arraytemp = $xmlarray | Where {$Dataset.Tables.Identifier -NotContains $xmlarray.myid} $Arraytemp = $xmlarray | Where {$Dataset.Tables.Identifier -NotContains $x_} Write-Host "Compared Results" $Arraytemp | ft Write-Host "XML Results" $xmlarray | ft Write-Host "SQL Results" $Dataset.Tables.Identifier | ft I read a XML result in an array $xmlarray. It contains the coloumn myid as a unique identifier (and other coloumns). I read a MS SQL result in an array in $Dataset.Tables.Identifier, it only contains a unique identifier. The SQL result contains only a part of the XML array. So I want to know, which rows are the difference, because I want to INSERT them in the database. When I check the result with Write-Host the results looks good. When I compare them, nothing happens. SQL is System.Data.DataSet. SQL is System.Xml.XmlElement. May be the dataformat is not compatible?
{ "language": "en", "url": "https://stackoverflow.com/questions/51918604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: less css mixin with parametric A as default for parametric B I'm currently working with LESS CSS and tried to create a mixin that mimics the default css behavior of shorthand parameters. in css you often declare i.e. margin: 5px 5px 10px; and it's read as margin: 5px 5px 10px 5px; I tried the same with a border-radius mixin .border-radius (@topright: 5px, @bottomright: @topright, @bottomleft: @topright, @topleft: @bottomright) {} I want it to take the first as default for all, if called with one parameter only. If I call it with 2 parameter it should take the first as default for the third and the second as default for the fourth. Is there a way to achieve this behavior with LESS alone? A: The correct way to do this would be to receive just one parameter .border-radius(@px) { -webkit-border-radius: @px; -moz-border-radius: @px; border-radius: @px; } Then you can call it with one parameter: .border-radius(5px); or with many. This requires you to either put them in a variable, or escape them: @myradius: 5px 5px 10px; .border-radius(@myradius); or .border-radius(~"5px 5px 10px"); I read that the Bootstrap project uses the latter version for brevity.
{ "language": "en", "url": "https://stackoverflow.com/questions/10451617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to directly search string in PDF using any programming language Is it possible to search for a particular string in PDF using any programming language without converting it to a text or doc file. I want to search for a string directly without converting it, I tried to convert it to text and then search for the string but it gave me wrong result. Thanks! Kim A: Docotic.Pdf library can be used for your task. Please see my answer for similar question. Disclaimer: I work for the company that develops Docotic.Pdf library. A: 1) Create your own PDF "parser": http://www.quick-pdf.com/pdf-specification.htm Probably could be minimal if you just need text data and not any of the formatting. 2) Find a library in your language of choice that can "natively" read .pdfs (tons of them out there). 3) use a pre-built tool (like pdf2text or pdfgrep): https://unix.stackexchange.com/questions/6704/grep-pdf-files A: If your requirement is to search a for a word and replace it, you can go for Aspose.pdf.Kit A: Poppler contains tools to extract text from a pdf document. Use it to search on documents. A: In Java and C#, you can do that with iText, if the pdf file is not locked. http://itextpdf.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/5827370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to collapse a data table by its ID I am fairly new to r, and I am working with a large data set. I made an example of what my problem is below (data set is tab delineated). Basically I want to collapse all data by its ID number so that all of its attributes are contained in 1 cell instead of many cells. The actual data set I am working with is genomic in nature, with the "ID" being the "gene name" and the "attribute" being the "pathway" that the gene is associated with. My data set is ~5,000,000 rows long. I have tried messing around with cbind and rbind, but they do not seem to be specific enough for what I need. My data set currently looks something like this: ID Attributes 1 apple 1 banana 1 orange 1 pineapple 2 apple 2 banana 2 orange 3 apple 3 banana 3 pineapple And I want it to look like this: ID Attributes 1 apple,banana,orange,pineapple 2 apple,banana,orange 3 apple,banana,pineapple If you have another way besides using r, that would work as well. Thank you for your help A: a base solution. To split df by ID, then paste the Attributes together. Then rbind the list of results. do.call(rbind, by(df, df$ID, function(x) data.frame(ID=x$ID[1], Attributes=paste(x$Attributes, collapse=",")) )) data: df <- read.table(text="ID Attributes 1 apple 1 banana 1 orange 1 pineapple 2 apple 2 banana 2 orange 3 apple 3 banana 3 pineapple", header=TRUE) A: A tidyverse approach would be to group_by your ID and summarise with paste. library(dplyr) df <- read.table(text = " ID Attributes 1 apple 1 banana 1 orange 1 pineapple 2 apple 2 banana 2 orange 3 apple 3 banana 3 pineapple", header = TRUE, stringsAsFactors = FALSE) df %>% group_by(ID) %>% summarise( Attributes = paste(Attributes, collapse = ", ") ) # # A tibble: 3 x 2 # ID Attributes # <int> <chr> # 1 1 apple, banana, orange, pineapple # 2 2 apple, banana, orange # 3 3 apple, banana, pineapple
{ "language": "en", "url": "https://stackoverflow.com/questions/48513045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Sorting a list in OCaml Here is the code on sorting any given list: let rec sort lst = match lst with [] -> [] | head :: tail -> insert head (sort tail) and insert elt lst = match lst with [] -> [elt] | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;; [Source: Code However, I am getting an Unbound error: Unbound value tail # let rec sort lst = match lst with [] -> [] | head :: tail -> insert head (sort tail) and insert elt lst = match lst with [] -> [elt] | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;; Characters 28-29: | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;; ^ Error: Syntax error Can anyone please help me understand the issue here?? I did not find head or tail to be predefined anywhere nor in the code A: Your code seems correct, and compiles for me: Objective Caml version 3.11.1 # let rec sort lst = ... val sort : 'a list -> 'a list = <fun> val insert : 'a -> 'a list -> 'a list = <fun> # sort [ 1 ; 3 ; 9 ; 2 ; 5 ; 4; 4; 8 ; 4 ] ;; - : int list = [1; 2; 3; 4; 4; 4; 5; 8; 9] A: Adding to what Pascal said, the list type is defined as: type 'a list = [] | :: of 'a * 'a list and that's what you are matching your list lst against. A: The symbol “|“ is the horizontal line symbol, it is not l character and the -> are the minus symbol and the bigger symbol. I think you copied and pasted the segment of code in the website of Inria. Please check and rewrite the special symbols. I tested it and it works well. A: Head and tail need not to be defined. They are matched from 'list' you give.
{ "language": "en", "url": "https://stackoverflow.com/questions/2756489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I open a html file, after a php file is run? I am a complete beginner in web development in regards to php. Right not I am using: <form action="phpfile.php"> <input type="submit" value="click on me!"> </form> To open up my php file, which is a simple echo "hello world!" (for testing purposes) The php file that I would use would be this sendmail file <?php $to = '[email protected]'; $subject = 'Mailer Test'; $message = 'This is a test, Thanks Person'; $headers = "From: [email protected]\r\n"; ?> How can, after this is run, a html file would open as soon as the file is done loading? Like a "You have completed the task" page essentially (Also I'm using Xampp which has inbuilt sendmail, so the file does work. Once again temporary before I move onto a webserver) Thanks!! A: use this : header('Location: http://localhost/yourHtmlFile.html'); but make sure your php didn't output anything before it update another workaround is to use include ('yourHtmlFile.html'); A: PHP can answer code written in HTML back to the browser using echo: <?php //do some code $name="superuser"; echo "Hi ".$name; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/40429460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reference a lambda from inside it? I am trying to get height of a view in onCreate method but I couldn't find any way to remove OnGlobalLayoutListener. In Java (working): containerLayout.getViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { containerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this); int width = layout.getMeasuredWidth(); int height = layout.getMeasuredHeight(); } }); In Kotlin (not accepting "this"): containerLayout.viewTreeObserver.addOnGlobalLayoutListener { containerLayout.viewTreeObserver.removeOnGlobalLayoutListener(this) Toast.makeText(applicationContext, "size is "+ containerLayout.height,Toast.LENGTH_LONG).show() } Is there any reference or example for this problem? Thanks. A: What's about extension like this? import android.annotation.SuppressLint import android.os.Build import android.view.View import android.view.ViewTreeObserver inline fun View.doOnGlobalLayout(crossinline action: (view: View) -> Unit) { val vto = viewTreeObserver vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { @SuppressLint("ObsoleteSdkInt") @Suppress("DEPRECATION") override fun onGlobalLayout() { action(this@doOnGlobalLayout) when { vto.isAlive -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { vto.removeOnGlobalLayoutListener(this) } else { vto.removeGlobalOnLayoutListener(this) } } else -> { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { viewTreeObserver.removeOnGlobalLayoutListener(this) } else { viewTreeObserver.removeGlobalOnLayoutListener(this) } } } } }) } Finally, you can call OnGlobalLayoutListener from View directly val view: View = ... view.doOnGlobalLayout { val width = view?.measuredWidth val height = view?.measuredHeight } A: Simple / clear approach (no generics or anonymous objects): You could create the listener in advance, then add / use / remove as needed: private var layoutChangedListener: ViewTreeObserver.OnGlobalLayoutListener? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // create the listener layoutChangedListener = ViewTreeObserver.OnGlobalLayoutListener { // do something here // remove the listener from your view myContainerView.viewTreeObserver.removeOnGlobalLayoutListener(layoutChangedListener) layoutChangedListener = null } // add the listener to your view myContainerView.viewTreeObserver.addOnGlobalLayoutListener(layoutChangedListener) } use case: I had to be able to remove the listener, in order to adjust the layout inside the listener itself - not removing the listener may result in a deadlock A: Referencing a lambda from inside it is not supported. As a workaround, you might use anonymous object instead of lambda SAM-converted to Java functional interface OnGlobalLayoutListener: containerLayout.viewTreeObserver.addOnGlobalLayoutListener(object: OnGlobalLayoutListener { override fun onGlobalLayout() { // your code here. `this` should work } }) A: Another solution is to implement and use self-reference: class SelfReference<T>(val initializer: SelfReference<T>.() -> T) { val self: T by lazy { inner ?: throw IllegalStateException() } private val inner = initializer() } fun <T> selfReference(initializer: SelfReference<T>.() -> T): T { return SelfReference(initializer).self } Then the usage would be containerLayout.viewTreeObserver.addOnGlobalLayoutListener(selfReference { OnGlobalLayoutListener { containerLayout.viewTreeObserver.removeOnGlobalLayoutListener(self) // ... } } Instead of this, self property is used.
{ "language": "en", "url": "https://stackoverflow.com/questions/33898748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Argument to KnockoutJS function is returning the viewModel when not defined Still continuing to understand KO here. I have an argument to one of the KO methods,it works when I pass it an explicit value but when I call the function with no args it does not give <button data-bind="click:LaterCall">click</button> function InvoiceViewModel() { //Data var self = this; self.LaterCall = function (arg) { console.log(arg); // why is this not undefined???? }; } var viewModel = new InvoiceViewModel(); ko.applyBindings(viewModel); http://jsfiddle.net/sajjansarkar/9TMv2/2/ A: Knockout's click binding (and event binding, which click is a subset of) pass the current data as the first argument and the event as the second argument to any handlers. So, arg would be equal to your viewModel in your case. A: The parameter arg will reference the parent and as you can see in your example the actual viewmodel is the parent. Putting an argument there is mainly used when you have nested controllers and want to reference the parent dynamically as stated in the second example here, http://knockoutjs.com/documentation/click-binding.html <ul data-bind="foreach: places"> <li> <span data-bind="text: $data"></span> <button data-bind="click: $parent.removePlace">Remove</button> </li> </ul> <script type="text/javascript"> function MyViewModel() { var self = this; self.places = ko.observableArray(['London', 'Paris', 'Tokyo']); // The current item will be passed as the first parameter, so we know which place to remove self.removePlace = function(place) { self.places.remove(place) } } ko.applyBindings(new MyViewModel()); </script> I would also recommend you not to use self as a parameter name in javascript, instead go for that var that = this;
{ "language": "en", "url": "https://stackoverflow.com/questions/21415644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get all rows from orignal Dataframe which is having number or alpha number in particular column? I have Dataframe Like this in df_init column1 0 hi all, i am fine 1 How are you ? 123 a45 2 123444234324!!! (This is also string) 3 sdsfds sdfsdf 233423 5 adsfd xcvbb cbcvbcvcbc I want to get all those values from this dataframe which is having a number or alpha number I am expecting like this in df_final column1 0 How are you ? 123 a45 1 123444234324!!! (This is also string) 2 sdsfds sdfsdf 233423 A: Use str.contains with \d for match number and filter by boolean indexing: df = df[df.column1.str.contains('\d')] print (df) column1 1 How are you ? 123 a45 2 123444234324!!! (This is also string) 3 sdsfds sdfsdf 233423 EDIT: print (df) column1 0 hi all, i am fine d78 1 How are you ? 123 a45 2 123444234324!!! 3 sdsfds sdfsdf 233423 4 adsfd xcvbb cbcvbcvcbc 5 234324@ 6 123! vc df = df[df.column1.str.contains(r'^\d+[<!\-[.*?\]>@]+$')] print (df) column1 2 123444234324!!! 5 234324@
{ "language": "en", "url": "https://stackoverflow.com/questions/54474875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Short echo repurposed in newer versions of PHP? I have heard from several people that <?= has been re-purposed / replaced in newer versions of PHP, but am unable to find supporting documentation to this change, or to what version(s) it effects. Has short echo been replaced or re-purposed and is there supporting documentation to it? A: The current documentation does not reflect any change of behaviour of shorthand echo (<?=) since version 5.4.0, in which only the necessary configuration to enable it was changed. * *http://php.net/manual/en/function.echo.php
{ "language": "en", "url": "https://stackoverflow.com/questions/30850899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pandas: Adding column with calculations from other columns I have a csv with measurements: YY-MO-DD HH-MI-SS_SSS | x | y 2015-12-07 20:51:06:608 | 2 | 4 2015-12-07 20:51:07:609 | 3 | 4 and I want to add another column with the square root of the sum of x^2+y^2, z=sqrt(x^2+y^2) like this: YY-MO-DD HH-MI-SS_SSS | x | y | z 2015-12-07 20:51:06:608 | 2 | 4 | 4.472 2015-12-07 20:51:07:609 | 3 | 4 | 5 Any ideas? Thank you ! A: Use np.sqrt on the result of the squares: In [10]: df['z'] = np.sqrt(df['x']**2 + df['y']**2) df Out[10]: x y z 0 2 4 4.472136 1 3 4 5.000000 You can also sum row-wise the result of np.square and call np.sqrt: In [13]: df['z'] = np.sqrt(np.square(df[['x','y']]).sum(axis=1)) df Out[13]: x y z 0 2 4 4.472136 1 3 4 5.000000
{ "language": "en", "url": "https://stackoverflow.com/questions/36517311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Map in Fragment: incompatible types cannot be converted to Fragment I checked several solutions on StackOverflow but nothing fitted my special problem. I have several Fragments and I want a google map activity in one of those. So I prepared the layout and created a new google map Activity with the necessary name. When I try to run it it says: Error:(20, 42) error: incompatible types: FragmentScreenD cannot be converted to Fragment Furthermore it is written "Wrong 2nd argument type. Found "com.example.name.yapplication.FragmentScreenD", required "android.support.v4.app.Fragment". After doing this the message did not disappear. package com.example.name.myapplication; import android.support.v4.app.FragmentActivity; import android.os.Bundle; public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); setContentView(R.layout.activity_main); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment1, new FragmentScreenA()).commit(); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment2, new FragmentScreenB()).commit(); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment3, new FragmentScreenC()).commit(); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment4, new FragmentScreenD()).commit(); } } <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="2" android:orientation="horizontal" android:paddingBottom="10dp" android:weightSum="2" > <FrameLayout android:id="@+id/fragment3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="0dp" android:layout_weight="1" /> <FrameLayout android:id="@+id/fragment4" android:layout_width="0dp" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_weight="1" /> </LinearLayout> package com.example.name.myapplication; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class FragmentScreenD extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment_screen_d); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } } A: FragmentScreenD which is extended From FragmentActivity does not Fragment and the second arguement of FragmentManager's replace method needs a Fragment , FragmentScreenD can be started via intent and its behavior is like an Activity, change FragmentActivity to Fragment and implement the methods in FragmentScreenA,B,C,... A: I have several fragments and I want a google map activity in one of those. You don't want an Activity, you want a Fragment, as the error is trying to tell you. You can add a new SupportMapFragment() directly to the FrameLayout, or you need to instead extend that rather than FragmentActivity A: Just take a map fragment in fragment XML and check this link it will helpful to solve problem android MapView in Fragment
{ "language": "en", "url": "https://stackoverflow.com/questions/45259802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nodejs application healthcheck best practice I'm looking into setting up a healthcheck mechanism for nodejs microservices running via container orchestrations. From a nodejs/express point of view, what is considered best practice to ensure that the service is indeed running on a given port on a given container? Eg. A healthcheck middleware or particular nodejs library, using a separate service port etc. A: In order to implement healthcheck in nodejs, use the following use express-healthcheck as a dependency in your nodejs project in your app.js or equivalent code, use the following line app.use('/healthcheck', require('express-healthcheck')()); if your app is up your response will be like { "uptime":23.09 } also it returns a status code of 200 Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/48885862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Next.js refreshes indefinitely when query params are present I'm running a pretty basic Next.js app on local (next dev) and whenever a route has query parameters, it loads an reloads in an infinite loop. I've removed all calls to router.push, router.replace, and window.location but to no avail. When there are no query params present, this doesn't happen, and when I deploy the app for production (next export) I see no such behavior. Any idea what could be going on?
{ "language": "en", "url": "https://stackoverflow.com/questions/75164906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does read_edgelist from networkx not accept arrays/lists as weights? I am using Python and the networkx package to read an edgelist from file in order to build a graph. My edgelist looks something like this: [(0, 114, {'pts': array([[ 1, 822], [ 1, 821], [ 2, 820], [ 3, 819]], dtype=int16), 'weight': 23.38477631085024}), (1, 110, {'pts': array([[ 1, 3], [ 1, 2], [ 2, 1]], dtype=int16), 'weight': 18.414213562373096})] I wrote this edgelist with: nx.write_edgelist(G, 'my_el.edgelist', data=True) My edges are defined by the start and the end node, and following that, I have my weights. Each edge has two weights. The first weight is a array of pixel-coordinates, and the second is a float. The graph was constructed from a skeleton with the ´sknw´ library using the build_sknw function: def build_sknw(ske, multi=False): buf = buffer(ske) nbs = neighbors(buf.shape) acc = np.cumprod((1,)+buf.shape[::-1][:-1])[::-1] mark(buf, nbs) pts = np.array(np.where(buf.ravel()==2))[0] nodes, edges = parse_struc(buf, pts, nbs, acc) return build_graph(nodes, edges, multi) Now I want to read in this edgelist to build a graph. However, Python does not recognize my array of pixel-coords as a single weight-element. I've tried nx.read_edgelist('my_el.edgelist', data=True), which gives me the following error: TypeError: Failed to convert edge data (["{'pts':", 'array([[', '1,', '822],']) to dictionary. nx.read_edgelist('my_el.edgelist', data=['pts', 'weight'] gives me: IndexError: Edge data ["{'pts':", 'array([[', '1,', '822],'] and data_keys ['pts', 'weight'] are not the same length and nx.read_edgelist('my_el.edgelist', data=(('pts', int), ('weight', float'))) gives me IndexError: Edge data ["{'pts':", 'array([[', '1,', '822],'] and data_keys (('pts', <class 'int'>), ('weight', <class 'float'>)) are not the same length I assume that the function is having a problem with either the array as a weight, or with the formatting of the my_el.edgelist file, but I do not really know, how to properly solve this issue without any workarounds via conversion to string, or similar. I'd be thankful if someone can point me in the right direction and help me out with this! A: Dealing with numpy arrays seems to be a major problem for networkx. The function that converts my image skeleton to the graph G however seems to be using numpy arrays. Since I prefer not to alter the imported function, a possible workaround that seemed to mitigate the problem when writing the edgelist to file was to change the array type thus: for (s, e) in G.edges(): G[s][e]['pts'] = G[s][e]['pts'].tolist() It might not be the most computationally efficient, and doesn't deal with the root of the problem, but will get the job done, in case anybody encounters a similar issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/64318230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Noda Time Date Comparison I am new to Noda Time and I basically want to compare if a date has expired or not. In my case I have an object with the date it was created, represented by a LocalDate and the amount of months it's valid as an int, so I wanted to do a simple: if ( Now > (dateCreated + validMonths) ) expired = true; But I can't find in the Noda Time documentation the proper way to get the Now Date (they only show how to get the Now Time as SystemClock.Instance.Now) and the proper way to handle time comparisons. For example if today is January 1st 2015 and the document was created in December 1st 2014, and it was valid for one month, today it expires its one month validity. I miss methods such as isBefore() and isAfter() to compare dates and times. Simple overloads of the < > operators could also be very helpful. EDIT: 1 - Sorry, there are < > operators to compare dates. 2 - I solve my problem using this code (not tested yet!): ... LocalDate dateNow = this.clock.Now.InZone(DateTimeZoneProviders.Tzdb.GetSystemDefault()).LocalDateTime.Date; LocalDate dateExpiration = DataASO.PlusMonths(validity); return (dateNow < dateExpiration); A: To get the current date, you need to specify which time zone you're in. So given a clock and a time zone, you'd use: LocalDate today = clock.Now.InZone(zone).Date; While you can use SystemClock.Instance, it's generally better to inject an IClock into your code, so you can test it easily. Note that in Noda Time 2.0 this will be simpler, using ZonedClock, where it will just be: LocalDate today = zonedClock.GetCurrentDate(); ... but of course you'll need to create a ZonedClock by combining an IClock and a DateTimeZone. The fundamentals are still the same, it's just a bit more convenient if you're using the same zone in multiple places. For example: // These are IClock extension methods... ZonedClock zonedClock = SystemClock.Instance.InTzdbSystemDefaultZone(); // Or... ZonedClock zonedClock = SystemClock.Instance.InZone(specificZone);
{ "language": "en", "url": "https://stackoverflow.com/questions/28218324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DataFrame column data to series I have the following DataFrame that contains some rainfall data. I want to reformat this so that I get a Series with 24 entries indexed with 'Month-Year' so that it will be easier to plot this as a line. JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC Year 2015 96.6 58.9 23.5 18.6 62.9 26.7 60.0 108.6 67.9 58.1 78.0 80.4 2016 131.8 54.2 80.2 51.2 64.1 91.3 17.4 38.8 50.9 29.8 100.6 17.4 I was thinking I could iterate through each row and pull out each month individually and add it to a series. I was wondering if there was a better way. A: Use unstack with to_frame i.e ndf = df.unstack().to_frame().sort_index(level=1) 0 Year JAN 2015 96.6 FEB 2015 58.9 MAR 2015 23.5 APR 2015 18.6 MAY 2015 62.9 JUN 2015 26.7 JUL 2015 60.0 AUG 2015 108.6 SEP 2015 67.9 OCT 2015 58.1 NOV 2015 78.0 DEC 2015 80.4 JAN 2016 131.8 FEB 2016 54.2 MAR 2016 80.2 APR 2016 51.2 MAY 2016 64.1 JUN 2016 91.3 JUL 2016 17.4 AUG 2016 38.8 SEP 2016 50.9 OCT 2016 29.8 NOV 2016 100.6 DEC 2016 17.4 If you need index as a string then ndf.index = ['{} {}'.format(i,j) for i,j in ndf.index.values] If you need it as a datetime then ndf.index = pd.to_datetime(['{} {}'.format(i,j) for i,j in ndf.index.values])
{ "language": "en", "url": "https://stackoverflow.com/questions/46744512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How recursively find files with Unicode names in C++? I found and modify solution from here: #include <iostream> #include <windows.h> #include <vector> #include <fstream> using namespace std; //wofstream out; void FindFile(const std::wstring &directory) { std::wcout << endl << endl << endl << "FindFile(" << directory << ")" << std::endl; std::wstring tmp = directory + L"\\*"; WIN32_FIND_DATAW file; HANDLE search_handle = FindFirstFileW(tmp.c_str(), &file); if (search_handle != INVALID_HANDLE_VALUE) { std::vector<std::wstring> directories; do { std::wcout << std::endl; std::wcout << " [" << file.cFileName << "]" << std::endl; tmp = directory + L"\\" + std::wstring(file.cFileName); if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ((!lstrcmpW(file.cFileName, L".")) || (!lstrcmpW(file.cFileName, L".."))) { std::wcout << "continuing..." << std::endl; } else { std::wcout << "saving path to this directory" << std::endl; directories.push_back(tmp); } } else { std::wcout << "save [" << tmp << "] as file" << std::endl; } //std::wcout << tmp << std::endl; //out << tmp << std::endl; } while (FindNextFileW(search_handle, &file)); std::wcout << "all items inside current directory was worked out. close it's handle." << std::endl; FindClose(search_handle); for(std::vector<std::wstring>::iterator iter = directories.begin(), end = directories.end(); iter != end; ++iter) { std::wcout << "recursively find in next directory: [" << *iter << "]" << std::endl; FindFile(*iter); } } else { std::wcout << "invalid handle value" << std::endl; } } int main() { //out.open("C:\\temp\\found.txt"); FindFile(L"C:\\test"); //out.close(); cout << "The end" << endl; string str; cin >> str; return 0; } but this code isn't working with folders or files with cyrillic names (but I use Unicode versions of all types and functions!) Update: Application just finish, without any exceptions, as if all commands was executed. Update-2 (print-screen): Who had the same problem? Thanks for any help. SOLVED Thanks a lot to @zett42 ! After some refactoring working code looks like: #include <iostream> #include <windows.h> #include <vector> #include <fstream> #include <io.h> #include <fcntl.h> using namespace std; vector<wstring> FindFiles(const std::wstring &directory) { vector<wstring> files; std::vector<std::wstring> directories; std::wstring fullPath = directory + L"\\*"; WIN32_FIND_DATAW file; HANDLE search_handle = FindFirstFileW(fullPath.c_str(), &file); if (search_handle == INVALID_HANDLE_VALUE) return files; do { fullPath = directory + L"\\" + std::wstring(file.cFileName); if (!(file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) files.push_back(fullPath); else { if ((lstrcmpW(file.cFileName, L".")) && (lstrcmpW(file.cFileName, L".."))) directories.push_back(fullPath); } } while (FindNextFileW(search_handle, &file)); FindClose(search_handle); for(std::vector<std::wstring>::iterator iter = directories.begin(), end = directories.end(); iter != end; ++iter) { vector<wstring> newFiles = FindFiles(*iter); files.insert(files.begin(), newFiles.begin(), newFiles.end()); } return files; } int main() { _setmode( _fileno(stdout), _O_U16TEXT ); vector<wstring> files = FindFiles(L"E:\\test"); wcout << L"All found files: " << endl; for (int i = 0; i < files.size(); ++i) wcout << files[i] << endl; cout << "The end" << endl; string str; cin >> str; return 0; } A: On Windows, Unicode output to console doesn't work by default, even if you use std::wcout. To make it work, insert the following line at the beginning of your program: _setmode( _fileno(stdout), _O_U16TEXT ); _setmode and _fileno are Microsoft specific function. You may also have to change console font. I'm using Lucida Console which works fine for cyrillic letters. Complete example: #include <iostream> #include <io.h> // _setmode() #include <fcntl.h> // _O_U16TEXT int main() { // Windows needs a little non-standard magic for Unicode console output. _setmode( _fileno(stdout), _O_U16TEXT ); std::wcout << L"по русски\n"; } Example should be saved as UTF-8 encoded file because of the Unicode string literal, but this is not relevant in your case because you don't have Unicode string literals. I have successfully tested this code under MSVC2015 and MSVC2017 on Win10.
{ "language": "en", "url": "https://stackoverflow.com/questions/43329565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use angular lazy loading without a routes file I am using angular lazy loading for my modules. For example I load the modules like this as recommended by AG8 const routes: Routes = [ {path: 'home', component: HomeComponent, data: {title: 'Home', animation: 'Home'}}, {path: 'services', loadChildren: () => import('./modules/services.module').then(module => module.ServicesModule), data: {title: 'Services', animation: 'Services'}}, // {path: '', redirectTo: 'home', pathMatch: 'full'}, {path: 'login', loadChildren: () => import('./modules/login.module').then(module => module.LoginModule), data: {title: 'Login', animation: 'Login'}}, {path: 'dashboard', loadChildren: () => import('./modules/dashboard.module').then(module => module.DashboardModule ), data: {title: 'Dashboard', animation: 'Dashboard'}, canActivate: [AppAuthGuard]}, {path: 'user/:userID/event/:eventID', loadChildren: () => import('./modules/event.module').then(module => module.EventModule ), data: {title: 'Event Details', animation: 'Event'}}, {path: 'user/:userID', loadChildren: () => import('./modules/user.module').then(module => module.UserModule), data: {title: 'Profile', animation: 'User'}}, {path: '**', redirectTo: 'home', pathMatch: 'full' }, ]; The for each of those modules I have their corresponding files eg: @NgModule({ imports: [ CommonModule, SomeRoutingModule ], declarations: [SomeComponent] }) export class SomeModule { } But for all those modules I have to create their corresponding router files eg: const routes: Routes = [ { path: '', component: SomeComponent } ]; Is there a way to just guide from the parent module the route to load the lazy module's declared component without having to create a router file? Something like: loadChildren: () => import('./modules/services.module').then(module => module.ServicesModule.SomeComponent)
{ "language": "en", "url": "https://stackoverflow.com/questions/58630933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery menu breaking on fast clicking/ scrolling over I have this jquery code below, but the problem is that if I scroll over and out of the trigger element quickly and through the menu, then it breaks, progressively showing less elements each time until nothing is shown. Can I add a timer or easing to stop this breaking? <ul class="buying-dropdown"> <li><p class="green-button"><a href="#">Read the blog</a></p> <ul> <li class="first amazon"><a href="#">paperback</a></li> <li class="signed"><a href="#">Signed edition</a></li> <li class="kindle"><a href="#">kindle edition</a></li> <li class="hardback"><a href="#">hardback edition</a></li> <li class="last postcard"><a href="#">postcard edition</a></li> </ul> </li> (function ($) { Drupal.behaviors.weaveoftheride = { attach: function(context, settings) { console.log('called'); $('.buying-dropdown li').hover( function () { //show its submenu $('ul', this).stop().slideDown(100); }, function () { //hide its submenu $('ul', this).stop().slideUp(100); } ); } }; })(jQuery); A: You should force jQuery to clear the animation queue and jump to the end of the animation when using the .stop() method, i.e. .stop(true, true).
{ "language": "en", "url": "https://stackoverflow.com/questions/15598718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python, simple calculation User types an integer number (smaller than 100, bigger than 0) If user types 0, the program ends. In case of numbers that are 100 or bigger, or that are -1 or smaller, it shows INVALID, and prompts user to keep entering number. a = int(input('Enter a number: ')) total =0 keep = True while keep: if a ==0: print('Thanks for playing.. goodbye') break; else: while a>99 or a <0: print('INVALID') a = int(input('Enter a number: ')) total = total + a print(total) a = int(input('Enter a number: ')) Just putting normal numbers and getting the sum, I enter 0, then it stops, but when I enter 100, INVALID shows up, then I enter 0, the program doesn't end and it keeps showing me INVALID. Any suggestions will be appreciated. Thanks! A: At your code, the else never breaks the loop so it only sums the total after it has exitted that 2nd loop, but that 2nd one doesn't have a behaviour for 0. You should try to keep it simple with just one loop. total =0 while True: a = int(input('Enter a number: ')) if a == 0: print('Thanks for playing.. goodbye') break else: if a > 99 or a < 0: # You don't need a second while, just an if. print('INVALID') else: total = total + a print(total) Identation is key at python, be careful with it. Also cleaned a bit your code. As example: Since you get into a loop with the while there is no need to use 2-3 different inputs in and out of the loop, just add it once at the beginning inside of the loop. A: I think this is a more pythonic approach total =0 while True: a = int(input('Enter a number: ')) if a == 0: break if a>99 or a <0: print('INVALID') else: total = total + a print(total) print('Thanks for playing.. goodbye') A: When using your code, the result is : Enter a number: 100 INVALID Enter a number: 0 0 Enter a number: 0 Thanks for playing.. goodbye And I think your code may should be: a = int(input('Enter a number: ')) total =0 keep = True while keep: if a ==0: print('Thanks for playing.. goodbye') break; else: while a>99 or a <0: print('INVALID') a = int(input('Enter a number: ')) if a ==0: print('Thanks for playing.. goodbye') break; total = total + a print(total) a = int(input('Enter a number: ')) You may procide your requirement more detail. A: You are in while loop of else conditional since you entered 100 at first and you can't get out of there unless you enter a number satisfies 0 <= a <= 99. You can make another if statement for a == 0 to exit the while loop just below a = int(input('Enter a number')) of else conditional. I think it is good to check where you are in while loop using just one print(a). For example, just before if-else conditional or just before while of else conditional. Then, you can check where it gets wrong. a = int(input('Enter a number: ')) total = 0 keep = True while keep: \\ print(a) here to make sure if you are passing here or not. if a == 0: print('Thanks for playing.. goodbye') break; else: \\ print(a) here to make sure if you are passing here or not. while a > 99 or a < 0: \\You are in while loop since you entered 100 at first and you can't get out from here unless you enter a: 0 <= a <= 99. print('INVALID') a = int(input('Enter a number: ')) if a == 0: print('Thanks for playing.. goodbye') break; total = total + a print(total) a = int(input('Enter a number: '))
{ "language": "en", "url": "https://stackoverflow.com/questions/46901509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zend Framework - Issue with delete from database code In my Application_Model_DbTable_User, I have the following function: public function deleteUser($username) { $this->delete('username = ' . (string) $username); } This function is being called from my AdminController, with this three lines of code. $uname = $this->getRequest()->getParam('username'); $user = new Application_Model_DbTable_User(); $user->deleteUser($uname); This error however, turns up. Column not found: 1054 Unknown column 'test' in 'where clause' With test being the user I am trying to delete. This code is adapted from a previous code which deletes based on id, a INT field, which works perfectly fine. What am I doing wrong? I would be happy to give more detailed codes if needed. Thanks. A: Your query isn't quoted: $this->delete('username = ' . (string) $username); This equates to: WHERE username = test If you use the where() method, it will do this for you: $table->where('username = ?', $username); Or (like the example in the docs): $where = $table->getAdapter()->quoteInto('bug_id = ?', 1235); $table->delete($where);
{ "language": "en", "url": "https://stackoverflow.com/questions/11631826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Winapi detect button hovering I've got a C++ project in which I'm using the Winapi to develop a window with a button and I want to change the text of the button when it's being hovered. For example, changing "Click me" to "Click me NOW!", when hovered. I've tried searching but I've not found any good ways to do this. I noticed that when user hovers, the WM_NOTIFY message is received, but I don't know how to ensure that it has been called by the mouse hover. I've found that I can use TrackMouseEvent to detect hovering, but it's limited to a period of time and I want to execute an action every time the user hovers the button. Here is how I create a button: HWND Button = CreateWindow("BUTTON", "Click me", WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY, 20, 240, 120, 20, hwnd, (HMENU)101, NULL, NULL); And this my window procedure: LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_NOTIFY: { //??? Here is where I get a message everytime I hover the button, But I don't know any proper way to see if it has been executed by the button. } case WM_CREATE: //On Window Create { //... } case WM_COMMAND: //Command execution { //... break; } case WM_DESTROY: //Form Destroyed { PostQuitMessage(0); break; } } return DefWindowProc(hwnd, msg, wParam, lParam); } A: Assuming you're using the common controls there is the BCN_HOTITEMCHANGE notification code for the WM_NOTIFY message. The message includes the NMBCHOTITEM structure, which includes information for whether the mouse is entering or leaving the hover area. Here's an example: LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_NOTIFY: { LPNMHDR header = *reinterpret_cast<LPNMHDR>(lParam); switch (header->code) { case BCN_HOTITEMCHANGE: { NMBCHOTITEM* hot_item = reinterpret_cast<NMBCHOTITEM*>(lParam); // Handle to the button HWND button_handle = header->hwndFrom; // ID of the button, if you're using resources UINT_PTR button_id = header->idFrom; // You can check if the mouse is entering or leaving the hover area bool entering = hot_item->dwFlags & HICF_ENTERING; return 0; } } return 0; } } return DefWindowProcW(hwnd, msg, wParam, lParam); } A: You can check the code of the WM_NOTIFY message to see if it is a NM_HOVER message. switch(msg) { case WM_NOTIFY: if(((LPNMHDR)lParam)->code == NM_HOVER) { // Process the hover message } else if (...) // any other WM_NOTIFY messages you care about {} } A: You can use simply SFML to do this. Code: RectangleShape button; button.setPosition(Vector2f(50, 50)); button.setSize(Vector2f(100, 40)); button.setFillColor(Color::Green); if(button.getGlobalBounds().contains(static_cast<Vector2f>(Mouse::getPosition(/*your window name*/window) { button.setFillColor(Color::Red); }
{ "language": "en", "url": "https://stackoverflow.com/questions/45018958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can angular be exposed as webservice API? I want to expose angular as web service, is that possible? In other words, can a backend calls angular, using typescript language? A: NO, it's not possible. Angular is a FRONT-END framework A: Strictly speaking, It is not recommended but I would say it is possible. Basically, everyone will say that it is just "FrontEnd" web framwork. But I see that it also can be a multi-platform framework for frontend and backend as well. The main Angular core team didn't define this framework as one "Frontend" framework. Rather, it says one framework across all platform. It means it can be transformed anything. They think bigger than non-angular developers. I see the bigger picture and future with Angular. Of course, this is just mainly used for the mobile and desktop for now. Many developers have a skeptical idea of this. I would agree. For example, Ionic/Nativescript. They adopted Angular as a core framework. Yes, this is for mobile(Frontend right?). However, What about Nest.js. Cool right? This is totally server-side web framework for "Backend". The fact is that this framework heavily referenced "Angular framework" such as Angular-like Dependency Injection system. They even mentioned "The architecture is heavily inspired by Angular." Let's say you are a pioneer and you can make it possible. I highly recommend to play with the Angular platform source codebase. Git clone and modify something and build it(it takes some time but it should work at your local computer). If you see the github codebase, this is huge and actually have capability or "potential" to serve as a backend. Of course, it depends on a situation. So ask yourself What kind of your expectation from it and what the purpose is. Angular is just javascript(transpiled by Typscript) program. After having transpiled javascript static files, it requires a http server to serve the files. Luckily, Angular Frmaework has its own local server( called ng serve yes we know this one which is a cute http/https server. Thus, technically speaking, Angular is "Framework" not library. Framework includes many tools and even app servers in it. I would say that it's possible and it can even directly communicate with other Angular applications with websocket and webRTC as well. Don't make me wrong. Once again, It is only possible with the embedded Angular Serve module(ng serve) if you don't want to install other 3rd party http server. These days, What a Javascript/Typescript world. Javascript/Typescript can do everything. Angular is a part of it and it is the most advanced web framework among others. Check out the following github codes. Hope you like my answer. Take care. angular-cli/packages/angular_devkit/core/node/ architect-command.ts angular devkit dev-server Anything is possible
{ "language": "en", "url": "https://stackoverflow.com/questions/62623829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacting XML node text using PowerShell I am having my XML document as follows <Batch> <Alter> <ObjectDefinition> <DataSources> <DataSource> <ConnectionString>Provider=SQLNCLI11.1;Data Source=ABC;Integrated Security=SSPI;Initial Catalog =TesDB1</ConnectionString> <ConnectionString>Provider=SQLNCLI11.1;Data Source=XYZ;Integrated Security=SSPI;Initial Catalog =TesDB1</ConnectionString> </DataSource> </DataSources> </ObjectDefinition> </Alter> </Batch> I would like to replace the entire connection-string nodes as follows $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database" Here is what I tried but this is replacing only one node content $XMLA = "D:\employee.xml" $SqlDataBase = [xml](Get-Content $XMLA) $data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString") #$data $DataSource = "localhost" foreach($xn in $data) { $DataBase = $xn.'#text'.Split(";").Split("=") $DataBase[$DataBase.Length - 1] $DataBase = $DataBase[$DataBase.Length - 1] $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database" $SqlDataBase.SelectSingleNode("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString").InnerText = "$ConnectionString"; } $SqlDataBase.Save($XMLA) So any better way to replace multiple nodes please let me know A: This is best way where I have taken the source from here Selecet XML Nodes by similar names in Powershell $XMLA = "D:\employee.xml" $SqlDataBase = [xml](Get-Content $XMLA) $data = $SqlDataBase.SelectNodes("Batch/Alter/ObjectDefinition/DataSources/DataSource/ConnectionString") #$data $DataSource = "localhost" $SqlDataBase.Batch.Alter.ObjectDefinition.DataSources.DataSource.ChildNodes | Where-Object Name -Match 'ConnectionString' | ForEach-Object { $DataBase = $_.'#text'.Split(";").Split("=") $DataBase = $DataBase[$DataBase.Length - 1] $ConnectionString = "Provider=SQLNCLI11.1;Data Source=$DataSource;Integrated Security=SSPI;Initial Catalog =$Database" $_.'#text' = "$ConnectionString" } $SqlDataBase.Save($XMLA)
{ "language": "en", "url": "https://stackoverflow.com/questions/39888180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access VBA Return 0 in grouping even if there is no match I have employees table in access db with days on which they have worked on: Table A employee_id | date_wrk | Project | Worked ----------------------------------------- 1 10 |01.01.2015|Project1 | 1 2 10 |12.01.2015|Project1 | 0,5 3 10 |01.02.2015|Project1 | 1 4 10 |01.02.2015|Project2 | 1 5 10 |04.02.2015|Project2 | 1 6 12 |05.02.2015|Project2 | 1 What i need is Final table with sum of days done by month by projects: employee_id | Month | Project | Worked ----------------------------------------- 10 |January | Project 1 | 1,5 10 |February | Project 1 | 1 10 |February | Project 2 | 2 10 |March | Project 1 | 0 I group by month(date) with sum of days worked - The problem is I want to display all months jan-dec - the month and 0 if employee doesn't have any day worked in given month for given project.. I tried to build months table with all months listed and right join it but it doesnt help.. Any ideas would be appriciated. Cheers! ..... A: I try to avoid right join because it's needlessly confusing. Here's an example left join approach: select e.employee_id , m.month , a.project , sum(a.worked) from ( select distinct employee_id from TableA ) e , MonthsTable m left join TableA a on a.employee_id = m.employee_id and month(a.date_wrk) = m.month group by e.employee_id , m.month , a.project The cross join creates a matrix of each employee and each month. For each employee-month combination in the matrix, it optionally looks up the project hours. A: Ok I did it basing on Andomar suggestion - but as Access is not fond of sub-queries and cross join I created additional table based on : select distinct employee_id,months.month from TableA,months which give me a cross join table which then I linked to tableA. Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/32179020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AWS CodePipeline: source action has insufficient permissions for CodeStar connection I'm setting up a CodePipeline, and I created an action to fetch the source from GitHub. This requires to set up a connection, which I did, and things look fine also on GitHub's side. However, if I release a change to the pipeline, I see the following error at the source stage: Insufficient permissions Unable to use Connection: arn:aws:codestar-connections:us-east-1:REDACTED:connection/REDACTED. The provided role does not have sufficient permissions. I added full CodeStar access to the pipeline's service role (which I found in the pipeline settings) and looks like this: arn:aws:iam::REDACTED:role/service-role/AWSCodePipelineServiceRole-us-east-1-REDACTED Does anybody have any idea of what might be missing? Thanks! A: The solution was to add this bit to the policy of the service role: { "Effect": "Allow", "Action": "codestar-connections:UseConnection", "Resource": "insert ARN of the CodeStar connection here" }
{ "language": "en", "url": "https://stackoverflow.com/questions/64298865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How to parse cell format data from a .xlsx file using xlrd I am relatively new to python and I am trying to read information from an excel sheet to generate a graph. So far I am using the most current version of the xlrd library (0.9.4) in a nested for loop to grab the value from each cell. However, I am unsure how to access the formatting information for each cell For example, if a cell were formatted to display as currency in the excel file, using the standard sheet.cell(row, column).value from xlrd would only return 5.0 instead of $5.00 I found here that you can set the formatting_info parameter to true when opening the workbook in order to see some of the format information, however I am primarily using excel 2013 and my excel sheets are being saved by default as .xlsx files. According to this issue on GitHub, support for formatting_info has not yet been implemented for .xlsx files. Is there any way around using the formatting_info flag, or any other way that I can detect when a format, currency specifically, has been used in order to reflect that in my graphs? I am aware that it is possible to convert .xlsx files to .xls files such as shown here, but I am concerned about information/formatting loss.
{ "language": "en", "url": "https://stackoverflow.com/questions/34801157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to bulk insert data in Djnago without providing fields to model How to bulk insert data with only providing dictionary key and not worry about manually providing fields and type of fields in models.py What I have to do right now: models.py from django.db import models # Create your models here. class Info(models.Model): name = models.CharField(max_length=70) email = models.CharField(max_length=70) Outout: name | email Jon | [email protected] mongodb collection what I want without using fields and assigning more than 20-30 fields: name | email | fname | lname | cellNum | add | age | height | etc... for example using mongoClient to bulk insert data without providing fields data = {x:x, y:y, z:z} collection.insert_one(data) collection.insert_many([data,...])
{ "language": "en", "url": "https://stackoverflow.com/questions/71504037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: gcm canonical id should be updated or not I am working on an android project which uses gcm. I came to know that if we uninstall the appfrom device and reinstalled most of the time the device gets new registration id.Then if we do not delete the old one from application server and update, The messages will be sending to both ids and in the response it will be showing canonical id is present.My question is, at this point message will be successfully send to that device or not? A: When you receive a canonical registration ID in the response from Google, the message was accepted by the GCM server and the GCM server would attempt to deliver it to the device. Whether it is actually sent to the device depends on whether the device is available (i.e. connected to the internet). So if your server sends a GCM message to both the old ID and the new ID, the device will probably get two messages. Canonical IDs On the server side, as long as the application is behaving well, everything should work normally. However, if a bug in the application triggers multiple registrations for the same device, it can be hard to reconcile state and you might end up with duplicate messages. GCM provides a facility called "canonical registration IDs" to easily recover from these situations. A canonical registration ID is defined to be the ID of the last registration requested by your application. This is the ID that the server should use when sending messages to the device. If later on you try to send a message using a different registration ID, GCM will process the request as usual, but it will include the canonical registration ID in the registration_id field of the response. Make sure to replace the registration ID stored in your server with this canonical ID, as eventually the ID you're using will stop working. (Source) You can overcome this problem by assigning a unique identifier to each instance of your application. If you store that identifier in the device's external storage, it won't be deleted when the app is uninstalled. Then you can recover it when the app is installed again. If you send this identifier to your server along with the registration ID, you can check if your server has an old registration ID for this identifier, and delete it. A: @Eran We have two option either to remove older registration ids or update with Key and position of canonical id. I prefer to update... You can view working code of mine i have answered here Steps to Update Canonical Ids
{ "language": "en", "url": "https://stackoverflow.com/questions/23710404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: I am making a paint application using kotlin. I wanted to erase my last path using an undo button. How can I do that? I was trying to make a paint app through which users can paint and draw for fun. I wanted to erase a drawing partially by using the undo button in my app. The floating action button I have used erases the whole drawing, but I want only that last part of the drawing to get erased. Kindly help me how can I do that ? XML FILE <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" tools:context=".MainActivity"> <LinearLayout android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent" android:background="@drawable/toolbar_background" android:gravity="center" app:layout_constraintRight_toRightOf="parent"> <ImageButton android:id="@+id/redColor" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:background="@drawable/red_background"/> <ImageButton android:id="@+id/blueColor" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:background="@drawable/blue_background"/> <ImageButton android:id="@+id/blackColor" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:background="@drawable/black_background"/> <ImageButton android:id="@+id/whiteColor" android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="10dp" android:background="@drawable/white_background"/> </LinearLayout> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@id/toolbar" app:layout_constraintRight_toRightOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintBottom_toBottomOf="parent"> <include android:id="@+id/include" layout="@layout/paint_view" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/resetButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:text="RESET" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.954" app:layout_constraintStart_toStartOf="parent" android:src="@drawable/ic_baseline_delete_24"/> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout> MainActivity.kt package com.example.dapple import android.graphics.Color import android.graphics.Paint import android.graphics.Path import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.dapple.PaintView.Companion.colorList import com.example.dapple.PaintView.Companion.currentBrush import com.example.dapple.PaintView.Companion.pathList import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { companion object{ var path = Path() var paintBrush = Paint() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportActionBar?.hide() redColor.setOnClickListener{ paintBrush.color = Color.RED currentColor(paintBrush.color) } blueColor.setOnClickListener{ paintBrush.color = Color.BLUE currentColor(paintBrush.color) } blackColor.setOnClickListener{ paintBrush.color = Color.BLACK currentColor(paintBrush.color) } whiteColor.setOnClickListener{ paintBrush.color = Color.WHITE currentColor(paintBrush.color) } resetButton.setOnClickListener{ pathList.clear() colorList.clear() path.reset() } } private fun currentColor(color: Int){ currentBrush = color path = Path() } } PaintView.kt package com.example.dapple import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintSet import com.example.dapple.MainActivity.Companion.paintBrush import com.example.dapple.MainActivity.Companion.path class PaintView : View { var params:ViewGroup.LayoutParams? = null companion object{ var pathList = ArrayList<Path>() var colorList = ArrayList<Int>() var currentBrush = Color.WHITE } constructor(context: Context) : this(context, null){ init() } constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) { init() } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init() } private fun init(){ paintBrush.isAntiAlias = true paintBrush.color = currentBrush paintBrush.style = Paint.Style.STROKE paintBrush.strokeJoin = Paint.Join.ROUND paintBrush.strokeWidth = 8f params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } override fun onTouchEvent(event: MotionEvent): Boolean { var x = event.x var y = event.y when(event.action){ MotionEvent.ACTION_DOWN->{ path.moveTo(x,y) return true } MotionEvent.ACTION_MOVE->{ path.lineTo(x,y) pathList.add(path) colorList.add(currentBrush) } else -> return false } postInvalidate() return false } override fun onDraw(canvas: Canvas) { for(i in pathList.indices){ paintBrush.setColor(colorList[i]) canvas.drawPath(pathList[i],paintBrush) invalidate() } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/70325024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pythonic Way To Warn Developers For Broken Code Is there a pythonic way to throw an exception to other developers to warn them about using a piece of code with bugs in it? For example: def times_two(x): raise BrokenException("Attn.This code is unreliable. Only works on positive numbers") x = abs(x) * 2 return x I understand that I can raise a generic exception with a message, or even derive my own exception classes, but i just want to know if there is a built-in, pythonic way to do something like this. And also, I understand that why the actual times_two function doesn't work. That was just an example function. This is not something to validate input parameters, or even returned values. This is simply to mark a function as potentially unreliable. The code must be used in some areas under very specific circumstances, but when devs are writing code and run across this function should be warned of the limitations. A: Your example is pretty flawed for any use case in which alerting the developers would be needed. This would need to alert the user not to input a negative number. def times_two(x): if x < 0: raise BrokenException("Attn user. Don't give me negitive numbers.") return x * 2 Although, I think if your example more accurately described an actual error needing developer attention then you should just fix that and not put it into production knowing there is an error in it. sentry.io on the other hand can help find errors and help developers fix errors while in production. You may want to look into that if warnings isn't for you. From their README.me: Sentry fundamentally is a service that helps you monitor and fix crashes in realtime. The server is in Python, but it contains a full API for sending events from any language, in any application. A: Builtin Exception 'ValueError' is the one that should be used. def times_two(x): if x < 0: raise ValueError('{} is not a positive number.'.format(x)) return x * 2 A: This seems like an XY problem. The original problem is that you have some code which is incomplete or otherwise known to not work. If it is something you are currently working on, then the correct tool to use here is your version control. With Git, you would create a new branch which only be merged into master and prepared for release to production after you have completed the work. You shouldn't release a partial implementation. A: Do you want to stop execution when the function is called? If so, then some sort of exception, like the BrokenException in your example is a good way of doing this. But if you want to warn the caller, and then continue on anyway, then you want a Warning instead of an exception. You can still create your own: class BrokenCodeWarning(Warning) pass When you raise BrokenCodeWarning, execution will not be halted by default, but a warning will be printed to stderr. The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception). https://docs.python.org/3.7/library/warnings.html#the-warnings-filter
{ "language": "en", "url": "https://stackoverflow.com/questions/54754982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NHibernate - counters with concurrency and second-level-caching I'm new to NHibernate and am having difficulties setting it up for my current website. This website will run on multiple webservers with one database server, and this leaves me facing some concurrency issues. The website will have an estimated 50.000 users or so registered, and each user will have a profile page. On this page, other users can 'like' another user, much like Facebook. This is were the concurrency problem kicks in. I was thinking of using second-level cache, most likely using the MemChached provider since I'll have multiple webservers. What is the best way to implement such a 'Like' feature using NHibernate? I was thinking of three options: * *Use a simple Count() query. There will be a table 'User_Likes' where each row would represent a like from one user to another. To display the number the number of likes, I would simply ask the number of Likes for a user, which would be translated to the database as a simple SELECT COUNT(*) FROM USER_LIKES WHERE ID = x or something. However, I gather this would be come with a great performance penalty as everytime a user would visit a profile page and like another user, the number of likes would have to be recalculated, second-level cache or not. *Use an additional NumberOfLikes column in the User table and increment / decrement this value when a user likes or dislikes another user. This however gives me concurrency issues. Using a simple for-loop, I tested it by liking a user 1000 times on two servers and the result in the db was around 1100 likes total. That's a difference of 900. Whether a realistic test or not, this is of course not an option. Now, I looked at optimistic and pessimistic locking as a solution (is it?) but my current Repository pattern is, at the moment, not suited to use this I'm afraid, so before I fix that, I'd like to know if this is the right way to go. *Like 2, but using custom HQL and write the update statement myself, something along the lines of UPDATE User SET NumberOfLikes = NumberOfLikes + 1 WHERE id = x. This won't give me any concurrency issues in the database right? However, I'm not sure if I'll have any datamismatch on my multiple servers due to the second level caching. So... I really need some advice here. Is there another option? This feels like a common situation and surely NHibernate must support this in an elegant manner. I'm new to NHIbernate so a clear, detailed reply is both necessary and appreciated :-) Thanks! A: I suspect you will see this issue in more locations. You could solve this specific issue with 3., but that leaves other locations where you're going to encounter concurrency issues. What I would advise is to implement pessimistic locking. The usual way to do this is to just apply a transaction to the entire HTTP request. With the BeginRequest in your Global.asax, you start a session and transaction. Then, in the EndRequest you commit it. With the Error event, you go the alternative path of doing a rollback and discarding the session. This is quite an accepted manner of applying NHibernate. See for example http://dotnetslackers.com/articles/aspnet/Configuring-NHibernate-with-ASP-NET.aspx. A: I'd go with 3. I believe this in this kind of application it's not so critical if some pages show a slightly outdated value for a while. IIRC, HQL updates do not invalidate the entity cache entry, so you might have to do it manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/4246051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: delete specific rows from a flat file How to delete specific rows from a flat file on the basis of first 4 characters of a row? For example; delete the rows starting with '1000'. (After deleting these rows, the file will remain there with other rows that start with '2000', '3000', and so on. Or, how to write the rows starting with '1000', '2000', and '3000' into different flat files? (Each row has varying number of columns and columns have different width).
{ "language": "en", "url": "https://stackoverflow.com/questions/30043171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting top 100 records from database via NHibernate using linq Is there a way to delete top 1000 records from database via NHibernate using ling , something similar like Take(100) when u are fetching data?
{ "language": "en", "url": "https://stackoverflow.com/questions/64800541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access VBA Checkbox error 2447 Ok, I'm getting the error 2447 when trying to create a new record in my database. Here is the code that is have. 'This checks the record each time a record is changed to see if it needs to display the text boxes Private Sub Form_Current() If Me.SigCheck = 1 then <--This is where I'm getting the error. SigSerialtxt.Visible = True SigSeriallbl.Visible = True SigAssettxt.Visible = True SigAssetlbl.Visible = True Else SigSerialtxt.Visible = False SigSeriallbl.Visible = False SigAssettxt.Visible = False SigAssetlbl.Visible = False End if End Sub I've tried to change the variable to True, as well as -1, but neither of the work. I'm lost as to what to use. A: fixed the issue, I set the default to 0, now there is no error and it works properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/19054138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get reference to commits in git Lets have a git master branch and at some moment lets fork branch for release (release branch will be called R1). Sometimes I need to push commit to both of them(master and R1). Usually I work on master branch, when I'm done I test it, cherry-pick to R1, test it there and push to both of them. I would like to have in R1 commit reference to master branch. This is done by cherry-pick -x. However, this approach works ONLY when I push to master branch and then cherry-pick from master to R1. Let say that testing take too much time and I want to have master and R1 in sync as much as I can ( I want to minimize time gap between pushes), so I would like to push simultaneously. In this way I can not get reference (-x in cherry-pick), because hash will change while doing rebase in R1 (can not use merge). Is there any way how to automatize this, so I will have correct hash in R1 description? Something like hash predicting? A: Is there any way how to automatize this, so I will have correct hash in R1 description? Something like hash predicting? The short answer is no. The longer answer is still no, but you might not need to predict the hash. The issue here is that you are copying some fix commit—let's call this F—from master to another branch. Let's call this -x cherry-picked copy commit Fx. You may also end up copying the fix commit to a new fix commit because you are avoiding using git merge in this work-flow, so if master has acquired new commits, you use rebase to cherry-pick F into a new commit F' that you will add to master, and now you want to replace your Fx—your cherry-picked copy of F—with a cherry-picked copy of F'. So, you can just do that. If you rebase commit F to make F', strip Fx from the other branch and re-run git cherry-pick -x to copy F' to Fx'. You already know which commits these are, because you have the original hash ID of F and cherry-picking it (via rebase) produces F'; and you have F's hash ID in Fx. The drawback is that this re-copies any commits after Fx on the other branch, since "strip Fx from the other branch" can be nontrivial. (An alterative approach, one that avoids all this fussing-about, is to merge the fix into both branches. See How to do a partial merge in git? and the linked blog articles.)
{ "language": "en", "url": "https://stackoverflow.com/questions/52622631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C implicit conversion? Can someone explain to me how printf("%d", -2<2u?1:-1); prints out '-1'. I assume there is some kind of implicit conversion going on but I can't seem to grasp it. A: -2 is getting converted to unsigned integer. This will be equal to UINT_MAX - 1, which is definitely greater than 2. Hence, the condition fails and -1 is printed.
{ "language": "en", "url": "https://stackoverflow.com/questions/35362286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Simple loop on windows7 creates memory leak? I am unsure about this, but this question might be related to Memory leak in batch for loop?. I have the following trivial batch script: @echo off :label cmd.exe /c cls echo hello goto label When this script runs on a Windows7 32-bit installation, it behaves well. But when I run it on the few Windows7 64-bit machines that I have access to, it slowly and apparently irrevocably eats up all system memory - as seen in the Windows task manager. The memory stays in use after closing the window that executes the above batch lines. Is this happening to other people? If not, do you know what could cause this? Other installed software on the system? I have the same behavior if I do a while True: os.system('cls') loop in a Python-X/Y shell. It seems to be linked to the creation of a sub process. If I change the above from cmd.exe /c cls to just cls, I do not get a memory leak. I ran into this problem because I ported a Python script from Linux that repeatedly does a clear screen for a statistics display, implemented for Windows as shown in Clear the screen in python. A: I ran it on my x64 machine and it works ok, it does start to struggle as time goes but I wouldn't call it a memory leak, if anything it just hammers the CPU when it spikes. It could just be struggling to keep up with the commands depending on the performance of the computer. I added in a timeout for a second, now cmd is much happier and showing less than 1MB RAM consumption. Try just adjusting this to your needs, or find middle ground where you get the speed and the performance, just give cmd a break :) @echo off :label cmd.exe /c cls echo hello timeout /t 1 >nul goto label
{ "language": "en", "url": "https://stackoverflow.com/questions/11302232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coping text from textarea to div in jQuery I'd like to copy text from textarea to div using this code but there are line breaks missing. $("#some-div").text($("#some-textarea").val().replace('/\n/g', '<br />')); What's going wrong? Thanks A: The text function will set text, not HTML. You need replace the newlines in the generated HTML: $("#some-div").text($("#some-textarea").val()) .html(function(index, old) { return old.replace(/\n/g, '<br />') }); Note that you cannot set the HTML directly from the textarea, because that won't escape HTML tags. Also, unlike PHP, Javascript uses regex literals, so you cannot put a regex in a string. A: Rather than treating HTML as a string, I would suggest creating DOM nodes. Normalize the textarea value (IE uses \r\n rather than \n), split the textarea value on line breaks and create text nodes separated by <br> elements: var div = $("#some-div")[0]; var lines = $("#some-textarea").val().replace(/\r\n/g, "\n").split("\n"); for (var i = 0, len = lines.length; i < len; ++i) { if (i) div.appendChild(document.createElement("br")); div.appendChild(document.createTextNode(lines[i])); }
{ "language": "en", "url": "https://stackoverflow.com/questions/4969782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CRC16 modbus calculation returns wrong value for long data packets I'm connecting to a device through a serial port. The device appends a CRC16 tag to the end of the data packet in big-endian mode. In software side, the code to check CRC is something like this: bool Protocol::checkCRC(const QByteArray &buf) { if(buf.size()<3){ return false; } int len = buf.size()-2; // Exclude CRC token quint16 crc = 0xFFFF; quint16 claim = static_cast<uchar>(buf.at(buf.size()-1)); claim*=0x100; claim+=static_cast<uchar>(buf.at(buf.size()-2)); for (int pos = 0; pos < len; pos++) { crc ^= (quint16)buf[pos]; // XOR byte into LSB of crc for (int i = 8; i != 0; i--) { // Loop over each bit if ((crc & 0x0001) != 0) { // If the LSB is set crc >>= 1; // Shift right and XOR 0xA001 crc ^= 0xA001; } else // Else LSB is not set crc >>= 1; // Just shift right } } return crc==claim; } I copied the code from this question. It works fine for small packets. For example following data packet is passed in CRC16 check using this function: 0x04, 0x10, 0x00, 0x3d, 0xc1 Reported CRC is 0xC13D and function calculates 0xC13D as well. But for big data packets (in my case 53 bytes) the function fails to calculate correct CRC: 0x34, 0x02, 0x02, 0x08, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0a, 0xdf, 0x07, 0x0a, 0x39, 0x1b, 0x02, 0x02, 0x79, 0x61, 0xbf, 0x34, 0xdd, 0x0b, 0x83, 0x0f, 0x10, 0x03, 0x1b, 0x11, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x98 Reported CRC is 0x98FC but calculated value is 0xDFC4. A: I don't know what the QByteArray type is, but I'll wager that it is an array of signed characters. As a result, when the high bit of a byte is a one, that sign bit is extended when converted to an integer which all gets exclusive-or'ed into your CRC at crc ^= (quint16)buf[pos];. So when you got to the 0xdf, crc was exclusive-or'ed with 0xffdf instead of the intended 0xdf. So the issue is not the length, but rather the likelihood of having a byte with the high bit set. You need to provide unsigned bytes, or fix the conversion, or do an & 0xff to the resulting byte before exclusive-or'ing with the CRC.
{ "language": "en", "url": "https://stackoverflow.com/questions/36918735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Echart vs 5: I cannot get Sliders in three containers combined to work as one I have succeeded in making three charts (containers) above each other in ECHARTS v5 and all works fine. However, I need all three sliders to work as one. Meaning that if I change one slider the other two must do exactly the same so the x-Axis data remains the same to make comparison easier. Is this possible and if yes how? <Remark: Has been answered by 'A mere dev' and the solution is in the code below >. Now need to add an additional candle chart in myChart1 part to show Heikin Ashi candles with on off toggle just like the lines in myChart1. < made a new question if this: Link to this question> <!DOCTYPE html> <html style="height: 100%"> <head> <meta charset="utf-8"> </head> <body style="height: 100%; margin: 0"> <div id="container1" style="height: 34%"></div> <div id="container2" style="height: 33%"></div> <div id="container3" style="height: 33%"></div> <script type="text/javascript" src="echarts.min_All.js"></script> <script type="text/javascript"> //=========================================================================================================== var dom1 = document.getElementById("container1"); var myChart1 = echarts.init(dom1); var app = {}; var option1; const upColor = '#00da3c'; const upBorderColor = '#008F28'; const downColor = '#ec0000'; const downBorderColor = '#8A0000'; // Each item: open,close,lowest,highest const data0 = splitData([ ['2013/1/24', 2320.26, 2320.26, 2287.3, 2362.94], ['2013/1/25', 2300, 2291.3, 2288.26, 2308.38], ['2013/1/28', 2295.35, 2346.5, 2295.35, 2346.92], ['2013/1/29', 2347.22, 2358.98, 2337.35, 2363.8], ['2013/1/30', 2360.75, 2382.48, 2347.89, 2383.76], ['2013/1/31', 2383.43, 2385.42, 2371.23, 2391.82], ['2013/2/1', 2377.41, 2419.02, 2369.57, 2421.15], ['2013/2/4', 2425.92, 2428.15, 2417.58, 2440.38], ['2013/2/5', 2411, 2433.13, 2403.3, 2437.42], ['2013/2/6', 2432.68, 2434.48, 2427.7, 2441.73], ['2013/2/7', 2430.69, 2418.53, 2394.22, 2433.89], ['2013/2/8', 2416.62, 2432.4, 2414.4, 2443.03], ['2013/2/18', 2441.91, 2421.56, 2415.43, 2444.8], ['2013/2/19', 2420.26, 2382.91, 2373.53, 2427.07], ['2013/2/20', 2383.49, 2397.18, 2370.61, 2397.94], ['2013/2/21', 2378.82, 2325.95, 2309.17, 2378.82], ['2013/2/22', 2322.94, 2314.16, 2308.76, 2330.88], ['2013/2/25', 2320.62, 2325.82, 2315.01, 2338.78], ['2013/2/26', 2313.74, 2293.34, 2289.89, 2340.71], ['2013/2/27', 2297.77, 2313.22, 2292.03, 2324.63], ['2013/2/28', 2322.32, 2365.59, 2308.92, 2366.16], ['2013/3/1', 2364.54, 2359.51, 2330.86, 2369.65], ['2013/3/4', 2332.08, 2273.4, 2259.25, 2333.54], ['2013/3/5', 2274.81, 2326.31, 2270.1, 2328.14], ['2013/3/6', 2333.61, 2347.18, 2321.6, 2351.44], ['2013/3/7', 2340.44, 2324.29, 2304.27, 2352.02], ['2013/3/8', 2326.42, 2318.61, 2314.59, 2333.67], ['2013/3/11', 2314.68, 2310.59, 2296.58, 2320.96], ['2013/3/12', 2309.16, 2286.6, 2264.83, 2333.29], ['2013/3/13', 2282.17, 2263.97, 2253.25, 2286.33], ['2013/3/14', 2255.77, 2270.28, 2253.31, 2276.22], ['2013/3/15', 2269.31, 2278.4, 2250, 2312.08], ['2013/3/18', 2267.29, 2240.02, 2239.21, 2276.05], ['2013/3/19', 2244.26, 2257.43, 2232.02, 2261.31], ['2013/3/20', 2257.74, 2317.37, 2257.42, 2317.86], ['2013/3/21', 2318.21, 2324.24, 2311.6, 2330.81], ['2013/3/22', 2321.4, 2328.28, 2314.97, 2332], ['2013/3/25', 2334.74, 2326.72, 2319.91, 2344.89], ['2013/3/26', 2318.58, 2297.67, 2281.12, 2319.99], ['2013/3/27', 2299.38, 2301.26, 2289, 2323.48], ['2013/3/28', 2273.55, 2236.3, 2232.91, 2273.55], ['2013/3/29', 2238.49, 2236.62, 2228.81, 2246.87], ['2013/4/1', 2229.46, 2234.4, 2227.31, 2243.95], ['2013/4/2', 2234.9, 2227.74, 2220.44, 2253.42], ['2013/4/3', 2232.69, 2225.29, 2217.25, 2241.34], ['2013/4/8', 2196.24, 2211.59, 2180.67, 2212.59], ['2013/4/9', 2215.47, 2225.77, 2215.47, 2234.73], ['2013/4/10', 2224.93, 2226.13, 2212.56, 2233.04], ['2013/4/11', 2236.98, 2219.55, 2217.26, 2242.48], ['2013/4/12', 2218.09, 2206.78, 2204.44, 2226.26], ['2013/4/15', 2199.91, 2181.94, 2177.39, 2204.99], ['2013/4/16', 2169.63, 2194.85, 2165.78, 2196.43], ['2013/4/17', 2195.03, 2193.8, 2178.47, 2197.51], ['2013/4/18', 2181.82, 2197.6, 2175.44, 2206.03], ['2013/4/19', 2201.12, 2244.64, 2200.58, 2250.11], ['2013/4/22', 2236.4, 2242.17, 2232.26, 2245.12], ['2013/4/23', 2242.62, 2184.54, 2182.81, 2242.62], ['2013/4/24', 2187.35, 2218.32, 2184.11, 2226.12], ['2013/4/25', 2213.19, 2199.31, 2191.85, 2224.63], ['2013/4/26', 2203.89, 2177.91, 2173.86, 2210.58], ['2013/5/2', 2170.78, 2174.12, 2161.14, 2179.65], ['2013/5/3', 2179.05, 2205.5, 2179.05, 2222.81], ['2013/5/6', 2212.5, 2231.17, 2212.5, 2236.07], ['2013/5/7', 2227.86, 2235.57, 2219.44, 2240.26], ['2013/5/8', 2242.39, 2246.3, 2235.42, 2255.21], ['2013/5/9', 2246.96, 2232.97, 2221.38, 2247.86], ['2013/5/10', 2228.82, 2246.83, 2225.81, 2247.67], ['2013/5/13', 2247.68, 2241.92, 2231.36, 2250.85], ['2013/5/14', 2238.9, 2217.01, 2205.87, 2239.93], ['2013/5/15', 2217.09, 2224.8, 2213.58, 2225.19], ['2013/5/16', 2221.34, 2251.81, 2210.77, 2252.87], ['2013/5/17', 2249.81, 2282.87, 2248.41, 2288.09], ['2013/5/20', 2286.33, 2299.99, 2281.9, 2309.39], ['2013/5/21', 2297.11, 2305.11, 2290.12, 2305.3], ['2013/5/22', 2303.75, 2302.4, 2292.43, 2314.18], ['2013/5/23', 2293.81, 2275.67, 2274.1, 2304.95], ['2013/5/24', 2281.45, 2288.53, 2270.25, 2292.59], ['2013/5/27', 2286.66, 2293.08, 2283.94, 2301.7], ['2013/5/28', 2293.4, 2321.32, 2281.47, 2322.1], ['2013/5/29', 2323.54, 2324.02, 2321.17, 2334.33], ['2013/5/30', 2316.25, 2317.75, 2310.49, 2325.72], ['2013/5/31', 2320.74, 2300.59, 2299.37, 2325.53], ['2013/6/3', 2300.21, 2299.25, 2294.11, 2313.43], ['2013/6/4', 2297.1, 2272.42, 2264.76, 2297.1], ['2013/6/5', 2270.71, 2270.93, 2260.87, 2276.86], ['2013/6/6', 2264.43, 2242.11, 2240.07, 2266.69], ['2013/6/7', 2242.26, 2210.9, 2205.07, 2250.63], ['2013/6/13', 2190.1, 2148.35, 2126.22, 2190.1], ]); //----------------------------------------------------- const data1 = splitData([ ['2013/1/24', 2320.26, 2320.26, 2287.3, 2362.94], ['2013/1/25', 2300, 2291.3, 2288.26, 2308.38], ['2013/1/28', 2295.35, 2346.5, 2295.35, 2346.92], ['2013/1/29', 2347.22, 2358.98, 2337.35, 2363.8], ['2013/1/30', 2360.75, 2382.48, 2347.89, 2383.76], ['2013/1/31', 2383.43, 2385.42, 2371.23, 2391.82], ['2013/2/1', 2377.41, 2419.02, 2369.57, 2421.15], ['2013/2/4', 2425.92, 2428.15, 2417.58, 2440.38], ['2013/2/5', 2411, 2433.13, 2403.3, 2437.42], ['2013/2/6', 2432.68, 2434.48, 2427.7, 2441.73], ['2013/2/7', 2430.69, 2418.53, 2394.22, 2433.89], ['2013/2/8', 2416.62, 2432.4, 2414.4, 2443.03], ['2013/2/18', 2441.91, 2421.56, 2415.43, 2444.8], ['2013/2/19', 2420.26, 2382.91, 2373.53, 2427.07], ['2013/2/20', 2383.49, 2397.18, 2370.61, 2397.94], ['2013/2/21', 2378.82, 2325.95, 2309.17, 2378.82], ['2013/2/22', 2322.94, 2314.16, 2308.76, 2330.88], ['2013/2/25', 2320.62, 2325.82, 2315.01, 2338.78], ['2013/2/26', 2313.74, 2293.34, 2289.89, 2340.71], ['2013/2/27', 2297.77, 2313.22, 2292.03, 2324.63], ['2013/2/28', 2322.32, 2365.59, 2308.92, 2366.16], ['2013/3/1', 2364.54, 2359.51, 2330.86, 2369.65], ['2013/3/4', 2332.08, 2273.4, 2259.25, 2333.54], ['2013/3/5', 2274.81, 2326.31, 2270.1, 2328.14], ['2013/3/6', 2333.61, 2347.18, 2321.6, 2351.44], ['2013/3/7', 2340.44, 2324.29, 2304.27, 2352.02], ['2013/3/8', 2326.42, 2318.61, 2314.59, 2333.67], ['2013/3/11', 2314.68, 2310.59, 2296.58, 2320.96], ['2013/3/12', 2309.16, 2286.6, 2264.83, 2333.29], ['2013/3/13', 2282.17, 2263.97, 2253.25, 2286.33], ['2013/3/14', 2255.77, 2270.28, 2253.31, 2276.22], ['2013/3/15', 2269.31, 2278.4, 2250, 2312.08], ['2013/3/18', 2267.29, 2240.02, 2239.21, 2276.05], ['2013/3/19', 2244.26, 2257.43, 2232.02, 2261.31], ['2013/3/20', 2257.74, 2317.37, 2257.42, 2317.86], ['2013/3/21', 2318.21, 2324.24, 2311.6, 2330.81], ['2013/3/22', 2321.4, 2328.28, 2314.97, 2332], ['2013/3/25', 2334.74, 2326.72, 2319.91, 2344.89], ['2013/3/26', 2318.58, 2297.67, 2281.12, 2319.99], ['2013/3/27', 2299.38, 2301.26, 2289, 2323.48], ['2013/3/28', 2273.55, 2236.3, 2232.91, 2273.55], ['2013/3/29', 2238.49, 2236.62, 2228.81, 2246.87], ['2013/4/1', 2229.46, 2234.4, 2227.31, 2243.95], ['2013/4/2', 2234.9, 2227.74, 2220.44, 2253.42], ['2013/4/3', 2232.69, 2225.29, 2217.25, 2241.34], ['2013/4/8', 2196.24, 2211.59, 2180.67, 2212.59], ['2013/4/9', 2215.47, 2225.77, 2215.47, 2234.73], ['2013/4/10', 2224.93, 2226.13, 2212.56, 2233.04], ['2013/4/11', 2236.98, 2219.55, 2217.26, 2242.48], ['2013/4/12', 2218.09, 2206.78, 2204.44, 2226.26], ['2013/4/15', 2199.91, 2181.94, 2177.39, 2204.99], ['2013/4/16', 2169.63, 2194.85, 2165.78, 2196.43], ['2013/4/17', 2195.03, 2193.8, 2178.47, 2197.51], ['2013/4/18', 2181.82, 2197.6, 2175.44, 2206.03], ['2013/4/19', 2201.12, 2244.64, 2200.58, 2250.11], ['2013/4/22', 2236.4, 2242.17, 2232.26, 2245.12], ['2013/4/23', 2242.62, 2184.54, 2182.81, 2242.62], ['2013/4/24', 2187.35, 2218.32, 2184.11, 2226.12], ['2013/4/25', 2213.19, 2199.31, 2191.85, 2224.63], ['2013/4/26', 2203.89, 2177.91, 2173.86, 2210.58], ['2013/5/2', 2170.78, 2174.12, 2161.14, 2179.65], ['2013/5/3', 2179.05, 2205.5, 2179.05, 2222.81], ['2013/5/6', 2212.5, 2231.17, 2212.5, 2236.07], ['2013/5/7', 2227.86, 2235.57, 2219.44, 2240.26], ['2013/5/8', 2242.39, 2246.3, 2235.42, 2255.21], ['2013/5/9', 2246.96, 2232.97, 2221.38, 2247.86], ['2013/5/10', 2228.82, 2246.83, 2225.81, 2247.67], ['2013/5/13', 2247.68, 2241.92, 2231.36, 2250.85], ['2013/5/14', 2238.9, 2217.01, 2205.87, 2239.93], ['2013/5/15', 2217.09, 2224.8, 2213.58, 2225.19], ['2013/5/16', 2221.34, 2251.81, 2210.77, 2252.87], ['2013/5/17', 2249.81, 2282.87, 2248.41, 2288.09], ['2013/5/20', 2286.33, 2299.99, 2281.9, 2309.39], ['2013/5/21', 2297.11, 2305.11, 2290.12, 2305.3], ['2013/5/22', 2303.75, 2302.4, 2292.43, 2314.18], ['2013/5/23', 2293.81, 2275.67, 2274.1, 2304.95], ['2013/5/24', 2281.45, 2288.53, 2270.25, 2292.59], ['2013/5/27', 2286.66, 2293.08, 2283.94, 2301.7], ['2013/5/28', 2293.4, 2321.32, 2281.47, 2322.1], ['2013/5/29', 2323.54, 2324.02, 2321.17, 2334.33], ['2013/5/30', 2316.25, 2317.75, 2310.49, 2325.72], ['2013/5/31', 2320.74, 2300.59, 2299.37, 2325.53], ['2013/6/3', 2300.21, 2299.25, 2294.11, 2313.43], ['2013/6/4', 2297.1, 2272.42, 2264.76, 2297.1], ['2013/6/5', 2270.71, 2270.93, 2260.87, 2276.86], ['2013/6/6', 2264.43, 2242.11, 2240.07, 2266.69], ['2013/6/7', 2242.26, 2210.9, 2205.07, 2250.63], ['2013/6/13', 2190.1, 2148.35, 2126.22, 2190.1], ]); //----------------------------------------------------- function splitData(rawData) { const categoryData = []; const values = []; for (var i = 0; i < rawData.length; i++) { categoryData.push(rawData[i].splice(0, 1)[0]); values.push(rawData[i]); } return { categoryData: categoryData, values: values }; } function calculateMA(dayCount) { var result = []; for (var i = 0, len = data0.values.length; i < len; i++) { if (i < dayCount) { result.push('-'); continue; } var sum = 0; for (var j = 0; j < dayCount; j++) { sum += +data0.values[i - j][1]; } result.push(sum / dayCount); } return result; } option1 = { title: { text: 'Candlesticks and Lines', left: 0 }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } }, legend: { data: ['Candles', 'HACandles', 'MA5', 'MA10', 'MA20', 'Indicatorline_1', 'Indicatorline_2'] }, grid: { left: '3%', right: '5%', bottom: '17%' }, toolbox: { right: '3%', feature: { restore: { show: true }, saveAsImage: {} } }, xAxis: { type: 'category', data: data0.categoryData, boundaryGap: false, axisLine: { onZero: false }, splitLine: { show: false }, min: 'dataMin', max: 'dataMax' }, yAxis: { scale: true, splitArea: { show: true } }, dataZoom: [ { type: 'inside', start: 50, end: 100, }, { show: true, type: 'slider', top: '8%', start: 50, end: 100, height: 20, handleSize: '100%' } ], series: [ { name: 'Candles', type: 'candlestick', data: data0.values, itemStyle: { color: upColor, color0: downColor, borderColor: upBorderColor, borderColor0: downBorderColor }, //------------------------------------------- name: 'HACandles', type: 'candlestick', data: data1.values, itemStyle: { color: upColor, color0: downColor, borderColor: upBorderColor, borderColor0: downBorderColor }, //---------------------------------------- markPoint: { label: { formatter: function (param) { return param != null ? Math.round(param.value) + '' : ''; } }, data: [ { name: 'Mark1', coord: ['2013/5/31', 2230], value: 12, itemStyle: { color: 'rgb(0,204,102)' } }, { name: 'Mark2', coord: ['2013/6/4', 2250], value: 12, itemStyle: { color: 'rgb(41,60,85)' } }, ], tooltip: { formatter: function (param) { return param.name + '<br>' + (param.data.coord || ''); } } }, //---------------------------------------------------- markLine: { symbol: ['none', 'none'], data: [ //------------------------------------- [ { name: 'Position_01', type: 'min', coord: ['2013/5/31', 2230], symbol: 'circle', symbolSize: 10, itemStyle: { color: 'rgb(0,204,102)' }, label: { show: false }, emphasis: { label: { show: false } } }, { type: 'max', coord: ['2013/6/4', 2250], symbol: 'circle', symbolSize: 10, label: { show: false }, emphasis: { label: { show: false } }, }, ], //------------------------------------- [ { name: 'Position_02', //from lowest to highest type: 'min', coord: ['2013/5/6', 2230], symbol: 'circle', symbolSize: 10, itemStyle: { color: 'rgb(255,0,0)' }, label: { show: true }, emphasis: { label: { show: true } } }, { type: 'max', coord: ['2013/5/14', 2200], symbol: 'circle', symbolSize: 10, label: { show: true }, emphasis: { label: { show: true } }, }, ], //-------------------------------------- ] } }, // Lines { name: 'MA5', type: 'line', data: calculateMA(5), smooth: true, lineStyle: { opacity: 0.5 } }, { name: 'MA10', type: 'line', data: calculateMA(10), smooth: true, lineStyle: { opacity: 0.5 } }, { name: 'MA20', type: 'line', data: calculateMA(20), smooth: true, lineStyle: { opacity: 0.5 } }, { name: 'Indicatorline_1', type: 'line', itemStyle: { color: 'rgb(255,0,0)' }, data: [2190.1, 2148.35, 2126.22, 2190.1, 2242.26, 2210.9, 2205.07, 2250.63, 2264.43, 2242.11, 2240.07, 2266.69,2190.1, 2148.35], smooth: true, lineStyle: { opacity: 0.5 } }, { name: 'Indicatorline_2', type: 'line', itemStyle: { color: 'rgb(0,128,255)' }, data: [2320.26, 2300.92, 2347.224,2360.75, 2383.43, 2377.41, 2425.92,2320.26, 2300.92, 2347.224, 2360.75, 2383.43, 2377.41, 2425.92], smooth: true, lineStyle: { opacity: 0.5 } } ] }; if (option1 && typeof option1 === 'object') { myChart1.setOption(option1); } //=========================================================================================================== var dom2 = document.getElementById("container2"); var myChart2 = echarts.init(dom2); var app = {}; var option2; option2 = { title: { text: 'Lines Graph', left: 0 }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross', crossStyle: { color: '#999' } } }, legend: { data: ['Line_1', 'Line_2', 'Line_3', 'Line_4', 'Line_5'] }, grid: { left: '1%', right: '5%', bottom: '15%', containLabel: true }, toolbox: { right: '3%', feature: { restore: { show: true }, saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: data0.categoryData, }, yAxis: { type: 'value', }, //------ dataZoom: [ { type: 'inside', start: 50, end: 100 }, { show: true, type: 'slider', top: '8%', start: 50, end: 100, height: 20, handleSize: '100%' } ], //------ series: [ { name: 'Line_1', type: 'line', data: [ 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210 , 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210 , 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210 , 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 210 , 120, 132, 101, 134 ] }, { name: 'Line_2', type: 'line', data: [ 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310 , 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310 , 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310 , 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310, 220, 182, 191, 234, 290, 330, 310 ] }, { name: 'Line_3', type: 'line', data: [ 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410 , 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410 , 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410 , 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410, 150, 232, 201, 154, 190, 330, 410 , 150, 232, 201, 154 ] }, { name: 'Line_4', type: 'line', data: [ 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320 , 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320 , 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320 , 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320, 320, 332, 301, 334, 390, 330, 320 , 320, 332, 301, 334 ] }, { name: 'Line_5', type: 'line', data: [ 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320 , 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320 , 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320 , 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290, 1330, 1320 , 820, 932, 901, 934 ] }, ] }; option2 && myChart2.setOption(option2); //=========================================================================================================== var dom3 = document.getElementById("container3"); var myChart3 = echarts.init(dom3); var app = {}; var option3; option3 = { title: { text: 'Volume Bar Graph', left: 0 }, tooltip: { trigger: 'axis', axisPointer: { type: 'cross', crossStyle: { color: '#999' } } }, grid: { left: '1%', right: '5%', bottom: '15%', containLabel: true }, toolbox: { right: '3%', feature: { dataView: { show: false, readOnly: false }, magicType: { show: true, type: ['line', 'bar'] }, restore: { show: true }, saveAsImage: { show: true } } }, legend: { data: ['Sell Volume', 'Buy Volume', 'Total Volume'] }, xAxis: [ { type: 'category', data: data0.categoryData, axisPointer: { type: 'shadow' } } ], yAxis: [ { type: 'value', name: 'Volume', axisLabel: { formatter: '{value} vol' } } ], //------ dataZoom: [ { type: 'inside', start: 50, end: 100 }, { show: true, type: 'slider', top: '8%', start: 50, end: 100, height: 20, handleSize: '100%' } ], //------ series: [ { name: 'Sell Volume', type: 'bar', data: [ 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3, 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3, 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3 , 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3, 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3, 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3 , 2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3, 2.0, 4.9, 7.0, 23.2,, 25.6 ] }, { name: 'Buy Volume', type: 'bar', data: [ 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3, 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3, 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3 , 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3, 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3, 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3 , 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3, 2.6, 5.9, 9.0, 26.4, 28.7 ] }, { name: 'Total Volume', type: 'line', data: [ 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6, 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6, 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6 , 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6, 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6, 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6 , 4.6, 10.8, 16.0, 49.6, 54.3, 147.4, 311.2, 344.4, 81.3, 38.8, 12.4, 5.6, 4.6, 10.8, 16.0, 49.6, 54.3 ] } ] }; option3 && myChart3.setOption(option3); //=========================================================================================================== echarts.connect([myChart1, myChart2, myChart3]); </script> </body> </html> A: Use echarts.connect to connect your charts as follow : echarts.connect([myChart1, myChart2, myChart3]) For this to work on your example, you'll have to remove the ids from the 3 'slider' type dataZoom. dataZoom: [ { type: 'inside', start: 50, end: 100 }, { show: true, //id: 'S3', type: 'slider', top: '8%', start: 50, end: 100, height: 20, handleSize: '100%' } ],
{ "language": "en", "url": "https://stackoverflow.com/questions/71664510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: on session end event I have a Symfony2 project, where at the beginning of each session, I create a folder on the server where the user can manipulate and place his files. I want to be able to delete the user's folder, when he closes his browser (or any other related event, maybe check for a session timeout?). How can I achieve this? PS: I have read somewhere that java has a sessionHandler where you can code your function. Is there anything similar in php (Symfony2 specifically)? A: First of all, you cannot recongnize if a browser is closed by HTML and PHP. You would need ajax and constant polling or some kind of thing to know the browser is still there. Possible, but a bt complicated, mainly because you might run into troubles if a browser is still there (session is valid) but has no internet connection for a few minutes (laptop, crappy wlan, whatever). You cannot have a sessionHandler which does this for you in PHP because PHP is executed when a script is retrieved from your server. After the last line is executed, it stops. If no one ever retrieves the script again, how should it do something? There is no magic that restarts the script to check if the session is still there. So, what to do? First of all you want to make the session visible by using database session storage or something like that. Then you need a cronjob starting a script, looking up all sessions and deciding which one is invalid by now and then does something with it (like deleting the folder). Symfony can help as it allows you to configure session management in a way that it stores sessions in the database (see here) as well as creating a task which can be executed via crontab (see here). The logical part, which contains deciding which session is invalid and what to do with this sessions) is your part. But it shouldn't be very hard as you got the session time and value in the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/9533800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Find the name of the employees with a particular letter I'm having the schemas like: Employee (Empno, Empname, City) Project (Pno, Pname) Part (Partno, Partname, Color) Use (Pno, Partno) Works (Empno, Pno) From these schemas I had created a sample tables: The goal is to find the names of the projects where no employees are working whose name starts with 'S' I'm using ORACLE 11g Express Edition. Here I used this query : For Names: Select DISTINCT Pname FROM ( SELECT w.Empno, p.Pno, p.Pname, e.Empname FROM Works w LEFT JOIN Project p ON w.Pno=p.Pno LEFT JOIN Employee e ON e.Empno=w.Empno ) WHERE Empname not like 'S%'; A: If you think about how to explain the process. There are several methods to solve this including: * *You would start with each of the Projects and find out if there does not exist anybody who Works on the project where the Employees name starts with S. You can do this using NOT EXISTS. or *Again, start with a Project and find, if any, who Works on the project and their corresponding Employees details using LEFT OUTER JOINs (but starting from the Project) and filtering for employee names starting with S in the JOIN condition. Then GROUP BY the primary key for the project and find those projects HAVING a COUNT of zero matched employees. Since this appears to be a homework question, I'll leave the rest for you to complete.
{ "language": "en", "url": "https://stackoverflow.com/questions/71025814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Appinvite_styles.xml:5: error When including Google Play Services library to eclipse I need to add an ad to my application. So I need to include Google Play Services library to my project. I have installed lastest version of Google Play Services (r29) and added to my projects as libProject. But when I add this service lib I'm getting error below: workspace\Google_Play_Services_Lib\res\values-v21\appinvite_styles.xml:5: error: Error retrieving parent for item: No resource found that matches the given name '@android:style/Theme.Material.Light.DialogWhenLarge.NoActionBar'. How can I solve this problem ? Thanks for help.. A: just changed Project SDK to 20 (from 21) and all compiled. A: I have solved the problem by checking the Is Library option and I referenced appcompat_v7 A: I was also facing same problem, but now it's been resolved. Below are the steps I followed - Go to project properties->Android - Under 'Project Build Target', select Android 5.0.1. Press and clean the library project.
{ "language": "en", "url": "https://stackoverflow.com/questions/34371867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: A global nextjs middleware without need for import in all the routes TLDR; a middleware to nextjs like express where I only define it once and it'll automatically applies to all of my routes I want a middleware style like we have in express I'll define a middleware inside the server.js(entry file) and the middleware will apply to all the routes without any other work needed. well I need similar thing to NextJs these what I've been tried and used for a while 1: Using High Order Component (HOC): I don't like this approach because of these drawbacks * *Using HOC will disable fast-refresh functionality which's is really nice future to have More Info Here *I have to import my middleware in every api route file which is really not fun to do and wrapping your api files in a function is not a thing to remember all the time 2: using next-connect I don't like to use this package due to these drawbacks * *The nextjs ways to handle api routes seem more natural since i use nextjs i want to still use the nextjs way to handle my routes. not totally different style just for sake of a middleware *same as the HOC I don't like to import nc and my-middleware in every api file well why not just using a custom server like express? the thing is when i use nextjs I want to only use nextjs also using a custom server will lose so many cool future of nextjs which's is partially why I use nextjs A: You can implement _app.tsx, which will run for all pages, though it has some drawbacks too like disabling automatic static generation. Another option is to implement a custom server using express itself, as shown in this example
{ "language": "en", "url": "https://stackoverflow.com/questions/68666416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling LUIS speech recognition service I'm trying to build simple app using LUIS service. I use project oxford version 1.0.0.6 SpeechRecognitionServiceFactory.CreateDataClientWithIntent to create a data client, but confused with it's interface. My understanding is that LUIS accepts only text queries, but above client only has method SendAudio which accepts only byte array (works perfectly with CRIS when sending audio files). So, should this method be used to for text query as well or is there some other way to make this call? A: I think that you are missing things. One thing is to call CRIS (and watch out I think that you are using an outdated SDK, take a look at the new one and also to the docs), and another thing is to call LUIS, which is another SDK (this one). Once you get the output of CRIS, you can just call the LUIS SDK to send the query text.
{ "language": "en", "url": "https://stackoverflow.com/questions/44771410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: force input element's width to size to its content/value I'm trying to unstyle an input element so that its text looks like plain/inline-text, and I've reset pretty much every css property it can have, but I can't get the input's width to adjust/shrink to its content (input { width:auto; min-width:0; } does not work). It obeys an arbitrary width like input { width: 10px; }, so obviously its width is adjustable. I see people trying to do it with javascript (the fiddle from the answer doesn't work anymore), so I'm wondering if what I want is even possible. Here's a fiddle. A: Played with this. Couldn't do it. What are you trying to achieve? Are you aware of the contenteditable attribute? This might get you what you need. https://developer.mozilla.org/en-US/docs/HTML/Content_Editable A: What if you just avoid the whole style snafu and do a little text shuffling? You already have everything you need with jQuery. http://jsfiddle.net/2fQgY/8/ The date is <span class="dateSpoof"></span><input class="myDate" type="hidden" value="foo" />. Thanks for coming. $('.myDate').datepicker({ showOn: 'button', buttonText: 'select...', onClose: function () { var dateText = $(this).val(); $('.dateSpoof').html(dateText); $('.ui-datepicker-trigger').hide(); }, dateFormat: 'd M yy' }); Here's an example that's resettable: http://jsfiddle.net/2fQgY/11 And here's one that's all text and nothing but text: http://jsfiddle.net/2fQgY/14
{ "language": "en", "url": "https://stackoverflow.com/questions/14904219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: RegEx expression not alerting properly in JS Okay, so when the user enters his/her full name in the field, I want a greeting to say, "Nice to meet you, (split name). I want to take the value of the input, take the innerHTML, split it, then take the first part ([0]), and alert it! Ignore the if/else stuff :P HTML <form onsubmit="return formValidate(this);"> <label>Full name</label><br> <input type="text" id="name"/> </form> JS function formValidate(form){ // set initial status var status = true; var name = document.getElementById("name"), full_name = name.innerHTML, full_name_split = full_name.split(" ")[0]; if(name.value == "") { document.getElementById("name-alert").innerHTML = alerts[0]; status = false; } else if(namePatt.test(name.value) == false){ document.getElementById("name-alert").innerHTML = alerts[1]; status = false; } else if(name.value.indexOf(charSpace) == 0 || name.value.indexOf(charSpace) == -1){ document.getElementById("name-alert").innerHTML = alerts[2]; status = false; } alert(full_name_split); // return the initial status return status; } A: input elements do not have .innerHTML. Use .value instead: var name = document.getElementById("name"), full_name = name.value, full_name_split = full_name.split(" ")[0];
{ "language": "en", "url": "https://stackoverflow.com/questions/17564090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: phpStorm remote debug goes to server_ip/index page all the time, what is wrong? I am trying to setup remote debug in a remote project under phpStorm 10.0.2 and I can't. Any time I set a breakpoints and hit Shift+F9 or Alt+Shift+F9 browser opens this URL: http://remote_host_ip/index.php and I don't know why. xDebug is installed and enabled, see the pic below for further info: Debugger config seems to be fine, see the pic below: What I am missing here? The issue was "fixed" with @lazyone suggestion. Now I didn't get redirect to http://remote_host_ip/index.php but I am running in a second issue since breakpoints aren't respected. In the pic below I show my setup for index.php debug: As soon as I start debug I can step into or step over but in none I get redirected to web page where I enter for example login and password. I am still missing something here just don't know what, any advice? Note: Yes I know you will ask for all the configs I had made but are a bunch, so ask for them and I will edit the post to add them.
{ "language": "en", "url": "https://stackoverflow.com/questions/34440457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android : getting only the last item in the listview multiple times i am trying to get the items in the listview using json from server, for this i have made my custom adapter. but if there are 6 items on the server it displays the last item 6 times in the list view and i have given a checkbox infront of every item in the list to get the id of the checked item. here is my code: btnclub.setOnClickListener(new OnClickListener() { ArrayList<Integer> checkedList = new ArrayList<Integer>(); @Override public void onClick(View v) { // TODO Auto-generated method stub Dialog d = new Dialog(TennerTextActivity.this); d.setContentView(R.layout.slctevnt); ListView list = (ListView) d.findViewById(R.id.list_mulitple); HashMap<String, String> list_map = new HashMap<String, String>(); // Initialize CATEGORY_LIST HERE try { client = new DefaultHttpClient(); HttpGet get = new HttpGet( "http://dhklashfgsdhgsdg"); HttpResponse rp = client.execute(get); String result = EntityUtils.toString(rp.getEntity()); System.out.println("----------------------- result: " + result); result = "{\"root\": " + result + "}"; JSONObject root = new JSONObject(result); JSONArray sessions = root.getJSONArray("root"); for (int i = 0; i < sessions.length(); i++) { HashMap<String, String> map2 = new HashMap<String, String>(); JSONObject e = sessions.getJSONObject(i); list_map.put("category_name", e.getString("name")); list_map.put("category_id", e.getString("id")); list_category.add(list_map); } } catch (Exception e) { e.printStackTrace(); } list.setAdapter(new MyAdapter()); d.show(); Button btndone = (Button) d.findViewById(R.id.button_multiple); btndone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub for(int i = 0 ; i < checkedList.size() ; i++) { clubs = "," + String.valueOf(checkedList.get(i)); } clubs = clubs.substring(1); System.out.print(clubs); Log.e("club", clubs); } }); and my adapter is: class MyAdapter extends BaseAdapter { @Override public int getCount() { // TODO Auto-generated method stub return list_category.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.dialoglist, null); TextView item = (TextView) convertView .findViewById(R.id.dialogitem); item.setText(list_category.get(position).get( "category_name")); } CheckBox check = (CheckBox)convertView.findViewById(R.id.checkBox_list); check.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(isChecked) { int temp = Integer.parseInt(list_category.get(position).get("category_id")); checkedList.add(temp); Object[] tempArray = checkedList.toArray(); Arrays.sort(tempArray); checkedList.clear(); for(int i = 0 ; i < tempArray.length ; i++) { checkedList.add((Integer) tempArray[i]); } } } }); return convertView; } } please tell where i am doing wrong ... A: i think you have to change for loop like this for (int i = 0; i < sessions.length(); i++) { HashMap<String, String> map2 = new HashMap<String, String>(); HashMap<String, String> list_map = new HashMap<String, String>(); JSONObject e = sessions.getJSONObject(i); list_map.put("category_name", e.getString("name")); list_map.put("category_id", e.getString("id")); list_category.add(list_map); } A: problem is in below line list_map.put("category_name", e.getString("name")); list_map.put("category_id", e.getString("id")); list_category.add(list_map); you are putting category_name and id into list_map and adding same into list_category. here you are adding list_map instance in list_category. and becuse of the key for map(which is category_name and id ) is same, it can store only one value corresponding to one key, hence it is storing last inserting value of these keys. when you are updating list_map with new data the instance itself getting change), That is why it is showing 6 times of last list_map data. Solution : what you can do here, initialize list_map in loop only with new keyword, so it will insert new instance every-time you insert into list_category. or you can use two d array. instead of hashmap. HashMap<String, String> list_map = new HashMap<String, String>(); P.S: I pointed out one problem in your code, which is causing duplicacy of data, there can be other problem also as suggested by other SO members. Edit: replace your below code for(int i = 0 ; i < checkedList.size() ; i++) { clubs = "," + String.valueOf(checkedList.get(i)); } clubs = clubs.substring(1); with something like below StringBuilder sb = new StringBuilder(); for(int i = 0 ; i < checkedList.size() ; i++) { sb.add(String.valueOf(checkedList.get(i))+","); } sb.deleteCharAt(sb.lastIndexOf(",")); A: change getView methode like this if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.dialoglist,null); } TextView item = (TextView) convertView.findViewById(R.id.dialogitem); item.setText(list_category.get(position).get("category_name"));
{ "language": "en", "url": "https://stackoverflow.com/questions/11516364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multiplying modified colums to form new column I want a query like: select tp.package_rate, sum(sell) as sold_quantity , select(tp.package_rate * sold_quantity ) as sell_amount from tbl_ticket_package tp where tp.event_id=1001 here the system firing error while doing the multiplication as sold_quantity is invalid column another problem is that in multiplication I want to use package_rate which got by select query from tp.package_rate but it multiplying with all package_rate of the table but I want only specific package_rate which was output of select query What would you suggest? I want to bind this query in gridview . is there any way to do it using ASP.net gridview? A: Your problem is that you are referring to sold_quantity here : select(tp.package_rate * sold_quantity ) The alias is not recognized at this point.You will have to replace it with sum(sales). You will also have to group by tp.package_rate. Your query should ideally be like : select tp.package_rate, sum(sell) as sold_quantity , (tp.package_rate * sum(sell) ) as sell_amount from tbl_ticket_package tp where tp.event_id=1001 group by tp.package_rate; I am guessing that tp.package_rate is unique for a given event_id, from latter part of your question. If that's not the case, the sql you have written makes no sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/36944253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Text-decoration: none not working Totally baffled! I've tried rewriting the text-decoration: none line several different ways. I also managed to re-size the text by targeting it but the text-decoration: none code will not take. Help much appreciated. Code .widget { height: 320px; width: 220px; background-color: #e6e6e6; position: relative; overflow: hidden; } .title { font-family: Georgia, Times New Roman, serif; font-size: 12px; color: #E6E6E6; text-align: center; letter-spacing: 1px; text-transform: uppercase; background-color: #4D4D4D; position: absolute; top: 0; padding: 5px; width: 100%; margin-bottom: 1px; height: 28px; text-decoration: none; } a .title { text-decoration: none; } <a href="#"> <div class="widget"> <div class="title">Underlined. Why?</div> </div> </a> A: Add this statement on your header tag: <style> a:link{ text-decoration: none!important; cursor: pointer; } </style> A: a:link{ text-decoration: none!important; } => Working with me :) , good luck A: You have a block element (div) inside an inline element (a). This works in HTML 5, but not HTML 4. Thus also only browsers that actually support HTML 5. When browsers encounter invalid markup, they will try to fix it, but different browsers will do that in different ways, so the result varies. Some browsers will move the block element outside the inline element, some will ignore it. A: Try placing your text-decoration: none; on your a:hover css. A: if you want a nav bar do ul{ list-style-type: none; } li{text-decoration: none; * *This will make it want to make the style of the list type to None or nothing with the < a > tag: a:link {text-decoration: none} A: I have an answer: <a href="#"> <div class="widget"> <div class="title" style="text-decoration: none;">Underlined. Why?</div> </div> </a>​ It works. A: Add a specific class for all the links : html : <a class="class1 class2 noDecoration"> text </a> in css : .noDecoration { text-decoration: none; } A: Use CSS Pseudo-classes and give your tag a class, for example: <a class="noDecoration" href="#"> and add this to your stylesheet: .noDecoration, a:link, a:visited { text-decoration: none; } A: There are no underline even I deleted 'text-decoration: none;' from your code. But I had a similar experience. Then I added a Code a{ text-decoration: none; } and a:hover{ text-decoration: none; } So, try your code with :hover. A: As a sidenote, have in mind that in other cases a codebase might use a border-bottom css attribute, for example border-bottom: 1px;, that creates an effect very similar to the text-decoration: underline. In that case make sure that you set it to none, border-bottom: none; A: I had lots of headache when I tried to customize a WordPress theme and the text-decoration didn't help me. In my case I had to remove the box-shadow as well. a:hover { text-decoration: none; box-shadow: none; } A: An old question and still no explanation. The underline is drawn not on your <div class="title"> element but on its parent a, since all browsers set this style for links by default. If you provide custom decoration style for the inner div - it will be visible instead of the parent style. But if you set none (and it is already set on divs by default), your div will not be decorated, but its parent decoration will become visible instead. So, as people suggested, in this case to remove all the decoration text-decoration: none; should be set on the parent a element.
{ "language": "en", "url": "https://stackoverflow.com/questions/11419998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: How to fix CA Dispose objects before losing scope? CA throw the following message: CA2000 Dispose objects before losing scope. In method 'GetMatchingJobsDeferred(BackgroundJobSearchParameters)', object '<>g__initLocal0' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '<>g__initLocal0' before all references to it are out of scope. I have disposable type CompositeCollection. public sealed class CompositeCollection<T> : IEnumerable<T>, IDisposable { private readonly List<IEnumerable<T>> _enumerables = new List<IEnumerable<T>>(); private readonly List<IDisposable> _disposables = new List<IDisposable>(); public void Add(IEnumerable<T> enumerable) { _enumerables.Add(enumerable); } public void Add(IDeferredResultCollection<T> deferredResultCollection) { _enumerables.Add(deferredResultCollection); _disposables.Add(deferredResultCollection); } public IEnumerator<T> GetEnumerator() { return _enumerables.Aggregate((results, enumerable) => results.Concat(enumerable)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { foreach (var item in _disposables) { item.Dispose(); } } } And that how I used it: public IDeferredResultCollection<BackgroundJobInfoLight> GetMatchingJobsDeferred(BackgroundJobSearchParameters jobSearchParameters) { var memoryLocatedJobs = GetInMemoryJobs(jobSearchParameters); var databaseLocatedJobs = GetInDatabaseJobsDeferred(jobSearchParameters, memoryLocatedJobs); return new CompositeCollection<BackgroundJobInfoLight> { memoryLocatedJobs, databaseLocatedJobs }; } I have exception when return statement called. How to fix that? I add try catch and it doesn't help public IDeferredResultCollection<BackgroundJobInfoLight> GetMatchingJobsDeferred(BackgroundJobSearchParameters jobSearchParameters) { CompositeCollection<BackgroundJobInfoLight> deferredJobs = null; DeferredResultCollection<BackgroundJobInfoLight> databaseLocatedJobs = null; try { var memoryLocatedJobs = GetInMemoryJobs(jobSearchParameters); databaseLocatedJobs = GetInDatabaseJobsDeferred(jobSearchParameters, memoryLocatedJobs); deferredJobs = new CompositeCollection<BackgroundJobInfoLight> { memoryLocatedJobs, databaseLocatedJobs }; return deferredJobs; } catch { if (databaseLocatedJobs != null) { databaseLocatedJobs.Dispose(); } if (deferredJobs != null) { deferredJobs.Dispose(); } throw; } } A: When returning the disposable objects, it should be the responsibility of the caller code to Dispose the object. Had the Disposed been called inside the method itself, the disposed object will return to the caller method, (wont be of any use). In that case it is safe to supress the warning. BUT what if the exception occurred in this method? If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. MSDN So, if you anticipate any exception in the method, you should have this code in try...catch block and in catch block you should call Dispose() checking if the object is not null. And when you are not returning IDisposable you can use using statement or try...finally and call dispose in finally A: Why are you keeping items in to different list variables? It may have something to do with your issue. Keep it DRY Store them in one list and safely cast to what you are looking for. IDisposable myDispType = myEnumarableType as IDisposable; If (myDispType != null) {//your logic here}
{ "language": "en", "url": "https://stackoverflow.com/questions/33892783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: can't get web page source from url in Swift I'm currently using SwiftHTTP for getting source of url address. I am using 'get method' for getting source code of url address which is do { let opt = try HTTP.GET(self.my_url_address!) opt.start { response in if let err = response.error { print("error: \(err.localizedDescription)") return } print(response.description) } } catch let error { print("got an error creating the request: \(error)") } after this code run I got this output in Xcode output screen URL: http://myweburl.com/detay/swat-under-siege.html Status Code: 200 Headers: Content-Type: text/html Connection: keep-alive CF-RAY: 38391215a60e2726-FRA Set-Cookie: ASPSESSIONIDSABBBSDT=HPKKPJGCDLKMDMILNGHPCAGD; path=/ Date: Mon, 24 Jul 2017 18:51:24 GMT Vary: Accept-Encoding X-Powered-By: ASP.NET Transfer-Encoding: Identity Server: cloudflare-nginx Content-Encoding: gzip Cache-Control: private The status code is 200 but the output is not the source code of url. How can I fix this? A: Response is correct. I've tried requesting the website (the real one) and it works: print(response.data.base64EncodedString()) If you decode the BASE64 data, it will render valid HTML code. The issue seems related to encoding. After checking the website's head tag, it states that the charset is windows-1254 String(data: response.data, encoding: .windowsCP1254) // works. latin1, etc. Your issue is similar to SWIFT: NSURLSession convert data to String
{ "language": "en", "url": "https://stackoverflow.com/questions/45288316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set control (windows control) position to some other control relative postion I want to set control position relative to other control so when i make one control hide then other control move up like this. Ex. Label1 Label2 Label3 When i hide Label2 so output will be Label1 Label3 A: You can use FlowLayoutPanel Though, you might need to set the FlowDirection to TopDown Just put those labels into the panel
{ "language": "en", "url": "https://stackoverflow.com/questions/5429528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keeping variable names when exporting Pyomo into a .mps file So, i'm currently working with a pyomo model with multiple instances that are being solved in parallel. Issue is, solving them takes pyomo quite a long time (like 2 to 3 secs, even though the solving part by gurobi takes about 0.08s). I've found out that, by exporting a pyomo instance into an .mps file and then giving it to gurobipy i can get like an increase of 30% in overall speed. The problem comes later, when i want to work with the variables of the solved model, because ive noticed that, when exporting the original instance from pyomo into a .mps file, variable names get lost; they all get named "x" (so, for example, model.Delta, model.Pg, model.Alpha, etc get turned into x1, x2, ... ,x9999 instead of Delta[0], Delta[1], ... Alpha[99,99]). Is there a way to keep the original variable name when exporting the model? A: Managed to solve it! To anyone who might find this useful, i passed a dictionary with "symbolic_solver_labels" as an io_options argument for the method, like this: instance.write(filename = str(es_) + ".mps", io_options = {"symbolic_solver_labels":True}) Now my variables are correctly labeled in the .mps file!
{ "language": "en", "url": "https://stackoverflow.com/questions/64342685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Operator overloading From language design point of view , What type of practice is supporting operator overloading? What are the pros & cons (if any) ? A: Pros: you can end up with code which is simpler to read. Few people would argue that: BigDecimal a = x.add(y).divide(z).plus(m.times(n)); is as easy to read as BigDecimal a = ((x + y) / z) + (m * n); // Brackets added for clarity Cons: it's harder to tell what's being called. I seem to remember that in C++, a statement of the form a = b[i]; can end up performing 7 custom operations, although I can't remember what they all are. I may be slightly "off" on the example, but the principle is right - operator overloading and custom conversions can "hide" code. A: EDIT: it has been mentioned that std::complex is a much better example than std::string for "good use" of operator overloading, so I am including an example of that as well: std::complex<double> c; c = 10.0; c += 2.0; c = std::complex<double>(10.0, 1.0); c = c + 10.0; Aside from the constructor syntax, it looks and acts just like any other built in type. The primary pro is that you can create new types which act like the built in types. A good example of this is std::string (see above for a better example) in c++. Which is implemented in the library and is not a basic type. Yet you can write things like: std::string s = "hello" s += " world"; if(s == "hello world") { //.... } The downside is that it is easy to abuse. Poor choices in operator overloading can lead to accidentally inefficient or unclear code. Imagine if std::list had an operator[]. You may be tempted to write: for(int i = 0; i < l.size(); ++i) { l[i] += 10; } that's an O(n^2) algorithm! Ouch. Fortunately, std::list does not have operator[] since it is assumed to be an efficient operation. A: The initial driver is usually maths. Programmers want to add vectors and quaternions by writing a + b and multiply matrices by vectors with M * v. It has much broader scope than that. For instance, smart pointers look syntactically like normal pointers, streams can look a bit like Unix pipes and various custom data structures can be used as if they were arrays (with strings as indexes, even!). The general principle behind overloading is to allow library implementors to enhance the language in a seamless way. This is both a strength and a curse. It provides a very powerful way to make the language seem richer than it is out of the box, but it is also highly vulnerable to abuse (more so than many other C++ features). A: You can do some interesting tricks with syntax (i.e. streams in C++) and you can make some code very concise. However, you can have the effect of making code very difficult to debug and understand. You sort of have to constantly be on your guard about the effects of various operators of different kinds of objects. A: You might deem operator overloading as a kind of method/function overloading. It is part of polymorphism in object oriented language. With overloading, each class of objects work like primitive types, which make classes more natural to use, just as easy as 1 + 2. Say a complex number class, Complex. Complex(1,2i) + Complex(2,3i) yields Complex(3,5i). 5 + Complex(3, 2i) yields Complex(8, 2i). Complex(2, 4i) + -1.8 yields Complex(0.2, 4i). It is much easier to use class this way. If there is no operator overloading, you have to use a bunch of class methods to denote 'add' and make the notation clumsy. The operator overloading ought to be defined carefully; otherwise, comes confusion. For example, '+' operator is natural to adding numbers, time, date, or concatenation of array or text. Adding '+' operator to a class of Mouse or Car might not make any sense. Sometimes some overloading might not be seem natural to some people. For example, Array(1,2,3) + Array(3,4,5). Some might expect Array(4,6,8) but some expect Array(1,2,3,3,4,5).
{ "language": "en", "url": "https://stackoverflow.com/questions/3183678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Would 2 consecutive .load calls in jquery execute async? In a script like the following, would the load functions be called in asynchronously or one after another? <script language="javascript" type="text/javascript"> $(document).ready(function () { $("#TheLink").click(){ $("#PlaceToUpdate1").load("/Controller/Method/View1"); $("#PlaceToUpdat2").load("/Controller/Method/View2"); } }); }); </script> A: Asynchronously, by default. If you need them to be one-after-the-other, you can do a few things: * *Place the second in the callback of the first. *Set $.ajax({async:false}) *You could possibly even set these up in a queue. The cleanest way is probably option 2. A: Yes, the full call for load is: load( url, [data], [callback] ) the third optional parameter is a callback method that will be called when the asynchronous load method completes.
{ "language": "en", "url": "https://stackoverflow.com/questions/2062241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: The syntax of my rename command is incorrect When trying to rename a file in a command prompt, I am getting the error: The syntax of the command is incorrect. Here's my command: rename "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs" "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs.old" A: rename does not support a path for the destination (just the new filename): rename "%userprofile%\AppData\LocalLow\Sun\Java\Deployment\security\trusted.certs" "trusted.certs.old"
{ "language": "en", "url": "https://stackoverflow.com/questions/48447486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Access value of Struct data I need to access value in a struct defined as mydata:struct<1:array<int>>. I tried accessing using mydata.1 but it is not a valid syntax. Sample data {1=[154873, 155630, 157698, 157945, 159058, 163148]} A: Simply quote the 1 with double quotes: SELECT mydata."1" FROM my_table A: This can be queried using unnest operator.You can use below query to fetch the items from array : select t1.* from test cross join UNNEST("mydata"."1") as t1(record);
{ "language": "en", "url": "https://stackoverflow.com/questions/64018625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable -Wreturn-type checking I am trying to compile Model 5.0 under OS X 10.8.3 I am getting a lot of warnings and errors while compiling. Several of those error are something like xwin.c:31523:2: error: non-void function 'scrfrg' should return a value [-Wreturn-type] return; What flag in C/C++ checks that? I want to disable it and try to finish the compilation. I'm not sure if this is the best forum to ask this, sorry for the inconvenience. A: As per the link you posted, seems you're using gcc. You can disable a lot of error/warning checks with a -Wno-xxxx flag, in your case -Wreturn-type is causing an error so you can disable it with: -Wno-return-type Frankly, it's better to just fix the errors/warnings when you can, and that one seems easy to fix.
{ "language": "en", "url": "https://stackoverflow.com/questions/16303232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Spark createdataframe cannot infer schema - default data types? I am creating a spark dataframe in databricks using createdataframe and getting the error: 'Some of types cannot be determined after inferring' I know I can specify the schema, but that does not help if I am creating the dataframe each time with source data from an API and they decide to restructure it. Instead I would like to tell spark to use 'string' for any column where a data type cannot be inferred. Is this possible? A: This can be easily handled with schema evaluation with delta format. Quick ref: https://databricks.com/blog/2019/09/24/diving-into-delta-lake-schema-enforcement-evolution.html
{ "language": "en", "url": "https://stackoverflow.com/questions/69650086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add RSS feed to a section of a View in Codeigniter I am completely new to Codeigniter and am trying to add an RSS feed to a section of my Home view as follows. I have asked this question already but I wasn't clear in how I presented my code so I have submitted it again. I have researched this on multiple forums especially this one and I am going round in circles but cant find an answer. Home View The home view contains a header image, a nav bar, a jumbotron and a login form. It also has the following section into which I want to add the RSS content. <div class="container"> <div class="row"> <div class="col-sm-8"><h1>Latest News</h1> <?php // RSS FEED HERE ?> I have one controller called "User that has the following code in its index function User Controller Code <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('user_model'); $this->load->library('rssparser'); } public function index() { if(($this->session->userdata('user_name')!="")) { $this->welcome(); } else { $data['title']= 'Home'; $this->load->view('include/header',$data); $this->load->view('pages/home.php', $data); $this->load->view('include/footer',$data); } } Controller method in User Controller to get RSS data The rss feed results are currently being stored in an unordered list public function get_news() { // Get 6 items from latest news $this->rssparser->set_feed_url('http://www.datadomain.com'); // get feed $this->rssparser->set_cache_life(30); // Set cache life time in minutes $rss = $this->rssparser->getFeed(6); echo '<ul>'; foreach ($rss as $item) { echo '<li>'; echo $item['title']; echo '</li>'; echo '<li>'; echo $item['description']; echo '</li>'; echo '<li>'; echo $item['link']; echo '</li>'; echo '<li>'; echo $item['pubDate']; echo '</li>'; } echo '</ul>'; } If I insert the following into my index function in my controller I can get the feed on my homepage but it appears at the top of the page and not in the section I need it in. $data['rss'] = $this->get_news(); I have tried adding $rss into the section of the view in my Home page but I just get an undefined variable error. I would appreciate if someone could help shed some light on this for me as I cant find a solution. Other methods and views used in my project Controller method Welcome() public function welcome() { $data['title']= 'Welcome'; $this->load->view('include/header',$data); $this->load->view('pages/welcome_view.php', $data); $this->load->view('include/footer',$data); } welcome_view This view represents the members area of the application. It doesn't hold any real content at the minute because the application is at the early stages of construction. <div class="container"> <div class="row"> <header class="page-header"> <img class="img-responsive" src="<?php echo site_url('../images/black_header.jpg'); ?>" /> </header> </div> </div> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs- example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo site_url('user/index') ?>">Premier Games</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="<?php echo site_url('user/index') ?>">Home</a></li> <li><a href="<?php echo site_url('user/register') ?>">Register</a></li> </ul> <p class="navbar-text navbar-right"><strong>Signed in as <?php echo $this->session->userdata('user_name'); ?></strong></p> </div><!-- /.navbar-collapse --> </nav> <div class="container"> <div class="content"> <h2><?php echo $this->session->userdata('user_name'); ?>, Welcome Back</h2> <p>This section represents the area that only logged in members can access.</p> <h4><?php echo anchor('user/logout', 'Logout'); ?></h4> </div><!--<div class="content">--> </div> A: Typically, you do the html parsing in a view. Not sure if you are loading a view... it isn't clear whether we are working with a logged in user or not. Let's assume we are not dealing with a logged in user and are calling $data['title']= 'Home'; $this->load->view('include/header',$data); $this->load->view('pages/home.php', $data); $this->load->view('include/footer',$data); The easiest way to do it would be to just dump the data into the view and do the layout/parsing there: controller: $data['title']= 'Home'; $data['rss'] = $this->get_news(); $this->load->view('include/header',$data); $this->load->view('pages/home.php', $data); $this->load->view('include/footer',$data); pages/home.php <div class="container"> <?php echo '<ul>'; foreach ($rss as $item) { echo '<li>'; echo $item['title']; echo '</li>'; echo '<li>'; echo $item['description']; echo '</li>'; echo '<li>'; echo $item['link']; echo '</li>'; echo '<li>'; echo $item['pubDate']; echo '</li>'; } echo '</ul>'; ?> </div> controller get_news(): public function get_news() { // Get 6 items from GAA latest news $this->rssparser->set_feed_url('http://www.rte.ie/rss/gaa.xml'); // get feed $this->rssparser->set_cache_life(30); // Set cache life time in minutes $rss = $this->rssparser->getFeed(6); return $rss; }
{ "language": "en", "url": "https://stackoverflow.com/questions/21261791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cordova APP - Is it possible to show camera feed in a container? I am using ionicFramework with Cordova to build an App. My requirement is to show (front) camera feed inside my app (say at top right corner of the app). Unfortunately "cordovaCapture" is not working for me. "navigator.camera" just opens camera view, but my requirement is to show its feed in a container so its also not fitting in requirement. I tried backgroundvideo plugin also. Please help me in understanding, Is it possible to access camera feed without going native app approach ? Please share any leads. Thanks in Advance. A: I'll just point you to the right direction: * *https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview *https://github.com/donaldp24/CanvasCameraPlugin Try these plugins (in order) and lemme know if either of them worked out for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/31128943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What's a functional replacement for if-then statements? I've been learning F# and functional programming and trying to do things the functional way. However, when it comes to rewriting some code I'd already written in C# I get stuck at simple if-then statements (ones that only do something, not return a value). I know you can pull this off in F#: if expr then do () However, I thought this was an imperative approach to coding? Maybe I've not learned enough about functional programming, but it doesn't seem functional to me. I thought the functional approach was to compose functions and expressions, not simply execute statements one after the other which is what if-then seems to encourage. So, am I missing something and if-then is perfectly fine in the functional world? If not, what is the functional equivalent of such a statement? How could I take an if-then and turn it functional? Edit: I might've asked the wrong question (sorry, still fairly new to functional programming): Let's take a real world example that made me even ask this: if not <| System.String.IsNullOrWhiteSpace(data) then do let byteData = System.Text.Encoding.Unicode.GetBytes(data) req.ContentLength <- int64 byteData.Length let postStream : System.IO.Stream = req.GetRequestStream() postStream.Write(byteData, 0, byteData.Length) postStream.Flush() postStream.Dispose() The body of that if-then doesn't return anything, but I don't know how I could make this more functional (if that's even possible). I don't know the proper technique for minimizing imperative code. Given F#'s nature it's fairly easy to just transport my C# directly, but I'm having difficulties turning it functional. Every time I reach such an if statement in C#, and I'm trying to transport it to F#, I get discouraged that I can't think of a way to make the code more functional. A: It's considered functional if your if statement has a return value and does not have side effects. Suppose you wanted to write the equivalent of: if(x > 3) n = 3; else n = x; Instead of doing that, you use the return statement from the if command: let n = (if x > 3 then 3 else x) This hypothetical if is suddenly functional because it has no side effects; it only returns a value. Think of it as if it were the ternary operator in some languages: int n = x>3?3:x; A: An important point that hasn't been mentioned so far is the difference between if .. then .. else and if .. then without the else branch. If in functional languages The functional interpretation of if is that it is an expression that evaluates to some value. To evaluate the value of if c then e1 else e2 you evaluate the condition c and then evaluate either e1 or e2, depending on the condition. This gives you the result of the if .. then .. else. If you have just if c then e, then you don't know what the result of the evaluation should be if c is false, because there is no else branch! The following clearly does not make sense: let num = if input > 0 then 10 In F#, expressions that have side-effects like printf "hi" return a special value of type unit. The type has only a single value (written as ()) and so you can write if which does an effect in just a single case: let u = if input > 0 then printf "hi" else () This always evaluates to unit, but in the true branch, it also performs the side-effect. In the false branch, it just returns a unit value. In F#, you don't have to write the else () bit by hand, but conceptually, it is still there. You can write: let u = if input > 0 then printfn "hi" Regarding your additional example The code looks perfectly fine to me. When you have to deal with API that is imperative (like lots of the .NET libraries), then the best option is to use the imperative features like if with a unit-returning branch. You can use various tweaks, like represent your data using option<string> (instead of just string with null or empty string). That way, you can use None to represent missing data and anything else would be valid input. Then you can use some higher-order functions for working with options, such as Option.iter, which calls a given function if there is a value: maybeData |> Option.iter (fun data -> let byteData = System.Text.Encoding.Unicode.GetBytes(data) req.ContentLength <- int64 byteData.Length use postStream = req.GetRequestStream() postStream.Write(byteData, 0, byteData.Length) ) This is not really less imperative, but it is more declarative, because you don't have to write the if yourself. BTW: I also recommend using use if you want to Dispose object auotmatically. A: There are two observations that can assist in the transition from imperative to functional ("everything is an expression") programming: * *unit is a value, whereas an expression returning void in C# is treated as a statement. That is, C# makes a distinction between statements and expressions. In F# everything is an expression. *In C# values can be ignored; in F# they cannot, therefore providing a higher level of type safety. This explicitness makes F# programs easier to reason about and provides greater guarantees. A: There's nothing wrong with if-then in functional world. Your example is actually similar to let _ = expr since expr has side effects and we ignore its return value. A more interesting example is: if cond then expr which is equivalent to: match cond with | true -> expr | false -> () if we use pattern matching. When the condition is simple or there is only one conditional expression, if-then is more readable than pattern matching. Moreover, it is worth to note that everything in functional programming is expression. So if cond then expr is actually the shortcut of if cond then expr else (). If-then itself is not imperative, using if-then as a statement is an imperative way of thinking. From my experience, functional programming is more about the way of thinking than concrete control flows in programming languages. EDIT: Your code is totally readable. Some minor points are getting rid of redundant do keyword, type annotation and postStream.Dispose() (by using use keyword): if not <| System.String.IsNullOrWhiteSpace(data) then let byteData = System.Text.Encoding.Unicode.GetBytes(data) req.ContentLength <- int64 byteData.Length use postStream = req.GetRequestStream() postStream.Write(byteData, 0, byteData.Length) postStream.Flush() A: It's not the if-expression that's imperative, it's what goes in the if-expression. For example, let abs num = if num < 0 then -num else num is a totally functional way to write the abs function. It takes an argument and returns a transformation of that argument with no side effects. But when you have "code that only does something, not return a value," then you're writing something that isn't purely functional. The goal of functional programming is to minimize the part of your program that can be described that way. How you write your conditionals is tangential. A: In order to write complex code, you need to branch at some point. There's a very limited number of ways you can do that, and all of them require a logical flow through a section of code. If you want to avoid using if/then/else it's possible to cheat with loop/while/repeat - but that will make your code far less reasonable to maintain and read. Functional programming doesn't mean you shouldn't execute statements one after the other - it simply means that you shouldn't have a mutable state. Each function needs to reliably behave the same way each time it is called. Any differences in how data is handled by it need to be accounted for by the data that is passed in, instead of some trigger that is hidden from whatever is calling the function. For example, if we have a function foo(int, bool) that returns something different depending on whether bool is true or false, there will almost certainly be an if statement somewhere in foo(). That's perfectly legitimate. What is NOT legitimate is to have a function foo(int) that returns something different depending on whether or not it is the first time it is called in the program. That is a 'stateful' function and it makes life difficult for anyone maintaining the program. A: My apologies for not knowing F#, but here is one possible solution in javascript: function $if(param) { return new Condition(param) } function Condition(IF, THEN, ELSE) { this.call = function(seq) { if(this.lastCond != undefined) return this.lastCond.call( sequence( this.if, this.then, this.else, (this.elsif ? this.elsif.if : undefined), seq || undefined ) ); else return sequence( this.if, this.then, this.else, (this.elsif ? this.elsif.if : undefined), seq || undefined ) } this.if = IF ? IF : f => { this.if = f; return this }; this.then = THEN ? THEN : f => { this.then = f; return this }; this.else = ELSE ? ELSE : f => { this.else = f; return this }; this.elsif = f => {this.elsif = $if(f); this.elsif.lastCond = this; return this.elsif}; } function sequence(IF, THEN, ELSE, ELSIF, FINALLY) { return function(val) { if( IF(val) ) return THEN(); else if( ELSIF && ELSIF(val) ) return FINALLY(val); else if( ELSE ) return ELSE(); else return undefined } }} The $if function returns an object with the if..then..else..elsif construct, using the Condition constructor. Once you call Condition.elsif() you'll create another Condition object - essentially creating a linked list that can be traversed recursively using sequence() You could use it like: var eq = val => x => x == val ? true : false; $if( eq(128) ).then( doStuff ).else( doStuff ) .elsif( eq(255) ).then( doStuff ).else( doStuff ).call(); However, I realize that using an object is not a purely functional approach. So, in that case you could forgo the object all together: sequence(f, f, f, f, sequence(f, f, f, f sequence(f, f, f) ) ); You can see that the magic is really in the sequence() function. I won't try to answer your specific question in javascript. But I think the main point is that you should make a function that will run arbitrary functions under an if..then statement, then nest multiples of that function using recursion to create a complex logical chain. At least this way you will not have to repeat yourself ;) This code is just a prototype so please take it as a proof of concept and let me know if you find any bugs.
{ "language": "en", "url": "https://stackoverflow.com/questions/9298419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Google Spreadsheet Script Trigger: This app is blocked I am trying to create a trigger for a script in google spreadsheet and upon trying to save the trigger I am getting the following error: This app is blocked This app tried to access sensitive info in your Google Account. To keep your account safe, Google blocked this access. I don't have G-Suite, I don't have an organization, I am simply using my personal Gmail account. I don't have the special account protection thing enabled. I tried using different scripts, even an empty script. What could be the problem here? I have used scripts and add-ons in the past, but haven't needed triggers yet. Is there another way to run a script daily or monthly, without this trigger functionality? A: There is currently a bug I recommend oyu to "star" it to increase visibility, so it hopefully gets fixed soon. A: Try this: Unable to open Google xlsx spreadsheet / Also Google Drive permission Blocked The same solution logic can solve this problem. [ ]
{ "language": "en", "url": "https://stackoverflow.com/questions/66333420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call method on a child React.Component from a parent React.FunctionalComponent? How can I call a method on a child component from a parent component? I'm not sure it matters but my parent component is a functional component and the child is a class component. I'm hoping that the switch to function components doesn't mean that all class-based components need to be upgraded? The parent component looks like this: const Home: React.FC = () => { const grid = useRef(); const buttonClick = () => { // I want to be able to call a method on <MyGrid> here to // tell it to reload the grid (for example) grid.current!.reconfigure(); }; return ( <React.Fragment> <JqxButton onClick={buttonClick}>Refresh Grid</JqxButton> <MyGrid ref={grid} /> </React.Fragment> ); }; This actually works, though not without errors (which don't seem to crash the app in code sandbox, but it won't compile in VS Code offline). The 'ref' property on MyGrid shows this error: Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: MyGrid | null) => void) | RefObject<MyGrid> | null | undefined'. Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<MyGrid>'. Types of property 'current' are incompatible. Type 'undefined' is not assignable to type 'MyGrid | null'.ts(2322) My call to grid.current!.reconfigure() results in this error: Property 'reconfigure' does not exist on type 'never'. I've created a code sandbox with the full setup of the parent and child components here: https://codesandbox.io/s/react-fc-call-child-component-14rr3
{ "language": "en", "url": "https://stackoverflow.com/questions/56964896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access a variable from another script in another gameobject through GetComponent? I've searched around and I just can't get this to work. I think I just don't know the proper syntax, or just doesn't quite grasp the context. I have a BombDrop script that holds a public int. I got this to work with public static, but Someone said that that is a really bad programming habit and that I should learn encapsulation. Here is what I wrote: BombDrop script: <!-- language: c# --> public class BombDrop : MonoBehaviour { public GameObject BombPrefab; //Bombs that the player can drop public int maxBombs = 1; // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.Space)){ if(maxBombs > 0){ DropBomb(); //telling in console current bombs Debug.Log("maxBombs = " + maxBombs); } } } void DropBomb(){ // remove one bomb from the current maxBombs maxBombs -= 1; // spawn bomb prefab Vector2 pos = transform.position; pos.x = Mathf.Round(pos.x); pos.y = Mathf.Round(pos.y); Instantiate(BombPrefab, pos, Quaternion.identity); } } So I want the Bomb script that's attached to the prefabgameobject Bombprefab to access the maxBombs integer in BombDrop, so that when the bomb is destroyed it adds + one to maxBombs in BombDrop. And this is the Bomb script that needs the reference. public class Bomb : MonoBehaviour { // Time after which the bomb explodes float time = 3.0f; // Explosion Prefab public GameObject explosion; BoxCollider2D collider; private BombDrop BombDropScript; void Awake (){ BombDropScript = GetComponent<BombDrop> (); } void Start () { collider = gameObject.GetComponent<BoxCollider2D> (); // Call the Explode function after a few seconds Invoke("Explode", time); } void OnTriggerExit2D(Collider2D other){ collider.isTrigger = false; } void Explode() { // Remove Bomb from game Destroy(gameObject); // When bomb is destroyed add 1 to the max // number of bombs you can drop simultaneously . BombDropScript.maxBombs += 1; // Spawn Explosion Instantiate(explosion, transform.position, Quaternion.identity); In the documentation it says that it should be something like BombDropScript = otherGameObject.GetComponent<BombDrop>(); But that doesn't work. Maybe I just don't understand the syntax here. Is it suppose to say otherGameObject? Cause that doesn't do anything. I still get the error : "Object reference not set do an instance of an object" on my BombDropScript.maxBombs down in the explode() A: You need to find the GameObject that contains the script Component that you plan to get a reference to. Make sure the GameObject is already in the scene, or Find will return null. GameObject g = GameObject.Find("GameObject Name"); Then you can grab the script: BombDrop bScript = g.GetComponent<BombDrop>(); Then you can access the variables and functions of the Script. bScript.foo(); I just realized that I answered a very similar question the other day, check here: Don't know how to get enemy's health I'll expand a bit on your question since I already answered it. What your code is doing is saying "Look within my GameObject for a BombDropScript, most of the time the script won't be attached to the same GameObject. Also use a setter and getter for maxBombs. public class BombDrop : MonoBehaviour { public void setMaxBombs(int amount) { maxBombs += amount; } public int getMaxBombs() { return maxBombs; } } A: use it in start instead of awake and dont use Destroy(gameObject); you are destroying your game Object then you want something from it void Start () { BombDropScript =gameObject.GetComponent<BombDrop> (); collider = gameObject.GetComponent<BoxCollider2D> (); // Call the Explode function after a few seconds Invoke("Explode", time); } void Explode() { //.. //.. //at last Destroy(gameObject); } if you want to access a script in another gameObject you should assign the game object via inspector and access it like that public gameObject another; void Start () { BombDropScript =another.GetComponent<BombDrop> (); } A: Can Use this : entBombDropScript.maxBombs += 1; Before : Destroy(gameObject); I just want to say that you can increase the maxBombs value before Destroying the game object. it is necessary because, if you destroy game object first and then increases the value so at that time the reference of your script BombDropScript will be gone and you can not modify the value's in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/26551575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: C# Access to the path is denied... Client.Download(filelink, path) I've a problem with my code: when I try to download a file from dropbox, and put it in my Roaming folder something goes wrong, here's the error Log: System.Net.WebException: An exception occurred during a WebClient request. ---> System.UnauthorizedAccessException: Access to the path'C:\Users\Marco\AppData\Roaming\.maycraft' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) at System.Net.WebClient.DownloadFile(Uri address, String fileName) --- End of inner exception stack trace --- at System.Net.WebClient.DownloadFile(Uri address, String fileName) at System.Net.WebClient.DownloadFile(String address, String fileName) at MayCraftLauncher.Program.downloadExist() in c:\Users\Marco\Desktop\MayCraftLauncher\C# SourceCode\MayCraftLauncher\MayCraftLauncher\Program.cs:line 71 Obviously I tried to run Visual Studio with administator rights, but nothing... And here's the code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Security.Principal; using System.IO; using System.IO.Compression; using Ionic.Zip; namespace MayCraftLauncher { class Program { public static System.Threading.Thread existDownloading = new System.Threading.Thread(downloadExist); public static string userName = Environment.UserName; public static string path = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft\Exist"; public static string maypath = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft"; static void Main(string[] args) { folderExist(); } static void check1() { while (!Directory.Exists(maypath)) { System.Threading.Thread.Sleep(5000); } existDownloading.Start(); } static void folderExist() { if (!Directory.Exists(maypath)) { System.Diagnostics.Process.Start(@"C:\Users\Marco\Desktop\MayCraftLauncher.jar"); check1(); } else { fileExist(); } } static void fileExist() { if (File.Exists(path)) //Determina se è la prima volta che l'applicazione viene eseguita { Console.WriteLine("Exist"); Console.ReadLine(); } else { existDownloading.Start(); Console.WriteLine("Downloading..."); } } static void downloadExist() { WebClient Client = new WebClient(); DateTime btime = DateTime.Now; path = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft\"; string publicLinkExist = @"https://dl.dropbox.com/u/35356155/minecraft/download/Exist"; //string publicLinkMods = @"https://dl.dropbox.com/u/35356155/minecraft/download/mods.7z"; string publicLinkMods = @"https://dl.dropbox.com/u/35356155/minecraft/download/mcp.7z"; try { //----------------File downloading------------------- Client.DownloadFile(publicLinkExist, path); DirectoryInfo dev = Directory.CreateDirectory(path); string devpath = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft"; Client.DownloadFile(publicLinkMods, devpath); DateTime atime = DateTime.Now; Console.WriteLine("Downloading time: " + atime.Subtract(btime).TotalSeconds + " sec."); //---------------Files Extracion------------------- using (ZipFile zip = ZipFile.Read(devpath)) { zip.ExtractAll(path); } } catch (Exception e) { Console.WriteLine(e); System.IO.File.WriteAllText(@"C:\Users\Marco\Desktop\log.txt", e.ToString()); Console.ReadKey(); } existDownloading.Abort(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/12730441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSMutableArray not responding to removeObjectAtIndex: I think i've run into a confused state where i'm doing something fundamentally wrong, but i cannot understand what and why this is happening. Picture 1: A property of a My class. A NSMutableArray. Picture2: The code block i want to execute, i want to remove the eleventh object. Picture3: The debug console shows me that i have 30 objects within my array. And now, here i was, thinking that this would be an easy task. Since, i've removed and replaced objects at indexes in other NSMutableArrays within my source-code. Here comes Picture4: I believe this is telling me that NSMutableArray doesn't respond to removeObjectAtIndex. Does anyone know what in the heck i'm doing wrong? I'm totally confused. And no, this is not homework...even if one could believe so. I do. EDIT: The error was made during parsing of the objects that went into the dagArray. Instead of [tempPeriod.dagArray addObject:object] i was doing something completely different. I was working with a different array and added objects to that array, and when the parser was finished i used tempPeriod.dagArray = [theOtherArray copy] which resulted in this error. theOtherArray was still a NSMutableArray which still confused me. But my best guess is that copy does something with the NSMutableArray rendering it unable to perform those selectors. But i could be completely wrong. Thanks for shining some thoughts into this. A: actually it says that NSArray doesn't respond to removeObjectAtIndex. Which would be true. Could it be that you define it as NSMutableArray, but initialise it in a wrong way? Where do you init the array, is it possible that the current array is actually a NSArray? because: NSMutableArray *anArray = [[NSArray alloc] initWithObject:anObject]; is possible, but would result in runtime errors when you select the wrong selectors. A: You need to use -mutableCopy if you want a mutable copy of an array. Using -copy, even on a mutable array, will give you an immutable array.
{ "language": "en", "url": "https://stackoverflow.com/questions/13342169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sqlite Database Error: The FMDatabase is not open. I'm getting this Error "The FMDatabase is not open". Even after i open my database first before executing query. Here's the code of instance of database which i'm using to open database. var instance = ModelManager() class ModelManager: NSObject { var database: FMDatabase? = nil var database2: FMDatabase? = nil var resultSet: FMResultSet! class func getInstance(sqllite:String) -> ModelManager { if(instance.database == nil){ instance.database = FMDatabase(path: Util.getPath(sqllite)) } return instance } class func getInstance2(sqllite:String) -> ModelManager { if(instance.database2 == nil){ instance.database2 = FMDatabase(path: Util.getPath(sqllite)) } return instance } } and this is the the code where i am getting error. func saveImageAudio(audioFile:String?,imageFile:String?,isImage:Bool){ guard (instance.database?.open())! else { return } let fileName = isImage == true ? imageFile : audioFile var paramName = isImage == true ? "imageList" : "audioList" let countParam = isImage == true ? "imageCount" : "audioCount" let time = Util.DateTime() guard increaseLastNo(isImage: isImage) else { return } do { let FileArray = getImageAudiolist(isImagelist: isImage) var query = "" var values:[Any] = [] if FileArray.count == 0 { query = "update RoomSectionDetails set \(paramName) = ?, \(countParam) = 1 ,modified_dtm = ? where pda_guid = ? and roomName = ? and sectionID = ? and dead = ?" values = [fileName!,time,pda_guid,roomName,sectionId,0] }else{ query = "update RoomSectionDetails set \(paramName) = \(paramName) || ?, \(countParam) = \(countParam) + 1, modified_dtm = ? where pda_guid = ? and roomName = ? and sectionID = ? and dead = ?" values = [",\(fileName!)",time,pda_guid,roomName,sectionId,0] } try instance.database?.executeUpdate(query, values: values) paramName = isImage == true ? "lastImageNo" : "lastAudioNo" if !isImage { self.updateAudioDuration() } } catch { print("Error while Saving Image Audio in DB") } instance.database?.close() } Please give the solution for this problem. I wasn't closing database ever time after firing queries. that causes cpu usages more then 200. So now i'm closing database. but i am getting this error. Thanks for Help. A: I found the Solution for this problem. I am having method inside method which closing the database. Because of that error coming. Thanks for help.
{ "language": "en", "url": "https://stackoverflow.com/questions/46292229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrolling divs not scrolling to bottom of content I have 2 scrolling divs (outlined in red) that will not scroll to the their respective bottoms. I can't seem to seem to figure out what to tweak to fix it. The thick outlined box is a simulated browser window. http://jsfiddle.net/jsk55rfb/4/ HTML <div class="container"> <div class="header"></div> <div class="sidebar"></div> <div class="main"> <div class="detail-container"> <div class="top-info"></div> <div class="items-container"> <div class="item blue"></div> <div class="item orange"></div> <div class="item blue"></div> <div class="item orange"></div> </div> </div> <div class="main-container"> <div class="main-header"></div> <div class="main-content"> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> </div> </div> </div> </div> CSS .container { height: 500px; width: 500px; border: solid 3px black; overflow: hidden; } .header { height: 25px; background-color: #333; right: 0; left: 0; } .sidebar { position: fixed; top: 0; bottom: 0; width: 75px; margin-top: 35px; border: solid 1px grey; } .main { height: 100%; padding-left: 75px; } .main-container { width: 65%; height: 100%; } .main-content { height: 100%; overflow-y: scroll; border: solid 1px red; } .main-header { height: 20px; border: 1px solid black; } .detail-container { float: right; width: 35%; height: 100%; border: solid 1px grey; } .top-info { padding: 75px 0; } .items-container { height: 100%; overflow-y: scroll; border: solid 1px red; } .item { padding: 100px 0; } .blue { background-color: blue; } .orange { background-color: orange; } .grey { background-color: grey; } .purple { background-color: purple; } .content { width: 65%; height: 100%; } A: You have a fixed height for the container and overflow set to hidden. Since the divs exceed that height, the overflow can't be seen. Try this: .container { height: 500px; width: 500px; border: solid 3px black; overflow: scroll; } .header { height: 25px; background-color: #333; right: 0; left: 0; } .sidebar { position: fixed; top: 0; bottom: 0; width: 75px; margin-top: 35px; border: solid 1px grey; } .main { height: 100%; padding-left: 75px; } .main-container { width: 65%; height: 100%; } .main-content { height: 100%; overflow-y: scroll; border: solid 1px red; } .main-header { height: 20px; border: 1px solid black; } .detail-container { float: right; width: 35%; height: 100%; border: solid 1px grey; } .top-info { padding: 75px 0; } .items-container { height: 100%; overflow-y: scroll; border: solid 1px red; } .item { padding: 100px 0; } .blue { background-color: blue; } .orange { background-color: orange; } .grey { background-color: grey; } .purple { background-color: purple; } .content { width: 65%; height: 100%; } <div class="container"> <div class="header"></div> <div class="sidebar"></div> <div class="main"> <div class="detail-container"> <div class="top-info"></div> <div class="items-container"> <div class="item blue"></div> <div class="item orange"></div> <div class="item blue"></div> <div class="item orange"></div> </div> </div> <div class="main-container"> <div class="main-header"></div> <div class="main-content"> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> <div class="item grey"></div> <div class="item purple"></div> </div> </div> </div> </div> A: I could solve this with some javascript. This should addapt to any content size of your other blocks as long as the markup structure doesn't change. Good luck! $(function(){ //creating vars based on jquery objects $itemsContainer = $('.items-container'); $mainContent = $('.main-content'); $container = $('.container'); $header = $('.header'); $mainHeader = $('.main-header'); //calculating heights var containerH = $container.height(); var headerH = $header.height(); var mainHeaderH = $mainHeader.height(); //assigning new height to main-content class $mainContent.css("height", (containerH - headerH - mainHeaderH) + "px"); //similar operation for items-container //creating vars based on jquery objects $topInfo = $('.top-info'); //calculating heights var topInforH = $topInfo.outerHeight(); //since in your example top-info has no content only padding, you will need to use the method outerHeight instead of height //assigning new height to main-content class $itemsContainer.css("height", (containerH - headerH - topInforH) + "px"); }); By the way, I updated your jsfiddle with my solution, so you can test it. A: When you use a height of 100% it sets it to the full height regardless of other sibling elements. So they are at 100% of the parent element but then the headers are pushing them down. You will have to use fixed heights on all elements. Or set one to 20% and other to 80% etc. .main-content { width: 452px; } .items-container {width: 352px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/26261899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to remove space between numbers in ASP.Net using RegEx I need to remove the space between the numbers using RegEx means I want to make a formated number from the input like {lhs: \"1000 U.S. dollars\",rhs: \"58 740.6015 Indian rupees\",error: \"\",icc: true} I tried the following expression Regex regex = new Regex("rhs: \\\"(\\d+.\\d*)"); but its give me a error "Input format not correct" so how can I remove the space between the numbers P.S The currency name will change each time it called A: use the following expression string value = Regex.Replace(response.Split(',')[1], "[^.0-9]", "");
{ "language": "en", "url": "https://stackoverflow.com/questions/17187534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error using Play Framework debug command I try to launch my play project in debug mode with the play debug command, and it display me an error I can't resolve, despite of Google research... I found many topics about it, but no solution worked for me. Tried to change debug port, run as administrator, disable firewall.. Error message : ERROR: transport error 202: bind failed: Permission denied ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510) JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750] FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197) NOTE : On my computer, Windows Kernel is using port 9999 Have you got the same error and found a fix for it ? A: You could try * *Deactivating any antivirus or firewall; *Check ports in use by netstat command *Changing play.bat debug port (at play's folder root) and save it Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/27232386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Deploy WAR to TomEE server I built my JavaEE project & got my-service.war file. I want to deploy it to TomEE server. I have successfully installed TomEE (I can start & stop TomEE server successfully). I copy my-service.war to <TomEE_Home>/webapps/ Then, I start TomeEE server. I open my browser, and put URL http://localhost:8080/my-service But I get HTTP Status 404 page. (Then, I checked under /webapps/ that, my-server.war has been unzipped by server, because I see my-server folder there.) What do I miss for deploying my WAR to TomEE server? =====server logs ===== I got checked /logs/catalina.2016-08-16.log , I see these errors: webapps/my-service/WEB-INF/classes/ looking all classes to find CDI beans, maybe think to add a beans.xml if not there or add the jar to exclusions.list ... org.apache.catalina.core.StandardContext.startInternal Context [/my-service] startup failed due to previous errors 16-Aug-2016 13:51:46.311 INFO [localhost-startStop-1] org.apache.openejb.assembler.classic.Assembler.destroyApplication Undeploying app: /Users/xichen/Dev-tools/apache-tomee-webprofile-7.0.1/webapps/my-service A: You should check logs/catalina.date.log and logs/localhost..log files. If you are under unix execute: grep SEVERE logs/* to get the errors. The real error associated with Context [/my-service] startup failed due to previous errors Is before in the logs
{ "language": "en", "url": "https://stackoverflow.com/questions/38972721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving activity into pdf file I need to save Activity content into .pdf file. Something like a screenshot. I can save individual views of a activity into file using this code: PdfDocument document = new PdfDocument(); PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(600,300, 1).create(); PdfDocument.Page page = document.startPage(pageInfo); View content = findViewById(R.id.editText1); content.draw(page.getCanvas()); document.finishPage(page); But how to save (printscreen) whole activity, not just a views? Thank you. A: You can take a screenshot of the current activity using the given code public void saveBitmap(Bitmap bitmap) { File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png"); FileOutputStream fos; try { fos = new FileOutputStream(imagePath); bitmap.compress(CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { Log.e("GREC", e.getMessage(), e); } catch (IOException e) { Log.e("GREC", e.getMessage(), e); } } and make sure give write permissions of the storage in manifest <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
{ "language": "en", "url": "https://stackoverflow.com/questions/37046302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Web Start return value - workaround I know that returning a value from a JWSapp to the "calling" page cannot be done. However, I use this JWSapp to get user ID from its biometric information. The idea is that when you try to login, a button allows to launch the JWSapp that will deal with the biometric tasks and then return the user's idea. Still, as I said, from a JWSapp I cannot send back the id to auto-complete the field. I found this post: Returning a value from a java web start application but I really need to keep the JWS (external constraints)... So there's my question: is there any workaround to get the id back? Thank you in advance :)
{ "language": "en", "url": "https://stackoverflow.com/questions/37682860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storyboard vs. iOS Simulator WYSIWYG This is my problem: Left side: iOS Simulator Right side: Storyboard / Interface Builder Any ideas? Thanks ... UI Elements placed in IB appears shifted up in Simulator Maybe a better solution than this ... I have two xibs with the exact same look, one is shifted up, the other one works fine. A: OK, however. My workaround is to change the view hierarchy and set the UIImageView behind the UINavigationItem. Seems to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/10163347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Missing MySQL DLL? I've recreated the Northwind Spring/NHibernate example that comes with Spring.NET, but with MySQL rather than SQLServer. I've almost got it working I think, but I'm getting this when I try to use Hibernate to load something from the database A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll NHibernate.Util.ReflectHelper: ERROR lambda_method - Could not load type MySql.Data.MySqlClient.MySqlCommand, MySql.Data. System.IO.FileNotFoundException: Could not load file or assembly 'MySql.Data' or one of its dependencies. The system cannot find the file specified. File name: 'MySql.Data' Every project (DAO, Service, Web) has a reference to the MySQL.Data DLL so I'm a bit unsure what's going on. Can anyone help me please? A: Make sure that MySQL.Data.dll actually got copied to the output folder. And that you are using right platform (x32 vs x64 bit) and right version of .NET (2,3,3.5 vs 4). If everyhing seems fine, enable Fusion Logging and take a look at this article: For FileNotFoundException: At the bottom of the log will be the paths that Fusion tried probing for this assembly. If this was a load by path (as in Assembly.LoadFrom()), there will be just one path, and your assembly will need to be there to be found. Otherwise, your assembly will need to be on one of the probing paths listed or in the GAC if it's to be found. You may also get this exception if an unmanaged dependency or internal module of the assembly failed to load. Try running depends.exe on the file to verify that unmanaged dependencies can be loaded. Note that if you re using ASP.NET, the PATH environment variable it's using may differ from the one the command line uses. If all of them could be loaded, try ildasm.exe on the file, double-click on "MANIFEST" and look for ".file" entries. Each of those files will need to be in the same directory as the manifest-containing file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7451219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I set a System.env variable in Android Studio? In my build.gradle file in Android Studio using NDK, I have the following code. The app builds if I run it from the terminal with "./gradlew --assembleDebug" since I have set the path for ANDROID_NDK_HOME to /Users/chenige/Desktop/android-ndk-r9, but it will not build from inside Android Studio. From inside Android Studio, System.env.ANDROID_NDK_HOME is "null". Does anybody know why/how I can fix this? task buildNative(type: Exec) { if (System.env.ANDROID_NDK_HOME != null) { def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build') commandLine ndkBuild } else { doLast { println '##################' println 'Skipping NDK build' println 'Reason: ANDROID_NDK_HOME not set.' println '##################' } } } } A: Android Studio doesn't read environment variables, so this approach won't work. Also, using the projectDir scheme in settings.gradle will probably cause problems. Android Studio has a limitation that all of its modules need to be located underneath the project root. If you have libraries that are used in multiple projects and they can't be placed under a single project root, the best advice is to have them publish JARs or AARs to a local Maven repository that individual projects can pick up. read more Environment variable in settings.gradle not working with Android Studio A: It works for me with the follwoing steps: * *Set your variable in Windows *Reboot *reach it in gradle build: "$System.env.MYVARIABLE"
{ "language": "en", "url": "https://stackoverflow.com/questions/23714697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Programmatic Views how to set unique id's? I am creating in my app bunch of programmatic Views. As it appeared to be they all by default have the same id=-1. In order to work with them I need to generate unique id's. I have tried several approaches - random number generation and based on current time, but anyway there's no 100% guarantee that different Views will have different id's Just wondering is there any more reliable way to generate unique ones? Probably there's special method/class? A: Just want to add to Kaj's answer, from API level 17, you can call View.generateViewId() then use the View.setId(int) method. In case you need it for targets lower than level 17, here is its internal implementation in View.java you can use directly in your project: private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); /** * Generate a value suitable for use in {@link #setId(int)}. * This value will not collide with ID values generated at build time by aapt for R.id. * * @return a generated ID value */ public static int generateViewId() { for (;;) { final int result = sNextGeneratedId.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (sNextGeneratedId.compareAndSet(result, newValue)) { return result; } } } ID number larger than 0x00FFFFFF is reserved for static views defined in the /res xml files. (Most likely 0x7f****** from the R.java in my projects.) From the code, somehow Android doesn't want you to use 0 as a view's id, and it needs to be flipped before 0x01000000 to avoid the conflits with static resource IDs. A: Just an addition to the answer of @phantomlimb, while View.generateViewId() require API Level >= 17, this tool is compatibe with all API. according to current API Level, it decide weather using system API or not. so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the same time and don't worry about getting same id import java.util.concurrent.atomic.AtomicInteger; import android.annotation.SuppressLint; import android.os.Build; import android.view.View; /** * {@link View#generateViewId()}要求API Level >= 17,而本工具类可兼容所有API Level * <p> * 自动判断当前API Level,并优先调用{@link View#generateViewId()},即使本工具类与{@link View#generateViewId()} * 混用,也能保证生成的Id唯一 * <p> * ============= * <p> * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API. * <p> * according to current API Level, it decide weather using system API or not.<br> * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the * same time and don't worry about getting same id * * @author [email protected] */ public class ViewIdGenerator { private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); @SuppressLint("NewApi") public static int generateViewId() { if (Build.VERSION.SDK_INT < 17) { for (;;) { final int result = sNextGeneratedId.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (sNextGeneratedId.compareAndSet(result, newValue)) { return result; } } } else { return View.generateViewId(); } } } A: Regarding the fallback solution for API<17, I see that suggested solutions start generating IDs starting from 0 or 1. The View class has another instance of generator, and also starts counting from number one, which will result in both your and View's generator generating the same IDs, and you will end up having different Views with same IDs in your View hierarchy. Unfortunately there is no a good solution for this but it's a hack that should be well documented: public class AndroidUtils { /** * Unique view id generator, like the one used in {@link View} class for view id generation. * Since we can't access the generator within the {@link View} class before API 17, we create * the same generator here. This creates a problem of two generator instances not knowing about * each other, and we need to take care that one does not generate the id already generated by other one. * * We know that all integers higher than 16 777 215 are reserved for aapt-generated identifiers * (source: {@link View#generateViewId()}, so we make sure to never generate a value that big. * We also know that generator within the {@link View} class starts at 1. * We set our generator to start counting at 15 000 000. This gives us enough space * (15 000 000 - 16 777 215), while making sure that generated IDs are unique, unless View generates * more than 15M IDs, which should never happen. */ private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000); /** * Generate a value suitable for use in {@link View#setId(int)}. * This value will not collide with ID values generated at build time by aapt for R.id. * * @return a generated ID value */ public static int generateViewId() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { return generateUniqueViewId(); } else { return View.generateViewId(); } } private static int generateUniqueViewId() { while (true) { final int result = viewIdGenerator.get(); // aapt-generated IDs have the high byte nonzero; clamp to the range under that. int newValue = result + 1; if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. if (viewIdGenerator.compareAndSet(result, newValue)) { return result; } } } } A: Since support library 27.1.0 there's generateViewId() in ViewCompat ViewCompat.generateViewId() A: Create a singleton class, that has an atomic Integer. Bump the integer, and return the value when you need a view id. The id will be unique during the execution of your process, but wil reset when your process is restarted. public class ViewId { private static ViewId INSTANCE = new ViewId(); private AtomicInteger seq; private ViewId() { seq = new AtomicInteger(0); } public int getUniqueId() { return seq.incrementAndGet(); } public static ViewId getInstance() { return INSTANCE; } } Note that the id might not be unique, if there already are views that have ids in the view 'graph'. You could try to start with a number that is Integer.MAX_VALUE, and decrease it instead of going from 1 -> MAX_VALUE
{ "language": "en", "url": "https://stackoverflow.com/questions/6790623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Php, Symfony 1.4,doctrine I want to convert this mysql syntax into a doctrine 1.2 syntax. I want to show dates with zero values and print some errors on it. Also, is PHP foreach loop relevant for this for the templates/views? SELECT calendar.datefield AS DATE, IFNULL(SUM(orders.quantity),0) AS total_sales FROM orders RIGHT JOIN calendar ON (DATE(orders.order_date) = calendar.datefield) WHERE (calendar.datefield BETWEEN (SELECT MIN(DATE(order_date)) FROM orders) AND (SELECT MAX(DATE(order_date)) FROM orders)) GROUP BY DATE..
{ "language": "en", "url": "https://stackoverflow.com/questions/24257997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting InvalidOperationException: Incorrect Content-Type: text/plain exception when processing file through Web API Core I am having an API.Net Core Web API app that has a POST method that accepts and processes a PDF file. However, when I try to test in POSTMAN (Selecting POST, selecting Binary, choosing a file) I get a following error InvalidOperationException: Incorrect Content-Type: text/plain At the following line var file = Request.Form.Files[0]; Please let me know if there is anything I need to fix Thank you in advance Here is the entire method [HttpPost] [Route("SubmitForm")] public async Task<IActionResult> SubmitForm() { var file = Request.Form.Files[0]; HttpClient client = GetClient(); try { byte[] docAsBytes; using (var ms = new MemoryStream()) { file.CopyTo(ms); docAsBytes = ms.ToArray(); string s = Convert.ToBase64String(docAsBytes); // act on the Base64 data } PdfReader pdfReader = new PdfReader(docAsBytes); MemoryStream m = new MemoryStream(); PdfStamper outStamper = new PdfStamper(pdfReader, m); string formName = outStamper.AcroFields.GetField("FormSeqNo"); string endpointUrl = "https://myproject.sharepoint.com/sites/project" + String.Format( "/_api/web/GetFolderByServerRelativeUrl('{0}')/Files/Add(url='{1}', overwrite=true)", this.Config["TemplateLibrary"].Replace(" ", "%20"), formName + ".pdf"); ByteArrayContent imageBytes = new ByteArrayContent(docAsBytes); var result = await client.PostAsync(endpointUrl, imageBytes); //return result.Content.ToString(); } catch (Exception ex) { //return ex.ToString(); } return Ok(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/58327856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a running total grouped by a statement evaluation Using this article I have implemented a query that determines packing intervals for user events: http://www.itprotoday.com/microsoft-sql-server/new-solution-packing-intervals-problem I've ended up with following output: However, the bit I can't fathom out is how to group the packed intervals by userId for each date. Basically, I need a group column on the end which increments for each row when isStart is 1, but is output the same as the previous row's when isStart is null. Thus it should go: Row 1: 1 Row 2: 2 Row 3: 2 Row 4: 3 Row 5: 4 Row 6: 5 Row 7: 6 Row 8: 7 Row 9: 8 Row 10: 9 Row 11: 9 Row 12: 9 Row 13: 10 ... etc This then allows me to retrieve the min start and max end for each group. I'm sure this is really obvious but I can't seem to spot it! A: Just use a cumulative sum: select t.*, sum(isStart) over (order by start) as grp from t;
{ "language": "en", "url": "https://stackoverflow.com/questions/47551114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS - UILocalNotification - can schedule only up to 64 slots at a given time Overview * *I have an iOS app which sends local notifications at specific dates. *I just learned that I can only schedule 64 notifications at a given time. *There are cases when I can't schedule notifications as the 64 slots are filled. *So I store them in the database and when the user responds to a notification I check if there are any available slots and schedule the remaining notifications. Problem * *When the user doesn't respond to a notification my code is not executed so I am not able to schedule the remaining notifications. Question * *Is there a solution for this problem ? *can I execute a piece of code (house keeping) at certain times ? *is there any work around for this ? A: You may not want to signal to the user there is a problem, but rather just do it in the background. If a user has 64 notifications for one app and hasn't opened the app, then they probably aren't using the app. Once a notification has fired it isn't in the array anymore. So you will have room every time a notification is fired off. They do however remain in notification centre, which you have to clear out yourself. Its usually better to not present possible problems to the user, but rather handle them in a way that makes sense internally if that is an option. Look up the delegate methods for the appDelegate and you will most likely find ways you can handle what you are trying to do. Thought I would make a post in case you wanted to accept the answer. Best of luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/10576570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sampling and removing random elements from a list I have written a method which randomly samples a part of a list. The code is as follows: private List<String> selectImages(List<String> images, Random rand, int num) { List<String> copy = new LinkedList<String>(images); Collections.shuffle(copy,rand); return copy.subList(0, num); } The method takes as input the original list, the random number generator and the number of items to sample. Now I would like to remove the selected elements from the original list (called images). How can this be done? A: Using removeAll in the old list with the argument being your sub sample. private List<String> selectImages(List<String> images, Random rand, int num) { List<String> copy = new LinkedList<String>(images); Collections.shuffle(copy,rand); List<String> sample = copy.subList(0, num); images.removeAll(sample); return sample; }
{ "language": "en", "url": "https://stackoverflow.com/questions/46693619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: to compare two text files and output the difference in other file .txt I want to compare two text files and output the difference in other result.txt. I use this command in command prompt: findstr /vixg:Z:\misc\test1.txt Z:\misc\misc\test2.txt > Z:\misc\misc\result.txt But I have the file result.txt is the same of test2.txt.
{ "language": "en", "url": "https://stackoverflow.com/questions/42654699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: db connection deadlock We have a web application that has been running well for several years. The web application was using mysql, spring-1.2.6, and ibatis. After replacing spring-1.2.6 with spring-3.2.0, we started to notice a problem that multiple concurrent requests to a particular page always hang for some reason. jConsole shows the following for each concurrent thread: java.lang.Thread.State: WAITING on org.apache.commons.pool.impl.GenericObjectPool$Latch@b6b09e at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:485) at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1104) After investigation, we found that this problem has something to do with a resultMap that looks like the following. With spring-1.2.6, only one connection was needed for each thread regardless of the number of rows in the result set. However, with spring-3.2.0, N+1 connections (depending on the number of rows returned) are needed for each thread. Hence the deadlock. (We are using the default value (8) of maxActive property in our configuration.) How can I fix it so that connections are reused in this case? Thanks. <resultMap id="resultBlog" type="Blog"> <id property="id" column="idBlog" /> <result property="name" column="blogname" /> <result property="url" column="blogurl" /> <result property="author" column="idBlog" select="selectAuthor" /> </resultMap>
{ "language": "en", "url": "https://stackoverflow.com/questions/15993698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to type cast a literal in C I have a small sample function: #define VALUE 0 int test(unsigned char x) { if (x>=VALUE) return 0; else return 1; } My compiler warns me that the comparison (x>=VALUE) is true in all cases, which is right, because x is an unsigned character and VALUE is defined with the value 0. So I changed my code to: if ( ((signed int) x ) >= ((signed int) VALUE )) But the warning comes again. I tested it with three GCC versions (all versions > 4.0, sometimes you have to enable -Wextra). In the changed case, I have this explicit cast and it should be an signed int comparison. Why is it claiming, that the comparison is always true? A: x is an unsigned char, meaning it is between 0 and 256. Since an int is bigger than a char, casting unsigned char to signed int still retains the chars original value. Since this value is always >= 0, your if is always true. A: All the values of an unsigned char can fir perfectly in your int, so even with the cast you will never get a negative value. The cast you need is to signed char - however, in that case you should declare x as signed in the function signature. There is no point lying to the clients that you need an unsigned value while in fact you need a signed one. A: Even with the cast, the comparison is still true in all cases of defined behavior. The compiler still determines that (signed int)0 has the value 0, and still determines that (signed int)x) is non-negative if your program has defined behavior (casting from unsigned to signed is undefined if the value is out of range for the signed type). So the compiler continues warning because it continues to eliminate the else case altogether. Edit: To silence the warning, write your code as #define VALUE 0 int test(unsigned char x) { #if VALUE==0 return 1; #else return x>=VALUE; #endif } A: The #define of VALUE to 0 means that your function is reduced to this: int test(unsigned char x) { if (x>=0) return 0; else return 1; } Since x is always passed in as an unsigned char, then it will always have a value between 0 and 255 inclusive, regardless of whether you cast x or 0 to a signed int in the if statement. The compiler therefore warns you that x will always be greater than or equal to 0, and that the else clause can never be reached.
{ "language": "en", "url": "https://stackoverflow.com/questions/1362420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to remove the word "Data" at the top of Excel Pivot Table generated by C# with Interop.Excel? I have the following example raw data table: And hope to make the following Pivot Table using C# and the Microsoft.Office.Interop.Excel library: I have written the following code to generate both the original table and the pivot table: string fileTest = "test.xlsx"; Excel.Application app; Excel.Worksheet sheet; Excel.Workbook book; app = new Excel.Application(); book = app.Workbooks.Add(); sheet = (Excel.Worksheet)book.Worksheets.get_Item(1); sheet.Cells[1, 1] = "Name"; sheet.Cells[1, 2] = "Salary"; sheet.Cells[1, 3] = "Hours"; sheet.Cells[1, 4] = "Department"; sheet.Cells[2, 1] = "Bill"; sheet.Cells[2, 2] = 140000; sheet.Cells[2, 3] = 40; sheet.Cells[2, 4] = "IT"; sheet.Cells[3, 1] = "Ann"; sheet.Cells[3, 2] = 310000; sheet.Cells[3, 3] = 60; sheet.Cells[3, 4] = "Payroll"; sheet.Cells[4, 1] = "Bob"; sheet.Cells[4, 2] = 200000; sheet.Cells[4, 3] = 50; sheet.Cells[4, 4] = "IT"; sheet.Cells[5, 1] = "Sam"; sheet.Cells[5, 2] = 50000; sheet.Cells[5, 3] = 20; sheet.Cells[5, 4] = "Payroll"; Excel.Range range = sheet.Range["A1", "D5"]; Excel.Worksheet pivotSheet = (Excel.Worksheet)book.Worksheets.Add(); pivotSheet.Name = "Pivot Table"; Excel.Range range2 = pivotSheet.Cells[1, 1]; Excel.PivotCache pivotCache = (Excel.PivotCache)book.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, range); Excel.PivotTable pivotTable = (Excel.PivotTable)pivotSheet.PivotTables().Add(PivotCache: pivotCache, TableDestination: range2, TableName: "Summary"); Excel.PivotField pivotField = (Excel.PivotField)pivotTable.PivotFields("Salary"); pivotField.Orientation = Excel.XlPivotFieldOrientation.xlDataField; pivotField.Function = Excel.XlConsolidationFunction.xlSum; Excel.PivotField pivotField3 = (Excel.PivotField)pivotTable.PivotFields("Hours"); pivotField3.Orientation = Excel.XlPivotFieldOrientation.xlDataField; pivotField3.Function = Excel.XlConsolidationFunction.xlSum; Excel.PivotField pivotField2 = (Excel.PivotField)pivotTable.PivotFields("Department"); pivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField; Excel.PivotField dataField = pivotTable.DataPivotField; dataField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField; pivotTable.TableStyle2 = "PivotStyleLight16"; book.SaveAs(fileTest); book.Close(); app.Quit(); However, my Pivot Table has an extra row in the Pivot Table Header with the word "Data" in it: Is there a way I can remove this extra header? Thanks for any advice.
{ "language": "en", "url": "https://stackoverflow.com/questions/64200225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Formik component changing an uncontrolled input of type text to be controlled I am using Formik with an array, where the items are being passed from a parent and retrieved like this: updateState (){ this.state.choices = this.props.choices this.state.questionId = this.props.questionId } render() { this.updateState() var choices = this.state.choices console.log(choices) return ( ... I am originally initializing the values as empty or 0: constructor(props){ super(props); this.state = { choices : [], questionId: 0 }; } While this seems like it should work, I am getting the error that a component is changing an uncontrolled input of type text to be controlled. understand this is due to my use of this.state but I'm unsure how to actually fix this. What I have done so far, since I am using Formik, is change my export to look like this: export default withFormik({ mapPropsToValues: (props) => ({ choices: [{ id: '', value: '', weight: '', impact: ''}] }), })(Choices) It's unclear if I should be mapping props at all, or if I should be using something more like: export default withFormik({ mapPropsToValues: (props) => ({ id: '', value: '', weight: '', impact: '' }), })(Choices) All I know is that I am unable to click to push a new object onto the array that I am working with, so the functionality is basically frozen until I can figure out the state of the un/controlled input element. Any idea where I am going wrong? A: Fixing the HTML and the {choices[index].id} bits cleared this error. E.g.: <div className="col"> <label htmlFor={choices[index].id}>{choices[index].id}</label> <Field name={choices[index].id} placeholder={choices[index].value} type="text"/> <ErrorMessage name={choices[index].id} component="div" className="field-error" /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/53217463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can't see properties of viewcontoller I want to change the value of a label in my default view controller from a different class. * *So I start a simple 'Single View Application' iOS project (Xcode5) *This automatically generates a ViewController for me (which I understand is the root view controller) *I now add a label in my View and connect it to the ViewController (via IBOutlet mechanism) *I call this outlet 'gameStateLabel', so it looks like this in the ViewController.h file @property (weak, nonatomic) IBOutlet UILabel *gameStateLabel; Next, I have a completely separate class which has the logic for my code, and based on a condition in the logic I want to change the UIlabel. So I try to do this from my other class: * *Get an instance of the root view controller like this: UIViewController * uvc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; I think I now have an instance of the rootviewcontroller in uvc and should be able to reach in and change gameStateLabel. BUT: I CANNOT do this uvc.gameStateLabel simply does not show up as a property even though it is clearly declared as a property and I've added the @synthesize for it also. Any help will be greatly appreciated - I've been going nuts over this. (For ref. I'm used to doing something similar on the Mac side where I'd declare a label as a property of the AppDelegate, get the instance of the Appdelegate and simply refer to the label property and change its text] Here's the ViewController. Note that gameStateLable is a property #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UILabel *gameStateLabel; @end @implementation ViewController @synthesize gameStateLabel; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } And here is my class cls1 (which inherits from NSObject) #import "cls1.h" #import "ViewController.h" @implementation cls1 -(void) dummy{ UIViewController * uvc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; // uvc does NOT show gameStateLabel in intellisense, i.e. uvc.gameStateLabel does NOT work } A: Add #import "mainRootVC.h" in you CustomClass.m file And create object of mainRootVC such like, mainRootVC *obj = [[mainRootVC alloc] init]; // Now you can access your label by obj.gameStateLabel... A: Do like this... YourViewController *rootController =[(YourViewController*)[(YourAppDelegate*) [[UIApplication sharedApplication]delegate] window] rootViewController]; A: Try the following too: ViewController *controller = (ViewController*)self.window.rootViewController; It will return the initial view controller of the main storyboard. A: For sending information from a viewController to other viewController you have: * *Delegates:Definiton and examples *NSNotificationCenter: Apple Documentation NSString *label = @"label text"; [[NSNotificationCenter defaultCenter] postNotificationName:NAVIGATETO object:label userInfo:nil]; You can found tons of examples about those two. I recommend you use one of those. Hope this helps a bit. A: OK. I found two issues. * *I had copied the code over from my Mac project and modified it. Something seems to have gone wrong. I retyped the entire function and it solved most of the problem * *uvc should be of the type ViewController* - not UIViewController* as I was doing Thanks everyone for your replies - much appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/20609973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }