text
stringlengths
15
59.8k
meta
dict
Q: Web Scraping an Image I was thinking about the applications of web scraping (still quite new to it) and came up with a question. Can you get an image from a page if there are advertisements on the page (like can you avoid advertisements and only look for the correct image content on the page)? Also, if the image is also a link to another page, can you say go to the next page and get that image (and then go from there until you either reach a certain amount or get all of the images)? This would mean avoiding going to the advertisements pages. A: Absolutely. If you use a tool like kimonolabs.com this can be relatively easy. You click the data that you want on the page, so instead of getting all images including advertisements, Kimono uses the CSS selectors of the data you clicked to know which data to scrape. You can use Kimono to scrape data within links as well. It's actually a very common use. Here's a break-down of that strategy: https://help.kimonolabs.com/hc/en-us/articles/203438300-Source-URLs-to-crawl-from-another-kimono-API This might be a helpful solution for you, especially if you're not a programmer because it doesn't require coding experience. It's a pretty powerful tool. A: I think if you are ok with PHP programming then give a look into php simple html dome parser. I have used it a lot and scrapped number of websites.
{ "language": "en", "url": "https://stackoverflow.com/questions/28823008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setBackgroundResource on ImageView return null I'm using ListFragment in my android project. I decided to make a listView, each listview item consist of music frequency imageView. I will try to animate the imageView of music frequency. Each listView has a button called play, once the play is clicked, the music frequency start to animate. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragmentmusiclist, container, false); lv = (ListView) v.findViewById(R.id.list); mp = new MediaPlayer(); mp = null; Song s1 = new Song("Love Story",(float) 2.5, onMusicPlayListener); Song s2 = new Song("Sad Story",(float) 1.0, onMusicPlayListener); Song s3 = new Song("Breakup Story",(float) 3.5, onMusicPlayListener); songs = new ArrayList<Song>(); songs.add(s1); songs.add(s2); songs.add(s3); adapter = new MusicListAdapter(getActivity(),songs); setListAdapter(adapter); return super.onCreateView(inflater, container, savedInstanceState); } OnClickListener onMusicPlayListener = new OnClickListener() { @Override public void onClick(View v) { final int position = getListView().getPositionForView((LinearLayout)v.getParent()); animMusicFreq = (ImageView) v.findViewById(R.id.music_anim); animMusicFreq.setBackgroundResource(R.anim.anim_music); animMusicFreq.post(new Runnable() { @Override public void run() { AnimationDrawable frameAnimation = (AnimationDrawable) animMusicFreq.getBackground(); frameAnimation.start(); } }); A: You are inflating your view inside onCreateView, but you don't pass it to the system. Instead you tell it to inflate its own (you return super). It doesn't make any sense. You should return your v view like so: public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragmentmusiclist, container, false); // ... return v; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25591514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight Multithreading; Need to Synchronize? I have a Silverlight app where I've implemented the M-V-VM pattern so my actual UI elements (Views) are separated from the data (Models). Anyways, at one point after the user has gone and done some selections and possible other input, I'd like to asyncronously go though the model and scan it and compile a list of optiions that the user has changed (different from the default), and eventually update that on the UI as a summary, but that would be a final step. My question is that if I use a background worker to do this, up until I actually want to do the UI updates, I just want to read current values in one of my models, I don't have to synchronize access to the model right? I'm not modifying data just reading current values... There are Lists (ObservableCollections), so I will have to call methods of those collections like "_ABCCollection.GetSelectedItems()" but again I'm just reading, I'm not making changes. Since they are not primitives, will I have to synchronize access to them for just reads, or does that not matter? I assume I'll have to sychronize my final step as it will cause PropertyChanged events to fire and eventually the Views will request the new data through the bindings... Thanks in advance for any and all advice. A: You are correct. You can read from your Model objects and ObservableCollections on a worker thread without having a cross-thread violation. Getting or setting the value of a property on a UI element (more specifically, an object that derives from DispatcherObject) must be done on the UI thread (more specifically, the thread on which the DispatcherObject subclass instance was created). For more info about this, see here.
{ "language": "en", "url": "https://stackoverflow.com/questions/5746024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the background color for specified row in datagridview? I want to set the background color for specified Row in datagridview .. My need is i have a for loop (i=0;i<10;i++) .Inside this for loop i write the logic as if(i=1) { //Want to Set Color For This Specified Row.. dataGridView1.SelectedRows[1].DefaultCellStyle.SelectionBackColor = Color.Yellow; } if(i=1) { //Want to Set Color For This Specified Row.. dataGridView1.SelectedRows[2].DefaultCellStyle.SelectionBackColor = Color.Blue; } if(i=1) { //Want to Set Color For This Specified Row.. dataGridView1.SelectedRows[3].DefaultCellStyle.SelectionBackColor = Color.Red; } But i didn't get the expected o/p . I hope U understand My need . Please Help Me. A: Instead of using SelectedRows property of the DataGridview you can use as follows dataGridView1.Rows[1].DefaultCellStyle.ForeColor = Color.Red; Because SelectedRows property will return rows when row(s) has been selected by the User only, if no rows are selected then your code will throw exception. EDIT : For your doubt here am providing a sample code, hope it will help you. for (int i = 0; i < 10; i++) { if (dataGridView1.Rows.Count > i) { if (i == 1) dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Red; else if (i == 2) dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Blue; else dataGridView1.Rows[i].DefaultCellStyle.ForeColor = Color.Green; } } A: You may handle different events of your datagrid and set cell style Here is example from related question private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex != color.Index) return; e.CellStyle.BackColor = Color.Red; }
{ "language": "en", "url": "https://stackoverflow.com/questions/27525077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Spring Boot Mail send email using acces token I have simple mail sending functionality in project which configured in one bean. @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); Properties properties = new Properties(); properties.setProperty("mail.smtp.auth", "false"); properties.setProperty("mail.smtp.socketFactory.port", "465"); properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.starttls.required", "true"); javaMailSender.setHost("smtp.gmail.com"); javaMailSender.setProtocol("smtp"); javaMailSender.setUsername("username"); javaMailSender.setPassword("password"); javaMailSender.setJavaMailProperties(properties); return javaMailSender; } and it works great. Now I want to add functionality for sending emails via accessToken/refreshToken of specific email. How to do it? What should I extend in my bean or add another bean for sending with token? I couldn't find some example which is full explained. As I understand I should add setFrom() and in setPassword() put accessToken A: The use of OAUTH2 with JavaMail is explained on the JavaMail project page. Also, you should fix these common mistakes in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/53376248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rxjs synchronous? I recently started working on a new project and I have seen this twice now, am I crazy or will never work under any circumstance? protected get reportView(): any { let convertedView = null; this.store .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1)) .subscribe((convertedOrder) => (convertedView = convertedOrder)); return convertedView; } A: am I crazy or will never work under any circumstance? Q) Are you crazy? A) Yes. Absolutely. That looks bonkers! Q) Will this never work under any circumstance? A) Oh, there are times this will work. Some observables are synchronous. For example, this will always log a 2, so this works as expected. let convertedView = null; of(1).pipe( map(v => v + 1) ).subscribe(convertedOrder => convertedView = convertedOrder); console.log(convertedView); That's because of(1) is a synchronous observable. This, however, will never work let convertedView = null; of(1).pipe( delay(0), map(v => v + 1) ).subscribe(convertedOrder => convertedView = convertedOrder); console.log(convertedView); This will print null. Even though delay(0) conceptually takes no time, it still uses JSs event loop and therefore doesn't get executed until the current code completes. I think it's best practise to assume all observables are asynchronous. Any code that assume otherwise is likely to be brittle. A: Your store.subscribe is asynchronous and the rest of your code is not. You can resolve it with a Promise like the example below. protected get reportView(): Promise < any > { return new Promise((resolve, reject) => { this.store .pipe(select(fromStore.getTransferOrderConverted), rxjs.take(1)) .subscribe((convertedOrder) => resolve(convertedOrder)); }); } reportView.then(convertedOrder => { // do your stuff }); Also you can get the convertedOrder with Async/Await. But remember, the parent function must be async. const convertedOrder = await reportView(); A: Convert a stream to synchronous isn't a good ideal. However, you can use method toPromise of a subject (subscription) for convert it to a promise and await for resolve. A: Rxjs take(1), first() operator should work absolutely fine These 2 operators takes the latest value from store selector or BehaviourSubject in synchronous way.
{ "language": "en", "url": "https://stackoverflow.com/questions/68402420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java.util.NoSuchElementException when run with Semaphore I have a Queue containing 10 elements, and I start 100 threads of which 6 may run concurrently, controlled by a Semaphore. When each thread runs, it takes the head element then adds it to the tail. But sometimes I get this exception: java.util.NoSuchElementException at java.util.LinkedList.removeFirst(LinkedList.java:270) at java.util.LinkedList.remove(LinkedList.java:685) at IBM.SemApp$1.run(SemApp.java:27) at java.lang.Thread.run(Thread.java:745) import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.concurrent.Semaphore; public class SemApp { public static void main(String[] args) { Queue queueB = new LinkedList<>(); for (int i = 0; i < 10; i++) { queueB.add("Object " + i); } Runnable limitedCall = new Runnable() { final Random rand = new Random(); final Semaphore available = new Semaphore(6); int count = 0; public void run() { int time = rand.nextInt(15); try { available.acquire(); String A = (String) queueB.remove(); queueB.add(A); available.release(); count++; System.out.println(count); } catch (InterruptedException e) { e.printStackTrace(); } } }; for (int i = 0; i < 100; i++) { new Thread(limitedCall).start(); } } } What am I doing wrong? A: The problem is that LinkedList is not a thread-safe structure. Therefore, it should not be shared and modified by multiple concurrent threads as the changes on queueB might not be properly "communicated" to other threads. Try using a LinkedBlockingQueue instead. Also, use an AtomicLong for count for the same reason: it is shared in between several threads and you want to avoid race conditions. A: The fact that up to six threads may be operating on the queue concurrently means that modifications are not safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/31881642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass context to AdMob InterstitialAd in LibGDX Does smb knows how to pass a context to InterstitialAd in LibGDX? In Android it is simply InterstitialAd interstitial = new InterstitialAd(this); My class extended from Screen. or I can intialize it in class extended Game.. Or how to pass the context in this case? And if smb knows any problem related to this, I'll be very thankfull to any advice! A: To show ads from inside other classes not from the main activity you need to use a facade. Basically, you make use of a listener to load/display the ads. Follow this libgdx official tutorial guide. It covers both banner and interstitial ads and it isn't outdated. It uses the new admob via the google play services
{ "language": "en", "url": "https://stackoverflow.com/questions/26512198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best variable scope I should use in servlet operation I am working on workflow management system. Have one separate java class which contains logic method. One of this is: public static in get_nxt_stg(int current_stg,int action) { } and define static variable cur_stg and nxt_stg. used in servlet. call this method. When multiple users log in and do some action these variables get not proper value. It seems like it is shared between all user requests. What is best way to use variable in servlet, which is remain specific for that request? A: You should not use static in such a way. If you need to share state, consider using the singleton pattern; but try to avoid static. Unwise use of "static" can turn into a nightmare (for example regarding unit testing). In addition: it seems that you are a beginner with the Java language. But creating servlets is definitely a "advanced" java topic. I really recommend you to start learning more about Java as preparation for working on servlets. Otherwise the user of your server might have many unpleasant experiences ... A: What you are doing is wrong. You should use Servlets only for the purpose of reading request parameters and sending responses. What you are trying to do, should be implemented in the Business layer of your application and if you have it implemented with EJBs, then your problem can easily be solved with an Stateful EJB.
{ "language": "en", "url": "https://stackoverflow.com/questions/29295212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load XML into mxml (Flex AS3) I am trying to display content of an xml file in a textarea (using Flex 4.7). But I am getting errors and I am not sure why. This is my code: <?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ var xmlLoader:URLLoader = new URLLoader(); xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here xmlLoader.load(new URLRequest("books.xml")); // 2nd error here var xmlData:XML = new XML(); function loadXML(e:Event):void{ xmlData = new XML (e.target.data); } ]]> </fx:Script> <s:VGroup> <s:TextArea id="txtArea"> </s:TextArea> </s:VGroup> </s:WindowedApplication> Here are my errors: Multiple markets at this line: -1120: Access of undefined propertyloadXML (1st error) -1120: Access of undefined property xmlLoader (2nd error) This is the app structure: Tester - src -- (default package) --- Tester.mxml -- books.xml -- Tester-app.xml I am not sure what I am doing wrong. Could anyone please get me on the right track? Thank you! A: Most of your ActionScript code must go inside a method; and you have code that must be put in a method. Variable definitions are okay. Import statements are okay. I think some directives, such as include are okay. But, other code must be in a method. This is your annotated code: <fx:Script> <![CDATA[ // this is a variable definition so it is good var xmlLoader:URLLoader = new URLLoader(); // these two lines are code that executes; so they must be put inside a method; something you did not do. Comment them out //xmlLoader.addEventListener(Event.COMPLETE, loadXML); // 1st error here //xmlLoader.load(new URLRequest("books.xml")); // 2nd error here // this is a variable definition so it is okay var xmlData:XML = new XML(); // this is a function definition so it is okay function loadXML(e:Event):void{ xmlData = new XML (e.target.data); } // move your executing code into a method public function load():void{ xmlLoader.addEventListener(Event.COMPLETE, loadXML); xmlLoader.load(new URLRequest("books.xml")); } ]]> </fx:Script> I bet that removes your errors. However, you'll also want to / need to do something to execute that load method. When you do this depends on how the data is used in your app and the current component. But, I'd probably add a preinitialize event listener: <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" preinitialize="load()"> If preinitialize doesn't work; I'd move the code to the initialize event. If that doesn't work; I'd go to the creationComplete event.
{ "language": "en", "url": "https://stackoverflow.com/questions/16995286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where is the tail position in my Clojure loop? Clojure is saying that I can't call recur from a non-tail-position. Is this not the tail position? What is the tail position in my loop then? (loop [i 20] (for [x (range 1 21)] (if (zero? (rem i x)) i (recur (+ i 1))))) A: for does not do what you think it does; it is not an imperative loop. It is a list comprehension, or sequence-generator. Therefore, there is not a return or iterate call at its end, so you cannot place recur there. It would seem you probably do not need either loop or recur in this expression at all; the for is all you need to build a sequence, but it's not clear to me exactly what sequence you wish to build. A: Further to @JohnBaker's answer, any recur refers to the (nearest) enclosing loop or fn (which may be dressed as a letfn or a defn). There is no such thing in your snippet. So there is nothing for the recur to be in tail position to. But just replace the for with loop, and you get (loop [i 20] (loop [x 1] (if (zero? (rem i x)) i (recur (+ i 1))))) ... which evaluates to 20,no doubt what you intended. However, the outer loop is never recurred to, so might at well be a let: (let [i 20] (loop [x 1] (if (zero? (rem i x)) i (recur (+ i 1))))) The recur is in tail position because there is nothing left to do in that control path through the loop form: the recur form is the returned value. Both arms of an if have their own tail position. There are some other disguised ifs that have their own tail position: ors and ands are such.
{ "language": "en", "url": "https://stackoverflow.com/questions/36434246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I zero pad a 4 character string in C# I am using the following class method to create a Base36 string from a number: private const string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static String Encode(long input) { if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative"); char[] clistarr = CharList.ToCharArray(); var result = new Stack<char>(); while (input != 0) { result.Push(clistarr[input % 36]); input /= 36; } return new string(result.ToArray()); } One of the requirements is that the string should always be padded with zero's and should be a maximum of four digits. Can anyone suggest a way that I can code the leading zero's and also limit the function so it will never return more than "ZZZZ" ? Is there some function in C# that can do this. Sorry about the indentation on this code. I am not sure why it's not indenting properly. A: ZZZZ in base 36 is 1679615 in base 10 (36^4 - 1). So you can simply test if the number is greater than this and reject it. To pad you can use String.PadLeft. A: If there are always going to be exactly four digits, it's really easy: const long MaxBase36Value = (36L * 36L * 36L * 36L) - 1L; public static string EncodeBase36(long input) { if (input < 0L || input > MaxBase36Value) { throw new ArgumentOutOfRangeException(); } char[] chars = new char[4]; chars[3] = CharList[(int) (input % 36)]; chars[2] = CharList[(int) ((input / 36) % 36)]; chars[1] = CharList[(int) ((input / (36 * 36)) % 36)]; chars[0] = CharList[(int) ((input / (36 * 36 * 36)) % 36)]; return new string(chars); } Or using a loop: const long MaxBase36Value = (36L * 36L * 36L * 36L) - 1L; public static string EncodeBase36(long input) { if (input < 0L || input > MaxBase36Value) { throw new ArgumentOutOfRangeException(); } char[] chars = new char[4]; for (int i = 3; i >= 0; i--) { chars[i] = CharList[(int) (input % 36)]; input = input / 36; } return new string(chars); }
{ "language": "en", "url": "https://stackoverflow.com/questions/8336981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Protractor test picking up edge browser instead of chrome after reboot I was trying to get a server installed with headless chrome, selenium webdriver and protractor for automating tests. I setup my environment with these instructions: # JDK 8 sudo add-apt-repository ppa:openjdk-r/ppa sudo apt-get update && sudo apt-get install openjdk-8-jdk # Node JS curl -sL https://deb.nodesource.com/setup_6.x | sudo bash - sudo apt-get install -y nodejs # NPM modules sudo npm install protractor -g sudo npm install chromedriver -g # Google Chrome echo "deb http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee -a /etc/apt/sources.list wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - sudo apt-get update sudo apt-get -y install libxpm4 libxrender1 libgtk2.0-0 libnss3 libgconf-2-4 sudo apt-get -y install google-chrome-stable sudo apt-get -y install xvfb gtk2-engines-pixbuf sudo apt-get -y install xfonts-cyrillic xfonts-100dpi xfonts-75dpi xfonts-base xfonts-scalable sudo apt-get -y install imagemagick x11-apps Xvfb -ac :99 -screen 0 1280x1024x16 & disown $1 export DISPLAY=:99 The issue is that when I run my protractor test for the first time, it works great and the tests run perfectly. But when there is a server reboot or something, I cant seem to run it again. Now this is because when I am do a webdriver-manager start, this is my output: yeshwanthvshenoy@node-3:~$ sudo webdriver-manager start [02:59:54] I/start - java -Djava.security.egd=file:///dev/./urandom -Dwebdriver.chrome.driver=/usr/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.29 -Dwebdriver.gecko.driver=/usr/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/geckodriver-v0.16.1 -jar /usr/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.4.0.jar -port 4444 [02:59:54] I/start - seleniumProcess.pid: 2239 02:59:54.729 INFO - Selenium build info: version: '3.4.0', revision: 'unknown' 02:59:54.730 INFO - Launching a standalone Selenium Server 2017-06-07 02:59:54.758:INFO::main: Logging initialized @329ms to org.seleniumhq.jetty9.util.log.StdErrLog 02:59:54.832 INFO - Driver provider org.openqa.selenium.ie.InternetExplorerDriver registration is skipped: registration capabilities Capabilities [{ensureCleanSession=true, browserName=internet explorer, version=, platform=WINDOWS}] does not match the current platform LINUX 02:59:54.833 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver registration is skipped: registration capabilities Capabilities [{browserName=MicrosoftEdge, version=, platform=WINDOWS}] does not match the current platform LINUX 02:59:54.833 INFO - Driver class not found: com.opera.core.systems.OperaDriver 02:59:54.833 INFO - Driver provider com.opera.core.systems.OperaDriver registration is skipped: Unable to create new instances on this machine. 02:59:54.837 INFO - Driver class not found: com.opera.core.systems.OperaDriver 02:59:54.837 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered 02:59:54.842 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped: registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform LINUX 2017-06-07 02:59:54.892:INFO:osjs.Server:main: jetty-9.4.3.v20170317 2017-06-07 02:59:54.942:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@523884b2{/,null,AVAILABLE} 2017-06-07 02:59:54.968:INFO:osjs.AbstractConnector:main: Started ServerConnector@2d653761{HTTP/1.1,[http/1.1]}{0.0.0.0:4444} 2017-06-07 02:59:54.969:INFO:osjs.Server:main: Started @541ms 02:59:54.969 INFO - Selenium Server is up and running As you can see, it shows the edge browser instead of chrome. Why is that it is being switched back? Is there a way to store this permanently or should I do some other command to specify that I need to use chrome? A: I see that IE, Edge, Safari, and Opera are skipped (which is to be expected). After starting the WebDriver manager, go to http://localhost:4444/grid/console and check what has been registered. Check out Setting Up the Browser for Protractor.
{ "language": "en", "url": "https://stackoverflow.com/questions/44402817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Use of XML / XML Attributes in Flex I am new to XML and XML attributes. I have read in some XML documentation that XML can be represented in 2 ways: Method-1 <?xml version="1.0" encoding="UTF-8"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>USA</COUNTRY> <COMPANY>Columbia</COMPANY> <PRICE>10.90</PRICE> <YEAR>1985</YEAR> </CD> <CD> <TITLE>Hide your heart</TITLE> <ARTIST>Bonnie Tyler</ARTIST> <COUNTRY>UK</COUNTRY> <COMPANY>CBS Records</COMPANY> <PRICE>8.90</PRICE> <YEAR>1988</YEAR> </CD> </CATALOG> Method - 2 <?xml version="1.0" encoding="UTF-8"?> <CATALOG> <CD TITLE="Empire Burlesque" ARTIST="Bob Dylan" COUNTRY="USA" COMPANY="Columbia" PRICE="10.90" YEAR="1985"/> <CD TITLE="Hide your heart" ARTIST="Bonnie Tyler" COUNTRY="UK" COMPANY="CBS Records" PRICE="8.90" YEAR="1988"/> </CATALOG> But for example when I am using this function to filter where price >=9 and display the data in a grid. When using XML Way 1, it works fine, but when I use XML Way 2, the datagrid is empty. Also note that I am using @ Binding at the datafield of each DatagridColumn. My filter function is as such: private function myFilter(xml:XML):Boolean { return Number(xml.PRICE) >= 9; } Thanks A: In way number 2, the price is an atribute and not a subtag so it should be accessed with the @ symobl. So for way 2, your filter function should be: private function myFilter(xml:XML):Boolean { return Number(xml.@PRICE) >= 9; } Notice the @ before PRICE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7201376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create SQL query for the following tables A database is composed of 4 tables: Table1, table2, table3 and table4. For a given query Q. If Q = Name_1. I want to select all the fields in tables 1, 2, 3 and 4 and save them in an array using python. create Tables: Create Table table1 (ID1 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100)); Create table table2 (ID2 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1)); Create table table3 (ID3 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1)); Create table table4 (ID4 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T2 INT, Foreign Key(ID_T2) references table2(ID2)); Insert Data in tables: insert into table1 (ID1,NAME) values ("1", "john"); insert into table2 (ID2,NAME,ID_T1) values ("1", "math","1"); insert into table3 (ID3,NAME,ID_T1) values ("1", "physics","1"); insert into table4 (ID4,NAME,ID_T2) values ("1", "friend of","1"); A: Here is the query: SELECT * FROM Table1 AS t1 JOIN table3 as t3 ON t1.ID_table1 = t3.ID_table1 JOIN table2 as t2 ON t1.ID_table1 = t2.ID_table1 JOIN table4 as t4 ON t2.ID_table2 = t4.ID_table2
{ "language": "en", "url": "https://stackoverflow.com/questions/28604514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sticky section using "position: sticky;" css? * *I try to sticky full section using css but i cant sticky section *when i try with div it's working fine but when i try with section it's not working. *I try to sticky pizza section. i already sticky inner div but not sticky full section. Please view in full screen. * *I try to sticky full section using css but i cant sticky section *when i try with div it's working fine but when i try with section it's not working. *I try to sticky pizza section. i already sticky inner div but not sticky full section. Here is my code $(document).ready(function(){ // Add smooth scrolling to all links $("a").on('click', function(event) { // Make sure this.hash has a value before overriding default behavior if (this.hash !== "") { // Prevent default anchor click behavior event.preventDefault(); // Store hash var hash = this.hash; // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top }, 600, function(){ // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } // End if }); }); $(window).scroll(function() { var scrollDistance = $(window).scrollTop(); // Show/hide menu on scroll //if (scrollDistance >= 850) { // $('nav').fadeIn("fast"); //} else { // $('nav').fadeOut("fast"); //} // Assign active class to nav links while scolling $('.page-section').each(function(i) { if ($(this).position().top <= scrollDistance) { $('.navigation a.active').removeClass('active'); $('.navigation a').eq(i).addClass('active'); } }); }).scroll(); .page-section { height: 480px; width: 100%; padding: 3em; background: linear-gradient(45deg, #43cea2 10%, #185a9d 90%); color: white; box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.5); } .navigation { position: sticky; width: 100%; top: 0px; background-color: #999; color: #fff; } .all-menu-item{ position: sticky; width: 100%; top: 0px; } .navigation__link { display: block; color: #ddd; text-decoration: none; padding: 1em; font-weight: 400; } .navigation__link:hover { background-color: #aaa; } .navigation__link.active { color: white; background-color: rgba(0, 0, 0, 0.1); } .menu-title{ position: sticky; top: 0px; padding: 20px; background: #fff; } .menu-fix{ position: sticky; top: 0px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/> <section class="w-100 float-left"> <div class="container"> <div class="row"> <div class="col-12 py-4"> <h2>Content...</h2> <h5>Scroll down to see the Navbar stick</h5> <p>Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics, raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation. Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.</p> <hr> <p>Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies, forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.</p> <hr> <p>Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies, forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.</p> <hr> </div> </div> </div> </section> <section class="menu-fix w-100 float-left"> <h3>Pizza section</h3> <div class="container"> <div class="row"> <div class="col-lg-4"> <nav class="navigation" id="mainNav"> <a class="navigation__link" href="#1">Section 1</a> <a class="navigation__link" href="#2">Section 2</a> <a class="navigation__link" href="#3">Section 3</a> <a class="navigation__link" href="#4">Section 4</a> <a class="navigation__link" href="#5">Section 5</a> <a class="navigation__link" href="#6">Section 6</a> <a class="navigation__link" href="#7">Section 7</a> </nav> </div> <div class="col-lg-8"> <div class="all-menu-item"> <h2 class="menu-title">Pizza</h2> <div class="page-section hero" id="1"> <h1>Smooth scroll, fixed jump menu with active class</h1> </div> <div class="page-section" id="2"> <h1>Section Two</h1> </div> <div class="page-section" id="3"> <h1>Section Three</h1> </div> <div class="page-section" id="4"> <h1>Section Four</h1> </div> <div class="page-section" id="5"> <h1>Section Five</h1> </div> <div class="page-section" id="6"> <h1>Section Six</h1> </div> <div class="page-section" id="7"> <h1>Section Seven</h1> </div> </div> </div> </div> </div> </section> <section class="w-100 float-left"> <div class="container"> <div class="row"> <div class="col-12 py-4"> <h2>Content...</h2> <h5>Scroll down to see the Navbar stick</h5> <p>Sriracha biodiesel taxidermy organic post-ironic, Intelligentsia salvia mustache 90's code editing brunch. Butcher polaroid VHS art party, hashtag Brooklyn deep v PBR narwhal sustainable mixtape swag wolf squid tote bag. Tote bag cronut semiotics, raw denim deep v taxidermy messenger bag. Tofu YOLO Etsy, direct trade ethical Odd Future jean shorts paleo. Forage Shoreditch tousled aesthetic irony, street art organic Bushwick artisan cliche semiotics ugh synth chillwave meditation. Shabby chic lomo plaid vinyl chambray Vice. Vice sustainable cardigan, Williamsburg master cleanse hella DIY 90's blog.</p> <hr> <p>Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies, forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.</p> <hr> <p>Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies, forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.</p> <hr> <p>Ethical Kickstarter PBR asymmetrical lo-fi. Dreamcatcher street art Carles, stumptown gluten-free Kickstarter artisan Wes Anderson wolf pug. Godard sustainable you probably haven't heard of them, vegan farm-to-table Williamsburg slow-carb readymade disrupt deep v. Meggings seitan Wes Anderson semiotics, cliche American Apparel whatever. Helvetica cray plaid, vegan brunch Banksy leggings +1 direct trade. Wayfarers codeply PBR selfies. Banh mi McSweeney's Shoreditch selfies, forage fingerstache food truck occupy YOLO Pitchfork fixie iPhone fanny pack art party Portland.</p> <hr> </div> </div> </div> </section> A: add position: relative to parent element .parent{ position: relative; } .child{ position: sticky; top: 0 }
{ "language": "en", "url": "https://stackoverflow.com/questions/63407449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Printing PDF files using VBS I am new to coding with VBS. This is my unfinished code to print documents in a folder containing documents with 3 distinct headers, "DN" "INV" and "PO". I've been searching around for the code/method to print out PDF documents. I tried using the invokeverb "&print" function but it doesn't seem to work. Can someone please teach me how to print it out? Thank you very much :) "DN" needs to printed out once, " INV" needs to be printed out 6 times, "PO" needs to be printed out 2 times. P.S. Thank you @kajkrow for solving this same problem using VBA. Reposting as I found out I was using VBS. Previous question can be found here. *EDIT : attached link solves my problem in both VBA and VBS and uses InvokeVerbEx to print files. '' To set the path to the current folder set shApp = CreateObject("shell.application") currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".") set shFolder = shApp.NameSpace( currentPath ) '' To set the items in the current folder as "files" set files = shFolder.Items() ''Start of code'' 'msgbox("Starting Script") for each files in files ' If name contains "DN" ' if inStr(files, "DN") then 'print out 1 time' end if ' if name contains "INV" ' if inStr(files, "INV") then 'print out 6 times' end if ' if name contains "PO" ' if inStr(files, "PO") then 'print out 2 times' end if next MsgBox("completed") A: According to documentation (https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf) you could send a command to print a file, but there is no parameter for the number of copies. You can display and print a PDF file with Acrobat and Adobe Reader from the command line. These commands are unsupported, but have worked for some developers. There is no documentation for these commands other than what is listed below. Note: All examples below use Adobe Reader, but apply to Acrobat as well. If you are using Acrobat, substitute Acrobat.exe in place of AcroRd32.exe on the command line. AcroRd32.exe pathname — Start Adobe Reader and display the file. The full path must be provided. This command can accept the following options. /n Start a separate instance of Acrobat or Adobe Reader, even if one is currently open. /s Suppress the splash screen. /o Suppress the open file dialog box. /h Start Acrobat or Adobe Reader in a minimized window. AcroRd32.exe /p pathname — Start Adobe Reader and display the Print dialog box. AcroRd32.exe /t path "printername" "drivername" "portname" — Start Adobe Reader and print a file while suppressing the Print dialog box. The path must be fully specified. The four parameters of the /t option evaluate to path, printername, drivername, and portname (all strings). printername — The name of your printer. drivername — Your printer driver’s name, as it appears in your printer’s properties. portname — The printer’s port. portname cannot contain any "/" characters; if it does, output is routed to the default port for that printer For multiple copies of each pdf, you could use a loop. Something like this: set shApp = CreateObject("shell.application") currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".") set shFolder = shApp.NameSpace( currentPath ) set files = shFolder.Items() set oWsh = CreateObject ("Wscript.Shell") dn = 1 inv = 6 po = 2 for each files in files msgbox(files) if inStr(files, "DN") then for x = 1 to dn oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true next end if if inStr(files, "INV") then for x = 1 to inv oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true next end if if inStr(files, "PO") then for x = 1 to po oWsh.run """AcroRd32.exe"" /t /n /h /o /s" &files,,true next end if next MsgBox("completed") Note: tested only with XPS Document writer
{ "language": "en", "url": "https://stackoverflow.com/questions/50920097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I reset a ComboBox when the underlying list changes? I'm currently working on a WinForms graphical interface in C#. The form has a ComboBox that is displaying the contents of a custom class I wrote. This class implements the IList interface so that it can be used as the DataSource for that ComboBox. The issue is that when I add or remove items to/from the underlying object, the ComboBox does not visually reflect this. I have tried reassigning the list to the DataSource property whenever the contents change, but that doesn't seem to make a difference. Most of the answers on this site that deal with this issue or similar seem to require a number of extra classes, or editing XAML documents, in order to achieve this. Is there a simpler method to achieving this? If it makes a difference, the ComboBox will not be visible at the point where changes are made to the IList sourcing it. The only idea I've had so far is to possibly delete the ComboBox and replace it with a new one when needed, but I'm not sure if this is possible to do at runtime, and is obviously not very elegant either way.
{ "language": "en", "url": "https://stackoverflow.com/questions/43918972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Override PLIST file for iOS builds using VS2015 TACO to work around CB-10493 [iOS] Missing icon.png I am using VS2015 TACO to build a cordova application using Cordova 6.0 and Cordova-ios 4.0.1. There is a registered issue CB-10493 [iOS] Missing icon.png https://issues.apache.org/jira/browse/CB-10493 The work around for the issue requires you to update the PLIST file to remove a particular keyed entry from the PLIST file. Unfortunately, because of the way that VS2015 TACO rebuilds the Cordova project on build, any manual edits to the files in the platforms folder is overwritten. Directions on how to update the file was discussed here: https://taco.visualstudio.com/en-us/docs/configure-app/#VisualAssets However upon putting the file in place, it seems to be ignored. I copied the PLIST file in the platforms folder to: res/native/ios/myapp/myapp-Info.plist and removed the requisite entries. I then removed the platforms folder and rebuilt the application. This made no impact on the contents of the PLIST file in the platforms folder. I could rollback versions for Cordova, however as this would involve also rolling back a number of plugins with fixes that I want to keep, I would prefer not to do this. I would really appreciate if I could get clear working directions on how to implement an effective work-around to removing the offending entries from the PLIST file within a VS2015 TACO project. Thanks in advance. A: Okay - discovered that despite the fact that the PLIST file in the platforms folder is not being overwritten, the use of a PLIST file in the native folder is still effective in working around the issue. Discovered this when syntax errors entered my file and my build broke, despite the platforms copy of the PLIST still being exactly the same as the original.
{ "language": "en", "url": "https://stackoverflow.com/questions/35546943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compile errors after adding V8 to my project (C2143, C2059, ..) i've recently added Google's V8 to a MSVC2005 project which is also using Qt and i haven't been able to compile it since. The defines are giving me a lot of problems, for example in V8's token.h there is #define T(name, string, precedence) name, enum Value { TOKEN_LIST(T, T) NUM_TOKENS }; The line TOKEN_LIST(T, T) yields an error C2143 ('}' missing before '{'), also error C2059 (syntax error '{'), also C2334 (token before '{'; visible function text is skipped). This repeats itself a couple of times. I have searched through SO and through Microsoft's database and tested various things, for example using /clr, which broke Qt. I also used #undef before including the "v8.h" file for possibly existing definitions to be removed. Can anyone help with this? Is there a standard procedure to fix errors like this? Thanks. A: You can find the conflicting macro definitions by searching for differences between the preprocessed code generated for token.h with and without the #include <windows.h>. For example, for "token.h", the errors occur at the definition of the enum Value so you have to look at the preprocessed definition of that enum in both cases. So with #include <windows.h> #include <token.h> you get: enum Value { ... INSTANCEOF, , NOT, BIT_NOT, (0x00010000L), TYPEOF, void, BREAK, ... SWITCH, void, THROW, ... FUTURE_STRICT_RESERVED_WORD, const, EXPORT, ... }; instead of: enum Value { ... INSTANCEOF, IN, NOT, BIT_NOT, DELETE, TYPEOF, VOID, BREAK, ... SWITCH, THIS, THROW, ... FUTURE_STRICT_RESERVED_WORD, CONST, EXPORT, ... }; with only #include <token.h>.
{ "language": "en", "url": "https://stackoverflow.com/questions/9567868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Logical Error with PHP! A password length check I am getting a logical error I believe I am using PHP as my server side language and I am performing password checks. Users will not be allowed to enter a password less than 8 characters and no more than 32 characters. register.php <?php $pageTitle = "Register"; ?> <?php $sectoin = "signing"; ?> <?php include 'INC/header.php'; ?> <?php $submit = $_POST['submit']; $username = strip_tags($_POST['username']); $password = strip_tags($_POST['password']); $repeatPassword = strip_tags($_POST['repeatPassword']); $email = strip_tags($_POST['email']); $date = date("m-d-Y"); if ($submit) { // Checking for exsistence if ($username && $password && repeatPassword && $email) { // Encrypts the Pasword $password = md5($password); $repeatPassword = md5($repeatPassword); // Do Passwords Match if ($password == $repeatPassword) { // Check Character Length of Username if (strlen($username) > 16 || strlen($username) <= 2) { echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Username</b> must be between 3 and 16 characters! </h3> </span>"; } else { // Check Password Length if (strlen($password && $repeatPassword) < 8) { echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Password</b> is less than 8 characters! </h3> </span>"; } else { echo 'Registration Completed!'; } } } else echo "<h3 class='text-center'> <span class='alert alert-danger'> Your <b>Passwords</b> must match! </h3> </span>"; } else echo "<h3 class='text-center'> <span class='alert alert-warning'> Please fill out <b>All</b> fields!</h3> </span>"; } ?> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-body"> <div class="page-header"> <h3 class="text-center"> Registration </h3> </div> <form class="form-horizontal" role="form" action="register.php" method="POST"> <!--Start of Username--> <div class="form-group"> <label for="username" class="col-sm-2 control-label"> Username </label> <div class="col-sm-10"> <div class="input-group"> <span class="input-group-addon"> <span class="glyphicon glyphicon-user"> </span> </span> <input type="text" name="username" class="form-control" id="username" placeholder="Username" /> </div> </div> </div> <!--End of Username--> <!--Start of E-Mail--> <div class="form-group"> <label for="email" class="col-sm-2 control-label"> E-Mail </label> <div class="col-sm-10"> <div class="input-group"> <span class="input-group-addon"> <span class="glyphicon glyphicon-envelope"> </span> </span> <input type="email" name="email" class="form-control" id="email" placeholder="E-Mail" /> </div> </div> </div> <!--End of E-Mail--> <!--Start of Password--> <div class="form-group"> <label for="password" class="col-sm-2 control-label"> Password </label> <div class="col-sm-10"> <div class="input-group"> <span class="input-group-addon"> <span class="glyphicon glyphicon-star"> </span> </span> <input type="password" name="password" class="form-control" id="password" placeholder="Password" /> </div> </div> </div> <!--End of Password--> <!--Start of Repeat Password--> <div class="form-group"> <label for="repeatPassword" class="col-sm-2 control-label"> <span id="repeatPassword"> Repeat Password </span> </label> <div class="col-sm-10"> <div class="input-group"> <span class="input-group-addon"> <span class="glyphicon glyphicon-check"> </span> </span> <input type="password" name="repeatPassword" class="form-control" id="password" placeholder="Password" /> </div> </div> <!--End of Repeat Password--> <!--Start of Checkbox and Submit Button--> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <label class="checkbox"> <input type="checkbox" name="rememberMe" value="rememberMe" id="rememberMe"> <span id="rememberUs"> Remember Me </span> </label> <button type="submit" name="submit" value="Register" class="btn btn-primary slideToTheLeft"> Register </button> </div> </div> </form> </div> </div> </div> <div class="col-sm-2"></div> </div> <?php include 'INC/footer.php'; ?> If I take the '&& $repeatPassword' out of the equation it skips the condition and echos. if (strlen($password && $repeatPassword) < 8 { However, it is called that $repeatPassword = $password, so I shouldn't even need the '&& repeatPassword' but it won't do anything if it is included into the code. However, the main problem besides that is that no matter what the if statement is stating that no matter what the password is less than 8 characters. A: As a means of testing if supplied values are within permitted bounds you could try: $valid_username=in_array( strlen( $username ), range(2,16) ); $valid_password=$password===$repeatPassword && in_array( strlen( $password ), range(8,32) ); if( $valid_username && $valid_password ){/* all good */} example: if( $submit ) { if( $username && $password && $repeatPassword && $email ) { // hash the Passwords $password = md5( trim( $password ) ); $repeatPassword = md5( trim( $repeatPassword ) ); $unrange=range(3,16); $pwdrange=range(8,32); $valid = true; $valid_username = in_array( strlen( $username ), $unrange ); $valid_password = in_array( strlen( $password ), $pwdrange ); $password_match = $password===$repeatPassword; if( !$valid_password ){ $valid=false; echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Password</b> should be between ".min( $pwdrange )." and ".max( $pwdrange )." characters! </h3> </span>"; } if( !$valid_username ){ $valid=false; echo "<h3 class='text-center'> <span class='alert alert-warning'> Your <b>Username</b> must be between ".min( $unrange )." and ".max( $unrange )." characters! </h3> </span>"; } if( !$password_match ){ $valid=false; echo "<h3 class='text-center'> <span class='alert alert-danger'> Your <b>Passwords</b> must match! </h3> </span>"; } if( $valid ) { echo 'Registration Completed!'; /* add to db? */ } } else echo "<h3 class='text-center'> <span class='alert alert-warning'> Please fill out <b>All</b> fields!</h3> </span>"; } A: You probably don't need to check the length of both $password and $repeatPassword since you will also be checking to see if they match each other. if (strlen($password < 8) { // error } elseif ($password != $repeatPassword) { // error } else { // ALL IS GOOD ! } A: I had actually solved my problem, I decided to take out the or to the password and it had solved the problem and everything is up and running. A: Try this: if (strlen($password) >= 8 && strlen($password) <= 32) { if (strlen($repeatpassword) >= 8 && strlen($repeatpassword) <= 32) { // code here } } I think it's a bit odd to check both passwords, however. So, my solution would be: if (strlen($password) >= 8 && strlen($password) <= 32) { // code here }
{ "language": "en", "url": "https://stackoverflow.com/questions/35132633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: unable to read IF in printing outputs For the following code, Python recommended me to use a.any. Now, according to my code what the outputs show is wrong. l is bigger than 1 but the out put is printing r instead of q=10. from numpy import * import numpy as np for i in range (1,3): r=np.random.uniform(0,3,i) x=np.random.uniform(0,9,i) h=np.random.uniform(0,1,i) l=r+x if (l<1.0).any: q=r elif (l>1.0).any: q=10 print("q= ",q,"l= ",l) A: I took a look at your questions. This one can be scrutinized by changing the random number. using np.random.uniform(0,1) does not need any() if you just want random number. But if it is important to have specific numbers for each i you must use any(). for i in range (1,3): r=np.random.uniform(0,3) x=np.random.uniform(0,9) h=np.random.uniform(0,1) l=r+x if l<1.0: q=r elif l>1.0: q=10 print("q= ",q,"l= ",l)
{ "language": "en", "url": "https://stackoverflow.com/questions/49316345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find the specific component a React warning is referring to? This is what I see in my console: In my React project, I'm seeing many warnings that look like this: Warning: <React warning> in div in div in form (created by MyComponent) in MyComponent in div ... Is there any way to figure out which component the warning is specifically referring to? I have installed React Dev Tools but it has not helped me figure out which component these warnings are referring to. A: According to the React documentation (https://reactjs.org/docs/error-boundaries.html#component-stack-traces), detailed stack traces can be added with the babel-plugin-transform-react-jsx-source plugin (https://www.npmjs.com/package/babel-plugin-transform-react-jsx-source)
{ "language": "en", "url": "https://stackoverflow.com/questions/60403397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Roslyn - Use VisualStudioWorkspace in Visual Studio 2010 Is it possible somehow to use the VisualStudioWorkspace service, in an VsExtension that targets Visual Studio version 2010?(http://source.roslyn.codeplex.com/#Microsoft.VisualStudio.LanguageServices/Implementation/ProjectSystem/VisualStudioWorkspace.cs,e757fe6b8e91e765) I tried to import the service using MEF, as described at https://joshvarty.wordpress.com/2014/09/12/learn-roslyn-now-part-6-working-with-workspaces/, but that's not working at all. [Import(typeof(Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace))] public VisualStudioWorkspace myWorkspace { get; set; } A: No. VisualStudioWorkspace only exists in VS2015 and newer.
{ "language": "en", "url": "https://stackoverflow.com/questions/39372384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery - multiple checkbox and multiple textbox I have 4 check box when i select anyone of the check box need to display the respective check box and text box. input type="checkbox" id="acheck[]" value='name' input type="textbox" id="productfield" value=' ' jquery Code: $(document).ready(function() { $("#productfield").css("display","none"); $("#acheck").click(function(){ if ($("#acheck").is(":checked")) { $("#productfield").fadeIn("slow"); } else { $("#productfield").fadeOut("slow"); } }); }); A: It's not clear from the question, but I guess you want something to appear when you click the checkbox? This should get you started. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style> #appear_div { display: none; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> $(document).ready(function() { $('#appear').click(function() { $('#appear_div').show(); }); }); </script> </head> <body> <input type="checkbox" id="appear"> <div id="appear_div"> <input type="checkbox" id="cb1">Check me <input type="text" id="text1"> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/1124760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-7" }
Q: Store images in HTML5 local Storage onClick I am currently creating an app as a side project using jQuery Mobile & PhoneGap. This app will show multiple images and gives the user the opportunity to favorite an image that he/she likes. Once the user clicks on the button to favorite the image, that image will display on the favorites page (favorite.html). I am having trouble using local Storage to incorporate this task. Is it even possible to store and retrieve images to another page? Any help will be great. Below is a link to my jsfiddle if you need a visual. JSFiddle Demo <!-- Page One --> <div data-role="page" id="one"> <div data-role="header"> <h1>Page 1</h1> </div> <div data-role="main"> <img src="https://www.petfinder.com/wp-content/uploads/2012/11/140272627-grooming-needs-senior-cat-632x475.jpg" style="width: 100px;"/> <br /> <button id="favcat">Click Here to Favorite Cat Image!</button> <br /> <br /> <img src="http://www.dogslovewagtime.com/wp-content/uploads/2015/07/Dog-Pictures.jpg" style="width: 100px;" /> <br /> <button id="favdog">Click Here to Favorite Dog Image!</button> </div> </div> <!--Page Two --> <div data-role="page" id="two"> <div data-role="header"> <h1>Page 2: Stored and Retrieved Images Display On This Page Once Clicked</h1> </div> <div data-role="main"> </div> </div> A: First you must identify what image should be stored, you can see a custom attribute for image called data-name and other for button called data-image, both have the same content: <!-- Page One --> <img data-name="catImage" src="https://www.petfinder.com/wp-content/uploads/2012/11/140272627-grooming-needs-senior-cat-632x475.jpg" style="width: 100px;"/> <br /> <button class="btn-add-image" data-image="catImage">Click Here to Favorite Cat Image!</button> Now, when a user click on a image button, first you must get your image: var myImageName = $(this).attr("data-image"); var myImage = $('img[data-name="' + myImageName + '"]'); After you should get the image base64 string //Create a Canvas var myCanvas = document.createElement("canvas"); //Set width and height myCanvas.width = myImage.width(); myCanvas.height = myImage.height(); //Draw imagem var myContext = myCanvas.getContext("2d"); myContext.drawImage(myImage, 0, 0); //And finally get canvas64 string var base64 = myCanvas.toDataURL("image/jpeg"); // if it's a png uses image/png And now save it on localStorage: localStorage.setItem("image", base64); And now restore on page two - page two HTML: <!--Page Two --> <div data-role="page" id="two"> <h1>Page 2: Stored and Retrieved Images Display On This Page Once Clicked</h1> </div> <div data-role="main" id="restoredImage"> </div> Page two JavaScript: $(document).ready(function() { var img = document.createElement("img"); img.src = localStorage.getItem("image"); $("#restoredImage").html(img); }); A: Other idea is use only vanilla JS Page one - to save on localStorage: var img = new Image, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), src = "http://example.com/image"; // insert image url here img.crossOrigin = "Anonymous"; canvas.width = img.width; canvas.height = img.height; ctx.drawImage( img, 0, 0 ); localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") ); Page two - to recovery from localStorage: localStorage.getItem("savedImageData") JSBin example: https://jsbin.com/hewapewoxe/edit?html,js,console
{ "language": "en", "url": "https://stackoverflow.com/questions/33771737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to easily store and access logs from my running iOS app using the new Logger system? I've read a lot of documentation which tells me to use macOS' Console app to access the supposedly stored logs but I can't for the life of me get it to work. This is what I am doing: * *Created several Logger(subsystem: "Some.Name", category: "SomeCategory") through my app following documentation. *Created several log calls to the aforementioned loggers in my codebase, as stated in the documentation. *These seem to work perfectly fine as I can see all my logs in Xcode's console live while running my app in debugging mode through Xcode. Up to this point the experience has been perfect. *But I want these logs to be stored somewhere persistently though, so I can see what caused a crash that happened while my device was not connected to my macbook running Xcode. I tried using my macbook's Console app following these instructions, but all I can see is a live flood of my iPad's event logs, which for some reason don't contain the logs I coded myself, they instead consist of random framework logs from my app like CoreData logs for example. My google skills have been failing me with this particular problem, and I can't believe how difficult this has been, I probably should've just used a text file for logging at this point. Well, if anybody has any insight on this I'd be immensely thankful.
{ "language": "en", "url": "https://stackoverflow.com/questions/65854061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VBA Run-time error -2147319767 (80028029) in Public Function This error popped up today in the following code: Public lngLast_CS_Sheet As Long Public lngCS1_Index As Long Public lngCSLast_Index As Long Public Function num_CSx_Sheets() 'Function to find total number of CS Sheets Dim w As Long, cs As Long For w = 1 To Sheets.Count cs = cs - CBool(UCase(Left(Sheets(w).Name, 2)) = "CS") Next w num_CSx_Sheets = cs End Function This function has been working fine for several years but produces the error when w = 17 & cs = 4 I have checked the range of CS sheets for user mis-naming but cannot find any issues. The function is called by the following code: Sub BoMLookUpMaterials_2019_Rev_B() ' ' BoMSearch CS Sheets Macro - Modified 11/01/19 - PRS ' Dim FirstSheet As Integer Dim LastSheet As Integer Dim LastRow As Integer Dim FirstRow As Integer Dim ItemQTY As Single Dim sSheetName As String Dim sItemName As String With ActiveSheet LastRow = Cells(.Rows.Count, "Q").End(xlUp).Row 'Find last row of BoM (Qty) Col Q End With ' sSheetName = ActiveSheet.Name 'Get sheet name of active Database sheet ' lngLast_CS_Sheet = num_CSx_Sheets() 'Find total number of CS sheets lngCS1_Index = Sheets("CS1").Index 'CS1 Sheet Index No. lngCSLast_Index = Sheets("CS" & lngLast_CS_Sheet).Index 'Last CS Sheet Index No. Select Case sSheetName 'Determines which BoM sheet initiated Update BOM procedure I am not a experienced VBA programmer and can't figure out why this is occurring now. Can somebody point me in the right direction? A: I don't think this is a code issue as further testing by making lngLast_CS_Sheet equal the number of CS sheets in the workbook, the code runs without error. This error has only occurred in this workbook and not others with exactly the same code modules. Therefore I conclude this to be a user induced error somewhere within the workbook which I will tray & track down
{ "language": "en", "url": "https://stackoverflow.com/questions/60154207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CodeIgniter User Access I need help where every page I give value 1 so what I want if page without value 1 cannot be access with another user my logic like this : <li class="treeview"> <a href="#"> <i class="fa fa-gears"></i> <span>User Setting</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="<?= $this->config->base_url() ?>changepassword?f=1"><i class="fa fa-circle-o"></i> Change Password</a></li> <li><a href="<?= $this->config->base_url() ?>infouser"><i class="fa fa-circle-o"></i> Info User</a></li> </ul> </li> if user B who don't have access want to open page changepassword.php disable because in database access they don't have value 1 but 0. but they can open page infouser.php cause value not 1 there any one can give me logic using codeigniter where my database like this : no | UID | PWD | access | 1 | user A | user A | 11 | 2 | user B | user B | 10 | A: Well, you need to create ACL Functionality. in which you need to create a pivot table. id (int) 11 user_id (int) 11 controller (text) action (text) Database Records can be : | 1 | 3 | users | dashboard | | 1 | 3 | users | profile | | 1 | 3 | users | password | and you can make an interface to update user with their allowed controllers/actions In this way, you can allow users to access their respective actions. To get the permissions, you need to run the query with current user id and get controller/action from URL or getRoutes function.
{ "language": "en", "url": "https://stackoverflow.com/questions/42196647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to output a binary file in C without padding bits I'd like to output a struct's data to a binary file, but without any padding bits between each variable's information. For example: struct s { int i1; short s1; char c1; }; struct s example[2]; If I use fwrite(&example, sizeof(struct s), 2, file), the binary file still has the padding bits between, for example, s1 and c1, and also from c1 to i1 (of the 2nd struct). What would be a good approach to remove those padding bits from the output file ? Thanks! Any help is appreciated A: I would just suggest manually reading/writing the members of the struct individually. Packing using your compiler directives can cause inefficiency and portability issues with unaligned data access. And if you have to deal with endianness, it's easy to support that later when your read operations break down to field members rather than whole structs. Another thing, and this relates more to futuristic maintenance-type concerns, is that you don't want your serialization code or the files people have saved so far to break if you change the structure a bit (add new elements or even change the order as a cache line optimization, e.g.). So you'll potentially run into a lot less pain with code that provides a bit more breathing room than dumping the memory contents of the struct directly into a file, and it'll often end up being worth the effort to serialize your members individually. If you want to generalize a pattern and reduce the amount of boilerplate you write, you can do something like this as a basic example to start and build upon: struct Fields { int num; void* ptrs[max_fields]; int sizes[max_fields]; }; void field_push(struct Fields* fields, void* ptr, int size) { assert(fields->num < max_fields); fields->ptrs[fields->num] = ptr; fields->sizes[fields->num] = size; ++fields->num; } struct Fields s_fields(struct s* inst) { struct Fields new_fields; new_fields.num = 0; field_push(&new_fields, &inst->i1, sizeof inst->i1); field_push(&new_fields, &inst->s1, sizeof inst->s1); field_push(&new_fields, &inst->c1, sizeof inst->c1); return new_fields; } Now you can use this Fields structure with general-purpose functions to read and write members of any struct, like so: void write_fields(FILE* file, struct Fields* fields) { int j=0; for (; j < fields->num; ++j) fwrite(fields->ptrs[j], fields->sizes[j], 1, file); } This is generally a bit easier to work with than some functional for_each_field kind of approach accepting a callback. Now all you have to worry about when you create some new struct, S, is to define a single function to output struct Fields from an instance to then enable all those general functions you wrote that work with struct Fields to now work with this new S type automatically. A: Many compilers accept a command line parameter which means "pack structures". In addition, many accept a pragma: #pragma pack(1) where 1 means byte alignment, 2 means 16-bit word alignment, 4 means 32-bit word alignment, etc. A: To make your solution platform independent, you can create a function that writes each field of the struct one at a time, and then call the function to write as many of the structs as needed. int writeStruct(struct s* obj, size_t count, FILE* file) { size_t i = 0; for ( ; i < count; ++i ) { // Make sure to add error checking code. fwrite(&(obj[i].i1), sizeof(obj[i].i1), 1, file); fwrite(&(obj[i].s1), sizeof(obj[i].s1), 1, file); fwrite(&(obj[i].c1), sizeof(obj[i].c1), 1, file); } // Return the number of structs written to file successfully. return i; } Usage: struct s example[2]; writeStruct(s, 2, file);
{ "language": "en", "url": "https://stackoverflow.com/questions/30021822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Dropdown menu correct? I want to create a dopdownmenu, only with html & css. And now i think i made a fault.. I did not much at the moment here is my Page: Page The tutorials in the internet arent suitable for me :/ It would be cool if someone can write me something about the construction. Because i think it isnt correct. Thanks. Code: *{ margin: 0px; padding: 0px; } a{ display: block; display: block; padding: 10px; background-color: lightgrey; } .li_oben, .li_unten{ display: inline-block; } <html> <head> <title>Homeapge</title> <link rel="stylesheet" href="index.css"> </head> <body> <nav> <ul class="ul_oben"> <li class="li_oben"><a href="#">Link 1</a></li> <li class="li_oben"><a href="#">Link 2 <ul class="ul_unten"> <li class="li_unten"><a href="#">Link 2.1</a></li> <li class="li_unten"><a href="#">Link 2.2</a></li> </ul> </a></li> </ul> </nav> </body> </html> A: Multilevel menu markup should look like this: <ul> <li><a>Link 1</a></li> <li><a>Link 2</a></li> <li> <a>Link 3</a> <ul> <li><a>Link 3.1</a> <li><a>Link 3.2</a> (...) </ul> </li> </ul> A: This kind of technique is broadly published in the internet. A quick search landed me in a tutorial that captures precisely what you want to achieve. Simple CSS Drop Down Menu by James Richardson And here is a quick JSFiddle from the tutorial I've created. Quick look over the CSS styling. ul {list-style: none;padding: 0px;margin: 0px;} ul li {display: block;position: relative;float: left;border:1px solid #000} li ul {display: none;} ul li a {display: block;background: #000;padding: 5px 10px 5px 10px;text-decoration: none; white-space: nowrap;color: #fff;} ul li a:hover {background: #f00;} li:hover ul {display: block; position: absolute;} li:hover li {float: none;} li:hover a {background: #f00;} li:hover li a:hover {background: #000;} #drop-nav li ul li {border-top: 0px;}
{ "language": "en", "url": "https://stackoverflow.com/questions/27755094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Get return value of fputcsv Does anyone know of a function, or a cool trick, to get the return value of fputcsv instead of writing the output to file? I'm trying to encode a file as a tab-delimited file, but my client wants one of the columns encoded in csv (so 1 column of csv values in a tab delimited file). Not ideal, I agree, but at this point I just need to get it done. Thanks! A: Shamelessly copying from a user note on the documentation page: $buffer = fopen('php://temp', 'r+'); fputcsv($buffer, $data); rewind($buffer); $csv = fgets($buffer); fclose($buffer); // Perform any data massaging you want here echo $csv; All of this should look familiar, except maybe php://temp. A: $output = fopen('php://output', 'w'); fputcsv($output, $line); fclose($output); Or try one of the other supported wrappers, like php://memory if you don't want to output directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7362322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Postgres date subtraction in a query I want to do a dynamic query which always takes an interval of todays_date and todays_date - 30 SELECT day::date FROM generate_series('2014-08-01'::date, '2014-09-14'::date, interval '1 week') day But with current date, something like this SELECT day::date FROM generate_series(CURRENT_DATE, CURRENT_DATE - 30, interval '1 week') day A: You had it almost right. Try this (for an incrementing series): SELECT day::date FROM generate_series(CURRENT_DATE - interval '30 days', CURRENT_DATE, interval '1 week') day Or if you really want to go backward: SELECT day::date FROM generate_series(CURRENT_DATE, CURRENT_DATE - interval '30 days', -interval '1 week') day
{ "language": "en", "url": "https://stackoverflow.com/questions/25905638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get value of disabled control in angular material I have divided my form into multiple components. Only parent component has form control. Child components has for "formGroup" attribute. On submit I need to read values of all controls but child component has few controls disabled. I tried value and getRawValue options but both giving the same result. let fullForm: myClass; this.parentForm=this.formBuilder.group({ childGroup1:[this.fullForm.child1] childGroup2:[this.fullForm.child2] }); submit(){ --Both below line of code is not giving disabled controls value from child component console.log(this.parentForm.value); console.log(this.parentForm.getRawValue()); } ---Parent component html--- <form [formGroup]="parentForm"> <add-child1 [formGroup]="childGroup1"></app-child1> <add-child2 [formGroup]="childGroup2"></app-child2> <button (click)="submit()"></button> </form> I have used ControlValueAccessor in child components.
{ "language": "en", "url": "https://stackoverflow.com/questions/68026191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make a PictureBox move using arrow/WASD keys? I'm trying to use this code to make a pong game, but for what ever reason, my code isn't working. As far as I can tell, everything should be correct. I have the Timer enabled and the code compiles, because the program boots without errors, but the PictureBoxes aren't moving. Can someone spot my issue? public partial class Form1 : Form { bool P1Up, P1Down, P2Up, P2Down; int Speed = 12; public Form1() { InitializeComponent(); } private void MoveTriggerTick(object sender, EventArgs e) { if (P1Up == true) Player1Paddle.Top += Speed; if (P1Down == true) Player1Paddle.Top -= Speed; if (P2Up == true) Player2Paddle.Top += Speed; if (P2Down == true) Player2Paddle.Top -= Speed; } private void Form1_KeyDown(object sender, KeyEventArgs e) { int P1Y = Player1Paddle.Location.Y; int P2Y = Player2Paddle.Location.Y; if (e.KeyCode.ToString() == "w") P1Up = true; if (e.KeyCode.ToString() == "s") P1Down = true; if (e.KeyCode == Keys.Up) P2Up = true; if (e.KeyCode == Keys.Down) P2Down = true; } private void Form1_KeyUp(object sender, KeyEventArgs e) { int P1Y = Player1Paddle.Location.Y; int P2Y = Player2Paddle.Location.Y; if (e.KeyCode.ToString() == "w") P1Up = false; if (e.KeyCode.ToString() == "s") P1Down = false; if (e.KeyCode == Keys.Up) P2Up = false; if (e.KeyCode == Keys.Down) P2Down = false; } } Footnote: Wanted to get paddle movement implemented before looking at adding the ball or score. A: if (e.KeyCode.ToString() == "w") should be if (e.KeyCode == Keys.W) and so on. It's in the System.Windows.Forms namespace (see the documentation). Also check that MoveTriggerTick is correctly registered as timer handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/69053990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Constraint solving with choco: Finding unique solutions for a variable I'm using Choco to solve a CSP. In the beginning, I create an array of variables v like this: IntVar[] v = new IntVar[5]; After adding several constraints, I'll search for solutions and find multiple of them. However, I want only unique solutions for e.g. v[4]. So all solutions should have a different value in the v[4] variable. How can I achieve this?
{ "language": "en", "url": "https://stackoverflow.com/questions/45108308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Preventing "foo" from matching "foo-bar" with grep -w I am using grep inside my Perl script and I am trying to grep the exact keyword that I am giving. The problem is that "-w" doesn't recognize the "-" symbol as a separator. example: Let's say that I have these two records: A1BG 0.0767377011073753 A1BG-AS1 0.233775553296782 if I give grep -w "A1BG" it returns both of them but I want only the exact one. Any suggestions? Many thanks in advance. PS. Here is my whole code. The input file is a two-columns tab separated. So, I want to keep a unique value for each gene. In cases that I have more than one record, I calculate the average. #!/usr/bin/perl use strict; use warnings; #Find the average fc between common genes sub avg { my $total; $total += $_ foreach @_; return $total / @_; } my @mykeys = `cat G13_T.txt| awk '{print \$1}'| sort -u`; foreach (@mykeys) { my @TSS = (); my $op1 = 0; my $key = $_; chomp($key); #print "$key\n"; my $command = "cat G13_T.txt|grep -E '([[:space:]]|^)$key([[:space:]]|\$)'"; #my $command = "cat Unique_Genes/G13_T.txt|grep -w $key"; my @belongs= `$command`; chomp(@belongs); my $count = scalar(@belongs); if ($count == 1) { print "$belongs[0]\n"; } else { for (my $i = 0; $i < $count; $i++) { my @token = split('\t', $belongs[$i]); my $lfc = $token[1]; push (@TSS, $lfc); } $op1 = avg(@TSS); print $key ."\t". $op1. "\n"; } } A: You may use a POSIX ERE regex with grep like this: grep -E '([[:space:]]|^)A1BG([[:space:]]|$)' file To return matches (not matching lines) only: grep -Eo '([[:space:]]|^)A1BG([[:space:]]|$)' file Details * *([[:space:]]|^) - Group 1: a whitespace or start of line *A1BG - a substring *([[:space:]]|$) - Group 2: a whitespace or end of line A: If I got clarifications in comments right, the objective is to find the average of values (second column) for unique names in the first column. Then there is no need for external tools. Read the file line by line and add up values for each name. The name uniqueness is granted by using a hash, with names being keys. Along with this also track their counts use warnings; use strict; use feature 'say'; my $file = shift // die "Usage: $0 filename\n"; open my $fh, '<', $file or die "Can't open $file: $!"; my %results; while (<$fh>) { #my ($name, $value) = split /\t/; my ($name, $value) = split /\s+/; # used for easier testing $results{$name}{value} += $value; ++$results{$name}{count}; } foreach my $name (sort keys %results) { $results{$name}{value} /= $results{$name}{count} if $results{$name}{count} > 1; say "$name => $results{$name}{value}"; } After the file is processed each accumulated value is divided by its count and overwritten by that, so by its average (/= divides and assigns), if count > 1 (as a small measure of efficiency). If there is any use in knowing all values that were found for each name, then store them in an arrayref for each key instead of adding them while (<$fh>) { #my ($name, $value) = split /\t/; my ($name, $value) = split /\s+/; # used for easier testing push @{$results{$name}}, $value; } where now we don't need the count as it is given by the number of elements in the array(ref) use List::Util qw(sum); foreach my $name (sort keys %results) { say "$name => ", sum(@{$results{$name}}) / @{$results{$name}}; } Note that a hash built this way needs memory comparable to the file size (or may even exceed it), since all values are stored. This was tested using the shown two lines of sample data, repeated and changed in a file. The code does not test the input in any way, but expects the second field to always be a number. Notice that there is no reason to ever step out of our program and use external commands.
{ "language": "en", "url": "https://stackoverflow.com/questions/55403773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: installr:install.pandoc() appears broken I recently noticed that the install.pandoc function in the installr package appears to be broken. I get the following error message: trying URL 'https://github.com/' Content type 'text/html; charset=utf-8' length unknown downloaded 78 KB github.com is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. It looks like the function is not finding the appropriate file from GitHub. I have submitted a pull request to the installr package on GitHub which corrects this error. A: Here is the function that should install Pandoc correctly and that was submitted as a pull request. In case you run into this error before it is fixed. library(installr) FixedInstall.Pandoc <- function (URL = "https://github.com/jgm/pandoc/releases", use_regex = TRUE, to_restart, ...) { URL <- "https://github.com/jgm/pandoc/releases" page_with_download_url <- URL if (!use_regex) warning("use_regex is no longer supported, you can stop using it from now on...") page <- readLines(page_with_download_url, warn = FALSE) sysArch <- Sys.getenv("R_ARCH") sysArch <- gsub("/ |/x", "", sysArch) pat <- paste0("jgm/pandoc/releases/download/[0-9.]+/pandoc-[0-9.-]+-windows",".*", sysArch, ".*", ".msi") target_line <- grep("windows", page, value = TRUE) m <- regexpr(pat, target_line) URL <- regmatches(target_line, m) URL <- head(URL, 1) URL <- paste("https://github.com/", URL, sep = "") installed <- install.URL(URL, ...) if (!installed) return(invisible(FALSE)) if (missing(to_restart)) { if (is.windows()) { you_should_restart <- "You should restart your computer\n in order for pandoc to work properly" winDialog(type = "ok", message = you_should_restart) choices <- c("Yes", "No") question <- "Do you want to restart your computer now?" the_answer <- menu(choices, graphics = "TRUE", title = question) to_restart <- the_answer == 1L } else { to_restart <- FALSE } } if (to_restart) os.restart() }
{ "language": "en", "url": "https://stackoverflow.com/questions/53788391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTP Content-Length and Chunked Transfer-Encoding. Is there a 2GB Limit? Is a HTTP Content-Length over 2GB or 4GB supported by modern webservers? How about the chunks in HTTP Chunked Transfer Encoding? Can an individual HTTP chunk exceed 2GB in length? I need to know to use 32-bit integers or 64-bit integers in my code. A: From what I have gathered, 64-bit limits are new, especially in the web browsers. Chrome supports them, Opera maybe, and I see a patch for Firefox that hasn't landed yet. I've read posts that say IE returns negative Content-Length, which means it's likely to use 32-bits. 64-bit HTTP lengths looks like the future, but we aren't there yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/8811824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Symfony ajax form need reload page to show results I have a product page where users can write comments, this works fine but i would like to implement ajax form with no page refresh. The code call ajax and persist, but need press f5 to show new comment. what am I doing wrong? Thanks, and sorry for my english. In product view, render a controller that call the form: <div class="comments"> {{ render(controller('AppBundle:Comment:newComment',{'media': selected.id})) }} </div> Controller: class CommentController extends Controller { /** * @Route("/media/{media}/", name="create_comment", options={"expose"=true}) * @Method("POST") * @ParamConverter("media", class="AppBundle:Media") */ public function newCommentAction(Request $request, $media) { $comment = new Comment(); $form = $this->createForm(CommentType::class, $comment); $form->handleRequest($request); if($form->isSubmitted() && $form->isValid()){ $data = $form->getData(); $data->setUser($this->getUser()); $data->setMedia($media); $em = $this->getDoctrine()->getManager(); $em->persist($data); $em->flush(); return new JsonResponse('Success!'); } return $this->render('comment/newComment.html.twig', array( 'media' => $media, 'form' => $form->createView() )); } } newComment.html.twig <form method="POST" id="commentForm" action="{{path('create_comment', {'media': media.id})}}"> {{ form_row(form.comment) }} <button type="submit" id="submitButton" class="btn btn-xs btn-danger">{{ 'btn.send' |trans }}</button> app.js $('body').on('click','#submitButton', function(e){ e.preventDefault(); var $form = $('#commentForm'); $.ajax({ type: "POST", dataType: "json", url: 'http://demo/app_dev.php/media/16/', data: $form.serialize(), cache: false, success: function(response){ $(".ajaxResponse").html(response); console.log(response); }, error: function (response) { console.log(response); } }); }); A: This should work for you to reload the element with class="comments" after your POST: $('#submitButton').on('click', function (e) { e.preventDefault(); var $form = $('#commentForm'); $.ajax({ type: "POST", dataType: "json", url: 'http://demo/app_dev.php/media/16/', data: $form.serialize(), cache: false, success: function (response) { $('.comments').load(window.location + ' .comments > *'); console.log(response); }, error: function (response) { console.log(response); } }); }); Edit: As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests?
{ "language": "en", "url": "https://stackoverflow.com/questions/36024684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you use URL_Rewrite rewritemaps to modify ServerVariables in IIS? So I'm having an issue and not sure if it's even possible. Here's the scenario. We utilize an F5 loadbalancer with an i-Rule set to send us a header (HTTP_IV-USER) value based on an access token. We want to query that header, see if it matches a value we have setup in a rewritemap and then change it accordingly. I haven't seen anyone doing this with servervariables. It makes sense on how to do it in regards to changing an URL... but we'd like to change a header variable. Basically we're taking the value from the Token, which is a number, and then matching that number to a username in active directory. Thanks for the help! A: Of course, we can use rewritemap to check and replace the value. You could modify the rule below to achieve your requirement. <rewriteMaps> <rewriteMap name="StaticMap"> <add key="aaaaaaaaa" value="bbbbbbbb" /> </rewriteMap> </rewriteMaps> <outboundRules> <rule name="rewritemaprule"> <match serverVariable="HTTP_IV-USER" pattern="(.*)" /> <conditions> <add input="{StaticMap:{HTTP_IV-USER}}" pattern="(.+)" /> </conditions> <action type="Rewrite" value="{C:1}" /> </rule> </outboundRules>
{ "language": "en", "url": "https://stackoverflow.com/questions/58293108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handle Group by different way in postgres This query getting result like below select date_part('hour', ts.a_start_time) AS hour,count(*) as c, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 0) AS s, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 1) AS m, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 2) AS t, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 3) AS w, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 4) AS th, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 5) AS f, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 6) AS sa from flight_schedules as fs inner join resource_mapping as rm on rm.flight_schedules_id = fs.id inner join task_schedule_details as tsd on tsd.id = rm.task_schedule_detail_id inner join task_status as ts on ts.resource_mapping_id = rm.id inner join task_master as tm on tm.id = tsd.task_id inner join delay_code_master as dcm on dcm.id = ts.delay_code_id inner join delay_categorization as dc on dc.id = dcm.delay_category_id Where fs.station=81 group by hour order by hour ASC But i want group by hour like A: you can use case when hour to merge multi hours to time range then group it. select (case when date_part('hour', ts.a_start_time) <= 6 then '1 to 6' when date_part('hour', ts.a_start_time) <= 12 then '6 to 12' when date_part('hour', ts.a_start_time) <= 18 then '12 to 18' else '18 to 23' end )AS hour, count(*) as c, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 0) AS s, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 1) AS m, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 2) AS t, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 3) AS w, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 4) AS th, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 5) AS f, count(*) FILTER (WHERE EXTRACT(dow FROM ts.a_start_time) = 6) AS sa from flight_schedules as fs inner join resource_mapping as rm on rm.flight_schedules_id = fs.id inner join task_schedule_details as tsd on tsd.id = rm.task_schedule_detail_id inner join task_status as ts on ts.resource_mapping_id = rm.id inner join task_master as tm on tm.id = tsd.task_id inner join delay_code_master as dcm on dcm.id = ts.delay_code_id inner join delay_categorization as dc on dc.id = dcm.delay_category_id Where fs.station=81 group by hour order by hour ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/58654787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using CMD window, get the most recent filename for each folder of the current directory How can I use the cmd window to get the name of the most recent file in each folder in the current directory? I feel like this is either a multistep process of commands or a one-liner beyond my current knowledge. I am only familiar with using "one off" commands from the command line such as dir /b /o:n /ad > folderlist.txt, so any reference to doing more complicated cmd line tasks would be great too. A: You need to be able to iterate over the list of directories and over the list of files in each directories. This can be done using a FOR loop. See FOR /? for more details. @ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION PUSHD "C:\the directory\of interest" FOR /F "usebackq tokens=*" %%d IN (`DIR /B /A:D .`) DO ( DIR /B /A:-D %%d >NUL 2>&1 IF !ERRORLEVEL! EQU 0 ( FOR /F "usebackq tokens=*" %%f IN (`DIR /B /A:-D /O:D %%d`) DO ( SET LASTFILE=%%f ) ECHO %%d\!LASTFILE! ) ) POPD
{ "language": "en", "url": "https://stackoverflow.com/questions/36271090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passing command line arguments in coded ui tests Is it possible to pass command line arguments in coded ui test ? in normal C# programs we just pass the arguments along with the exe file eg: filename.exe "2" "7" in command prompt. but can something like this be done in coded ui tests? Thanks A: No, you can do that. CodedUi tests are executed through command line through MSTest which does not support it. Check here to see the available command-line options of MSTest. However, you can create another Project (e.g. console application) to achieve that. The second project has a reference to your CodedUI Project. Then pass the parameters through the .exe file of this Project which calls the appropriate CodedUI Test Method. But I think that this will not work like MSTest does (it will not create Test Results).
{ "language": "en", "url": "https://stackoverflow.com/questions/10299599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Get data payload of android notification on dismiss I'm using Firebase Cloud Messaging to send notifications with data payload to my app. When i send a notification, if my app is running (foreground) i get the data overriding the onMessageReceived() from FirebaseMessagingService class. If my app is not running the notification is sent to the "system tray" and when the user click's in notification my app start and i can get the data with the getExtras of the intent. But, how could i get the data if the user dismiss the notification in "system tray"? I need to write some background service that "listen" to the notifications to get this? A: Seems like you are sending notifications from the Firebase console. These messages are always notification messages. If a notification message has an accompanying data payload then that data is only available to your application if the user taps the notification. If the user never taps the notification then that data will not be available to your app. So you should not use notification messages to send app critical data to your application. If you send data messages they are always handled by onMessageReceived callback. At that point you can either silently handle the message or display your own notification. So use data messages if you want to be sure that your application has an opportunity to handle the data in the message. A: So basically you want to store that data ? if you want to store that data then write your code in OnReceive() method and write Database insertion code in it. and put one flag in it like "Dismissed=true" and if user open your notification then make it false and you can get your result. There is no specific method to detect whether your app's notification is dismissed or not. So you have to manually maintain that data.
{ "language": "en", "url": "https://stackoverflow.com/questions/38350498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to trigger a link from jQuery? I am not able to trigger A link from jQuery? Here is my code Html Code I am trying to open app if installed otherwise it will redirect me to play store. Its working when i click on link but i need to redirect it automatically <a id="link_id" href="app://details?id=agd.solutions.myapplication"fallbackhref="market://details?id=agd.solutions.myapplication">Click to download</a> Jquery Code I have tried everything but its not working jQuery('#link_id').click(); $("#link_id").trigger("click"); $('a').get(0).click(); $('a')[0].click(); $('#link_id')[0].click(); Tried all the above option but not working A: Try this: $('#link_id')[0].click(); A: You can try something link this. window.open($("#link_id").attr("href")) Working fiddle here
{ "language": "en", "url": "https://stackoverflow.com/questions/59589070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Object.assign() causes TypeError: this.map is not a function I was trying to extend Array.prototype with some new methods/properties, the following is what I did in the first attempt, which ended up with a TypeError: // Array.prototype + .max(), .maxRowLength (by Object.assign) Object.assign(Array.prototype, { // max something in the array max(mapf = (x) => x) { // ----------------------------------------- return Math.max(...this.map(x => mapf(x))); // ^^^^^^^^ // ⛔ TypeError: this.map is not a function // ----------------------------------------- }, // max row length of 2D array // assuming an element of the 2D array is called a "row" get maxRowLength() { return this.max(row => row.length); }, }); // matrix (2D array) let m = [[1, 2, 3, 4], [1, 2], [1, 2, 3]]; m.max(row => row.length) // didn't work, can't even run. m.maxRowLength I don't understand why this is happening, so I go on with my second attempt, this time with a different approach, and it runs successfully without any problem: // Array.prototype + .max() Array.prototype.max = function(f = x => x){ return Math.max(...this.map(x => f(x))); }; // Array.prototype + .maxRowLength (by Object.defineProperty) Object.defineProperty(Array.prototype, 'maxRowLength', { get: function(){ return this.max(row => row.length) } }); // matrix (2D array) let m = [[1, 2, 3, 4], [1, 2], [1, 2, 3]]; // 3 "rows" m.max(row => row.length) // 4 ✅ m.maxRowLength // 4 ✅ Does anyone know what are the differences between these two approaches, and most importantly why the first attampt failed? A: In your first code, when you use Object.assign, the parameters past the first have their getters invoked: Object.assign( {}, { get foo() { console.log('getter invoked'); } } ); So, your get maxRowLength is running immediately, before you're even declaring the m array - and when the getter is invoked, it calls this.max, and at that point, this is the second argument you're passing to Object.assign, which is that object - which doesn't have a .map method, resulting in the error. Here's another more minimal example of your code to show what's going on: const objectToAssign = { max() { // `this` is the object here console.log(this === objectToAssign); }, get maxRowLength() { return this.max(); }, }; Object.assign(Array.prototype, objectToAssign); A: Yesterday when I was reading the book JavaScript: The Definitive Guide, 7th Edition, I suddenly came across a listing of code in that book (Section 14.1: Property Attributes) that happened to be dedicated exactly to my original problem, so I think maybe I should list it here for future reference or maybe someone may need it: /***************************************************************** * Object.assignDescriptors() * ***************************************************************** * * • copies property descriptors from sources into the target * instead of just copying property values. * * • copies all own properties (both enumerable and non-enumerable). * • copies getters from sources and overwrites setters in the target * rather than invoking those getters/setters. * * • propagates any TypeErrors thrown by `Object.defineProperty()`: * • if the target is sealed or frozen or * • if any of the source properties try to change an existing * non-configurable property on the target. */ Object.defineProperty(Object, "assignDescriptors", { // match the attributes of `Object.assign()` writable : true, enumerable : false, configurable: true, // value of the `assignDescriptors` property. value: function(target, ...sources) { for(let source of sources) { // copy properties for(let name of Object.getOwnPropertyNames(source)) { let desc = Object.getOwnPropertyDescriptor(source, name); Object.defineProperty(target, name, desc); } // copy symbols for(let symbol of Object.getOwnPropertySymbols(source)) { let desc = Object.getOwnPropertyDescriptor(source, symbol); Object.defineProperty(target, symbol, desc); } } return target; } }); // a counter let counter = { _c: 0, get count() { return ++this._c; } // ⭐ getter }; // ---------------------------------------------------------- // ☢️ Alert: // Don't use Object.assign with sources that have getters, // the inner states of the sources may change❗❗❗ // ---------------------------------------------------------- // copy the property values (with getter) let iDontCount = Object.assign({}, counter); // ☢️ `counter.count` gets INVOKED❗❗❗ counter._c === 1 (polluted)❗❗❗ // copy the property descriptors let iCanCount = Object.assignDescriptors({}, counter); [ counter._c, // 1 (☢️ polluted by Object.assign❗) // ⭐ `iDontCount.count` is a "data" property Object.getOwnPropertyDescriptor(iDontCount, 'count'), // { // value: 1, <---- ⭐ data property // writable: true, enumerable: true, configurable: true // } iDontCount.count, // 1: just a data property, iDontCount.count, // 1: it won't count. // ⭐ `iCanCount.count` is an "accessor" property (getter) Object.getOwnPropertyDescriptor(iCanCount, 'count'), // { // get: [Function: get count], <---- ⭐ accessor property // set: undefined, // enumerable: true, // configurable: true // } // ☢️ although it can count, it doesn't count from 1❗ iCanCount.count, // 2: it's a getter method alright, but its "count" iCanCount.count, // 3: has been polluted by Object.assgin() ☢️ ].forEach(x => console.log(x))
{ "language": "en", "url": "https://stackoverflow.com/questions/72625697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Make selected text bold/unbold I'm wrapping the selected text in span tags, when you click a button. If I then select a different piece of text and click the button, that text also gets wrapped in tags. However, when I select a piece of text that's already wrapped in span tags, I'd like to remove those tags to unembolden the text, instead of wrapping those tags in more tags. HTML <div contenteditable="true" class="textEditor">Some random text.</div> <a href="#" class="embolden">Bold</a> JS $('.embolden').click(function(){ var highlight = window.getSelection(); var span = '<span class="bold">' + highlight + '</span>'; var text = $('.textEditor').html(); $('.textEditor').html(text.replace(highlight, span)); }); JSFiddle Demo I'm probably getting greedy with this request but I select just part of a piece of text that's already wrapped in span tags, but not all of it, I'd like to close the original tag at the start of the selection, open a new tag right after that, then close the new tag at the end of the selection and open a new tag after that. A: Why you are trying to bold text doing it by hand when you can use built in feature. Modern browsers implements execCommand function that allows to bold, underline etc. on text. You can write just: $('.embolden').click(function(){ document.execCommand('bold'); }); and selected text will be made bold and if it's already bold, the text styling will be removed. A list of commands and a little doc can be found here. (More about browser support here). $(document).ready(function() { $('#jBold').click(function() { document.execCommand('bold'); }); }); #fake_textarea { width: 100%; height: 200px; border: 1px solid red; } button { font-weigth: bold; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="jBold"><b>B</b></button> <div id='fake_textarea' contenteditable> Select some text and click the button to make it bold... <br>Or write your own text </div> A: Copied function from this answer: Get parent element of a selected text Haven't really perfected this and I think this only works on exact selections but it gives you an idea of how to go around this. The click function checks if the parent element of the current selection has the class 'bold', if so it replaces that element with the original selection again. http://jsfiddle.net/XCb95/4/ jQuery(function($) { $('.embolden').click(function(){ var highlight = window.getSelection(); var span = '<span class="bold">' + highlight + '</span>'; var text = $('.textEditor').html(); var parent = getSelectionParentElement(); if($(parent).hasClass('bold')) { $('.textEditor').html(text.replace(span, highlight)); } else { $('.textEditor').html(text.replace(highlight, span)); } }); }); function getSelectionParentElement() { var parentEl = null, sel; if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { parentEl = sel.getRangeAt(0).commonAncestorContainer; if (parentEl.nodeType != 1) { parentEl = parentEl.parentNode; } } } else if ( (sel = document.selection) && sel.type != "Control") { parentEl = sel.createRange().parentElement(); } return parentEl; } A: Something like this should do the trick: var span = ''; jQuery(function($) { $('.embolden').click(function(){ var highlight = window.getSelection(); if(highlight != ""){ span = '<span class="bold">' + highlight + '</span>'; }else{ highlight = span; span = $('span.bold').html(); } var text = $('.textEditor').html(); $('.textEditor').html(text.replace(highlight, span)); }); }); A: Got it, finally: <!DOCTYPE html> <html> <head> <style type="text/css"> .emphasized { text-decoration: underline; font-weight: bold; font-style: italic; } </style> </head> <body> <button type="button" onclick="applyTagwClass(this);" data-tag="span" data-tagClass="emphasized">Bold</button> <div contenteditable="true" class="textEditor"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In malesuada quis lorem non consequat. Proin diam magna, molestie nec leo non, sodales eleifend nibh. Suspendisse a tellus facilisis, adipiscing dui vitae, rutrum mi. Curabitur aliquet lorem quis augue laoreet feugiat. Nulla at volutpat enim, et facilisis velit. Nulla feugiat quis augue nec sodales. Nulla nunc elit, viverra nec cursus non, gravida ac leo. Proin vehicula tincidunt euismod.</p> <p>Suspendisse non consectetur arcu, ut ultricies nulla. Sed vel sem quis lacus faucibus interdum in sed quam. Nulla ullamcorper bibendum ornare. Proin placerat volutpat dignissim. Ut sit amet tellus enim. Nulla ut convallis quam. Morbi et sollicitudin nibh. Maecenas justo lectus, porta non felis eu, condimentum dictum nisi. Nulla eu nisi neque. Phasellus id sem congue, consequat lorem nec, tincidunt libero.</p> <p>Integer eu elit eu massa placerat venenatis nec in elit. Ut ullamcorper nec mauris et volutpat. Phasellus ullamcorper tristique quam. In pellentesque nisl eget arcu fermentum ornare. Aenean nisl augue, mollis nec tristique a, dapibus quis urna. Vivamus volutpat ullamcorper lectus, et malesuada risus adipiscing nec. Ut nec ligula orci. Morbi sollicitudin nunc tempus, vestibulum arcu nec, feugiat velit. Aenean scelerisque, ligula sed molestie iaculis, massa risus ultrices nisl, et placerat augue libero vitae est. Pellentesque ornare adipiscing massa eleifend fermentum. In fringilla accumsan lectus sit amet aliquam.</p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> function applyTagwClass(self) { var selection = window.getSelection(); if (selection.rangeCount) { var text = selection.toString(); var range = selection.getRangeAt(0); var parent = $(range.startContainer.parentNode); if (range.startOffset > 0 && parent.hasClass(self.attributes['data-tagClass'].value)) { var prefix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(0,selection.anchorOffset) + '</' + self.attributes['data-tag'].value + '>'; var suffix = '<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + parent.html().substr(selection.focusOffset) + '</' + self.attributes['data-tag'].value + '>'; parent.replaceWith(prefix + text + suffix); } else { range.deleteContents(); range.insertNode($('<' + self.attributes['data-tag'].value + ' class="' + self.attributes['data-tagClass'].value + '">' + text + '</' + self.attributes['data-tag'].value + '>')[0]); //Remove all empty elements (deleteContents leaves the HTML in place) $(self.attributes['data-tag'].value + '.' + self.attributes['data-tagClass'].value + ':empty').remove(); } } } </script> </body> </html> You'll notice that I extended the button to have a couple data- attributes. They should be rather self-explanatory. This will also de-apply to subsections of the selected text which are within the currently-targeted element (everything goes by class name). As you can see, I'm using a class which is a combination of things so this gives you more versatility. A: If you are looking to use the keyboard to bold characters, you can use the following (Mac): $(window).keydown(function(e) { if (e.keyCode >= 65 && e.keyCode <= 90) { var char = (e.metaKey ? '⌘-' : '') + String.fromCharCode(e.keyCode) if(char =='⌘-B') { document.execCommand('bold') } } }) Using keyboard to bold character: A: This code goes thru the content of the textEditor and removes all the span tags. It should do the trick. jQuery(function($) { $('.embolden').click(function(){ $('.textEditor span').contents().unwrap(); var highlight = window.getSelection(); var span = '<span class="bold">' + highlight + '</span>'; var text = $('.textEditor').html(); $('.textEditor').html(text.replace(highlight, span)); }); }); A: Modern browsers utilize the execCommand function that allows you to embolden text very easily. It also provides other styles like underline etc. <a href="#" onclick="emboldenFont()">Bold</a> function emboldenFont() { document.execCommand('bold', false, null); } A: check this is it what u wanted ??? using .toggleclass() (to make all text in text editor class bold only)
{ "language": "en", "url": "https://stackoverflow.com/questions/20880271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: In c: Can I copy a whole portion of an array at once, by refering to the pointer to the location of a slot in the array I want to copy from? Hope my question is clear and relavent, new to Pointers... - Can I copy a whole portion of an array at once, by refering to the pointer to the location of the first slot in the array I want to begin copying from? For example - Given an array : A [ 1,2,3,4,5,7,8,3,2,5,1,0,9] - I want to copy only the part of the array from the n'th slot on, into the beginning of the array B [0 0 0 ..... ] (B is of the same length of A). Can I do it at once, using pointers instead of a loop? Something like - switching the pointer to the 1'st slot in B with the pointer to the n'th slot of A, and the n'th slot in B with the last one in A? Thanks a lot on advance! A: That's what memcpy is for. memcpy(B, A + n, (N - n) * sizeof(A[0])); where N is the number of elements in A. If A is really an array (not just a pointer to one), then N can be computed as sizeof(A) / sizeof(A[0]), so the call simplifies to memcpy(B, A + n, sizeof(A) - n * sizeof(A[0])); memcpy lives in <string.h>; its first argument is the destination of the copy, its second the source. (I'm sorry, I don't really follow what kind of pointer trick you have in mind, so I can't comment on that.) A: I think I understand what you're asking. You can use pointers to set up your second array, but here is the problem with doing it that way: int [] primary = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int * secondary = primary + 5; At this point, primary is { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }, and secondary is { 6, 7, 8, 9, 0 }, but the problem is they both point to the same array in memory. So instead of having two independent copies, if you edit any of the elements of 'secondary', they are edited in 'primary' also. secondary[2] = 10; for(int i = 0; i < 10; ++i) cout << primary[i] << ' '; This portion of code would now yield: 1 2 3 4 5 6 7 10 9 0 The correct way to do it would to either be setting up the new array, and looping through copying over the values, or using memcpy(). Edit: //Rotate an array such that the index value is moved to the front of the array null rotateArray( &int original[], int size, int index) { int * secondary = new int[size]; //dynamically allocated array for(int i = 0; i < size; ++i) { secondary[i] = original[(i+index)%size]; } original = secondary; //Move the original array's pointer to the new memory location } Some notes: secondary[i] = original[(i+index)%size]; this is how I rotated the array. Say you had an original array of size 5, and you wanted the fourth element to be the new start (remember, elements are numbered 0-(size-1)): i = 0; secondary[0] = original[(0 + 3)%5]// = original[3] i = 1; secondary[1] = original[(1 + 3)%5]// = original[4] i = 2; secondary[2] = original[(2 + 3)%5]// = original[0] ... The last part of the code: original = secondary; is a little bit questionable, as I don't remember whether or not c++ will try and clean up the used memory once the function is exited. A safer and 100% sure way to do it would be to loop through and copy the secondary array's elements into the original array: for(int i = 0; i < size; ++i) original[i] = secondary[i];
{ "language": "en", "url": "https://stackoverflow.com/questions/13108878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determining column to use in INSERT statement based on data in the table being selected from I need to determine if I should insert data into theDate or theDate2 column based on data in the processDate column from the table being selected from. I am unable to use a column in a CASE statement however (I am getting an error when trying to run the code below), and I can't find a solution to this. How can I do this? processDate is a column from #tableTwo. INSERT INTO tableOne CASE WHEN processDate <> '' THEN + ',' + theDate ELSE + ',' + theDate2 END SELECT sDate FROM #tableTwo A: If both theDate and theDate2 can be determined by the flag processDate then do it in your select rather than in the insert. Assuming that the columns are nullable (as your CASE in the INSERT clause seems to indicate they are mutually exclusive, then I'd be inclined to do something like; INSERT INTO tableOne (theDate, theDate2) SELECT CASE WHEN processDate <> '' THEN sDate ELSE NULL END theDate, CASE WHEN processDate = '' THEN sDate ELSE NULL END theDate2, FROM #tableTwo A: what about two queries which would look like that: INSERT INTO tableOne (theDate) SELECT sDate FROM #tableTwo WHERE processDate <> '' Followed by something like INSERT INTO tableOne (theDate2) SELECT sDate FROM #tableTwo WHERE processDate = '' A: The proper syntax for an insert is insert into table (field1, field2, etc) select field3, field4, etc from somewhere I have no idea if this will work, but you can try: insert into tableOne (case when processDate <> '' then theDate else Date2 end) select sdate from #table2
{ "language": "en", "url": "https://stackoverflow.com/questions/20509936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel models, relationships how to make a innjoin query using Eloquent? Controller code (which isn`t working) $employees = Employee::with('department')->get(); Model:department class Department extends Model { ... /** * Defining Relationships. */ public function employee() { return $this->hasMany('GloboDeals\Employee'); } } Model:employee class Employee extends Model { /** * Defining Relationships. */ .... public function department() { return $this->belongsTo('GloboDeals\Department','departments_id','id'); } the external ids have the name of table_id. I search and search and none of the solutions are working so I guess my code is just blehhh, if anyone could check it out and give me an idea. A: Eloquent will assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention. In each of your models add its primary key like so for Department model: protected $primaryKey = 'department_id'; Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent. In other words, Eloquent will look for the value of the department id column in the department_id column of the employee record. If you would like the relationship to use a value other than id, you may pass a third argument to the belongsTo method specifying your custom key: In your case you are calling department() of your employee model: return $this->belongsTo('GloboDeals\Department', 'departments_id', 'departments_id'); This means the Employee model will eager load the department details where the relation departments_id of departments table = departments_id of the employees table.
{ "language": "en", "url": "https://stackoverflow.com/questions/38612280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to validate Validate NCName in C++ In .NET you have XmlConvert.VerifyNCName XmlConvert.IsNCNameChar etc to validate a NCName How can one do the equivalent in C++ ? A: You can try using the Xerces-C++ library from Apache, more specifically the XMLChar1_1::isValidNCName method. If you're using Visual Studio, you can also use C++/CLI, which will allow you to mix unmanaged C++ with managed C++, in which you'll be able to use the .NET functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/12915333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Yacc - productions for matching functions I am writing a compiler with Yacc and having trouble figuring out how to write productions to match a function. In my language, functions are defined like this: function foo(a, b, c); I created lex patterns to match the word function to FUNC, and any C style name to NAME. Ideally, I would want something like this: FUNC NAME OBRACKET NAME (COMMA NAME)* CBRACKET Which would allow some unknown number of pairs of COMMA NAME in between NAME and CBRACKET. Additionally, how would I know how many it found? A: You might try something like this: funcdecl: FUNC NAME OBRACKET arglist CBRACKET SEMI ; arglist: nonemptyarglist | ; nonemptyarglist: nonemptyarglist COMMA NAME | NAME ; I'd suggest using the grammar to build a syntax tree for your language and then doing whatever you need to the syntax tree after parsing has finished. Bison and yacc have features that make this rather simple; look up %union and %type in the info page. A: After a little experimentation, I found this to work quite well: int argCount; int args[128]; arglist: nonemptyarglist | ; nonemptyarglist: nonemptyarglist COMMA singleArgList | singleArgList { }; singleArgList: REGISTER { args[argCount++] = $1; };
{ "language": "en", "url": "https://stackoverflow.com/questions/13560844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Springfox / Swagger does not resolve polymorphic field I'm having a simple Spring Boot application with one REST endpoint to return a "Job" object, which contains a list of polymorphics, next to other stuff. We go Code First approach and try to create the API models to fit our needs. But the generated Api Doc does not represent our model the in it's full complexity, as it does not resolve the list of polymorphics. The Job object looks like @Data // Lombok Getters and Setters public final class Job { private String foo; private String bar; private List<Condition> conditionList; } Condition is a parent object for a set of different conditions public abstract class Condition { } Two example implementations of a Condition would be @Data public final class Internal extends Condition { private String nodeId; } and @Data public final class Timed extends Condition { private ZonedDateTime timestamp; } The REST controller is stupidly simple: @RestController @RequestMapping("/hello") public class MyController { @GetMapping public ResponseEntity<Job> getJob() { return new ResponseEntity<>(new Job(), HttpStatus.OK); } } Now, when I open the Swagger UI and look at the generated definition, the element conditionList is an empty object {} I tried to use the @JsonSubTypes and @ApiModel on the classed, but there was no difference in the output. I might not have used them correctly, or maybe Swagger is just not able to fulfill the job, or maybe I'm just blind or stupid. How can I get Swagger to include the Subtypes into the generated api doc? A: We "fixed" the problem by changing the structure. So it's more of a workaround. Instead of using a List of polymorphics, we now use a "container" class, which contains each type as it's own type. The Condition object became a "container" or "manager" class, instead of a List. In the Job class, the field is now defined as: private Condition condition; The Condition class itself is now public final class Condition{ private List<Internal> internalConditions; // etc... } And, as example, the Internal lost it's parent type and is now just public final class Internal{ // Logic... } The Swagger generated JSON now looks like this (excerpt): "Job": { "Condition": { "Internal": { } "External": { } //etc... } } A: Useful display of polymorphic responses in Swagger UI with Springfox 2.9.2 seems hard (impossible?). Workaround feels reasonable. OpenAPI 3.0 appears to improve support for polymorphism. To achieve your original goal, I would either * *Wait for Springfox to get Open API 3.0 support (issue 2022 in Springfox Github). Unfortunately, the issue has been open since Sept 2017 and there is no indication of Open API 3.0 support being added soon (in Aug 2019). *Change to Spring REST Docs, perhaps adding the restdocs-api-spec extension to generate Open API 3.0. We have run into similar problems with polymorphism but have not yet attempted to implement a solution based on Spring REST Docs + restdocs-api-spec.
{ "language": "en", "url": "https://stackoverflow.com/questions/55728949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the 'correct' way to include unrelated entities subset in a form? Imagine three entities - Account, Address, Purchase. Account has a OneToMany relationship with Address. A Purchase is related to an Account, but not with an Address - it does however have a text field for the address (this is because addresses can change, I don't want the address directly related). On the users' account page they can add addresses. Whilst logged into the site, a Purchase id is stored in the session and used to retrieve the Purchase details when required. What I want to do on the checkout page is display a list of all the addresses a user currently has in a <select>, allow them to pick one, and update the address in the current Purchase. $account->getAddresses() exists and will show the addresses relevant to the user. I have read http://symfony.com/doc/current/reference/forms/types/collection.html and http://symfony.com/doc/current/cookbook/form/form_collections.html and can't see how to apply it to this situation, although an embedded form isn't really necessary - I don't want to change other details of the Purchase at that stage. So my question is (at least one of): how do I pass the results of $account->getAddresses() to a form type? Or in the form type, should I use an entity field type, and if so, how do I get the custom query_builder to contain the current user in a form type? Or how else should I do this? A: You need to pass the entity in to the Type's constructor and then use it to get the parameter. Class YourType extends AbstractType { private $account; public function __construct($account) { $this->account = $account; } public function buildForm(FormBuilderInterface $builder, array $options) { $accountId = $account->getAccountId(); $builder->add('addressId', 'entity', array('class' => 'YourBundle:Address', 'query_builder' => function(EntityRepository $er) use ($accountId) { return $er->createQueryBuilder('a') ->where('a.accountId = ?1') ->setParameter(1, $accountId))); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/18881566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Money format output and also in the textbox i have here a sample computation, what i want to know is how can it be a money format output. for example 1000+ 1000 =2000 i want to output it as 2,000. also , when typing the value , i want it automatically look a money format. <html> <head> </head> <body> <form name="haha" method="post" > 1:<input type="text" name="num1"> 2:<input type="text" name="num2"> Total:<input type="label" name="total"> <input type="submit" value="add" name="submit"> </html> </form> <? if (isset($_POST['submit'])) { $num1=$_POST['num1']; $num2=$_POST['num2']; $total=$_POST['total']; $total= $num1 + $num2; echo $total; } ?> A: I'm assuming you're looking for number_format or its more advanced brother money_format. This will take care of the server-side for you. As for the client-side, I would advise against making things change while the user's typing. Just let them type in the number how they want. Bonus points if you allow them to type in thousand separators (since you can just strip them out easily in PHP to get the number itself). A: Try number_format $english_format_number = number_format(floatval($total)); echo $english_format_number; A: You need to use javascript for that, when user change the input value you need to call the function to format the value. You have to something like this: $("[name^='num']").change(function(){ var value = $(this).val(); $(this).val(money_format(format, value)); }); Here is the function for monet format : Ref: https://github.com/kvz/phpjs/blob/master/functions/strings/money_format.js function money_format (format, number) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // + input by: daniel airton wermann (http://wermann.com.br) // + bugfixed by: Brett Zamir (http://brett-zamir.me) // - depends on: setlocale // % note 1: This depends on setlocale having the appropriate locale (these examples use 'en_US') // * example 1: money_format('%i', 1234.56); // * returns 1: 'USD 1,234.56' // * example 2: money_format('%14#8.2n', 1234.5678); // * returns 2: ' $ 1,234.57' // * example 3: money_format('%14#8.2n', -1234.5678); // * returns 3: '-$ 1,234.57' // * example 4: money_format('%(14#8.2n', 1234.5678); // * returns 4: ' $ 1,234.57 ' // * example 5: money_format('%(14#8.2n', -1234.5678); // * returns 5: '($ 1,234.57)' // * example 6: money_format('%=014#8.2n', 1234.5678); // * returns 6: ' $000001,234.57' // * example 7: money_format('%=014#8.2n', -1234.5678); // * returns 7: '-$000001,234.57' // * example 8: money_format('%=*14#8.2n', 1234.5678); // * returns 8: ' $*****1,234.57' // * example 9: money_format('%=*14#8.2n', -1234.5678); // * returns 9: '-$*****1,234.57' // * example 10: money_format('%=*^14#8.2n', 1234.5678); // * returns 10: ' $****1234.57' // * example 11: money_format('%=*^14#8.2n', -1234.5678); // * returns 11: ' -$****1234.57' // * example 12: money_format('%=*!14#8.2n', 1234.5678); // * returns 12: ' *****1,234.57' // * example 13: money_format('%=*!14#8.2n', -1234.5678); // * returns 13: '-*****1,234.57' // * example 14: money_format('%i', 3590); // * returns 14: ' USD 3,590.00' // Per PHP behavior, there seems to be no extra padding for sign when there is a positive number, though my // understanding of the description is that there should be padding; need to revisit examples // Helpful info at http://ftp.gnu.org/pub/pub/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_7.html and http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/strfmp.htm if (typeof number !== 'number') { return null; } var regex = /%((=.|[+^(!-])*?)(\d*?)(#(\d+))?(\.(\d+))?([in%])/g; // 1: flags, 3: width, 5: left, 7: right, 8: conversion this.setlocale('LC_ALL', 0); // Ensure the locale data we need is set up var monetary = this.php_js.locales[this.php_js.localeCategories['LC_MONETARY']]['LC_MONETARY']; var doReplace = function (n0, flags, n2, width, n4, left, n6, right, conversion) { var value = '', repl = ''; if (conversion === '%') { // Percent does not seem to be allowed with intervening content return '%'; } var fill = flags && (/=./).test(flags) ? flags.match(/=(.)/)[1] : ' '; // flag: =f (numeric fill) var showCurrSymbol = !flags || flags.indexOf('!') === -1; // flag: ! (suppress currency symbol) width = parseInt(width, 10) || 0; // field width: w (minimum field width) var neg = number < 0; number = number + ''; // Convert to string number = neg ? number.slice(1) : number; // We don't want negative symbol represented here yet var decpos = number.indexOf('.'); var integer = decpos !== -1 ? number.slice(0, decpos) : number; // Get integer portion var fraction = decpos !== -1 ? number.slice(decpos + 1) : ''; // Get decimal portion var _str_splice = function (integerStr, idx, thous_sep) { var integerArr = integerStr.split(''); integerArr.splice(idx, 0, thous_sep); return integerArr.join(''); }; var init_lgth = integer.length; left = parseInt(left, 10); var filler = init_lgth < left; if (filler) { var fillnum = left - init_lgth; integer = new Array(fillnum + 1).join(fill) + integer; } if (flags.indexOf('^') === -1) { // flag: ^ (disable grouping characters (of locale)) // use grouping characters var thous_sep = monetary.mon_thousands_sep; // ',' var mon_grouping = monetary.mon_grouping; // [3] (every 3 digits in U.S.A. locale) if (mon_grouping[0] < integer.length) { for (var i = 0, idx = integer.length; i < mon_grouping.length; i++) { idx -= mon_grouping[i]; // e.g., 3 if (idx <= 0) { break; } if (filler && idx < fillnum) { thous_sep = fill; } integer = _str_splice(integer, idx, thous_sep); } } if (mon_grouping[i - 1] > 0) { // Repeating last grouping (may only be one) until highest portion of integer reached while (idx > mon_grouping[i - 1]) { idx -= mon_grouping[i - 1]; if (filler && idx < fillnum) { thous_sep = fill; } integer = _str_splice(integer, idx, thous_sep); } } } // left, right if (right === '0') { // No decimal or fractional digits value = integer; } else { var dec_pt = monetary.mon_decimal_point; // '.' if (right === '' || right === undefined) { right = conversion === 'i' ? monetary.int_frac_digits : monetary.frac_digits; } right = parseInt(right, 10); if (right === 0) { // Only remove fractional portion if explicitly set to zero digits fraction = ''; dec_pt = ''; } else if (right < fraction.length) { fraction = Math.round(parseFloat(fraction.slice(0, right) + '.' + fraction.substr(right, 1))) + ''; if (right > fraction.length) { fraction = new Array(right - fraction.length + 1).join('0') + fraction; // prepend with 0's } } else if (right > fraction.length) { fraction += new Array(right - fraction.length + 1).join('0'); // pad with 0's } value = integer + dec_pt + fraction; } var symbol = ''; if (showCurrSymbol) { symbol = conversion === 'i' ? monetary.int_curr_symbol : monetary.currency_symbol; // 'i' vs. 'n' ('USD' vs. '$') } var sign_posn = neg ? monetary.n_sign_posn : monetary.p_sign_posn; // 0: no space between curr. symbol and value // 1: space sep. them unless symb. and sign are adjacent then space sep. them from value // 2: space sep. sign and value unless symb. and sign are adjacent then space separates var sep_by_space = neg ? monetary.n_sep_by_space : monetary.p_sep_by_space; // p_cs_precedes, n_cs_precedes // positive currency symbol follows value = 0; precedes value = 1 var cs_precedes = neg ? monetary.n_cs_precedes : monetary.p_cs_precedes; // Assemble symbol/value/sign and possible space as appropriate if (flags.indexOf('(') !== -1) { // flag: parenth. for negative // Fix: unclear on whether and how sep_by_space, sign_posn, or cs_precedes have // an impact here (as they do below), but assuming for now behaves as sign_posn 0 as // far as localized sep_by_space and sign_posn behavior repl = (cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') : '') + value + (!cs_precedes ? (sep_by_space === 1 ? ' ' : '') + symbol : ''); if (neg) { repl = '(' + repl + ')'; } else { repl = ' ' + repl + ' '; } } else { // '+' is default var pos_sign = monetary.positive_sign; // '' var neg_sign = monetary.negative_sign; // '-' var sign = neg ? (neg_sign) : (pos_sign); var otherSign = neg ? (pos_sign) : (neg_sign); var signPadding = ''; if (sign_posn) { // has a sign signPadding = new Array(otherSign.length - sign.length + 1).join(' '); } var valueAndCS = ''; switch (sign_posn) { // 0: parentheses surround value and curr. symbol; // 1: sign precedes them; // 2: sign follows them; // 3: sign immed. precedes curr. symbol; (but may be space between) // 4: sign immed. succeeds curr. symbol; (but may be space between) case 0: valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol; repl = '(' + valueAndCS + ')'; break; case 1: valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol; repl = signPadding + sign + (sep_by_space === 2 ? ' ' : '') + valueAndCS; break; case 2: valueAndCS = cs_precedes ? symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol; repl = valueAndCS + (sep_by_space === 2 ? ' ' : '') + sign + signPadding; break; case 3: repl = cs_precedes ? signPadding + sign + (sep_by_space === 2 ? ' ' : '') + symbol + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + sign + signPadding + (sep_by_space === 2 ? ' ' : '') + symbol; break; case 4: repl = cs_precedes ? symbol + (sep_by_space === 2 ? ' ' : '') + signPadding + sign + (sep_by_space === 1 ? ' ' : '') + value : value + (sep_by_space === 1 ? ' ' : '') + symbol + (sep_by_space === 2 ? ' ' : '') + sign + signPadding; break; } } var padding = width - repl.length; if (padding > 0) { padding = new Array(padding + 1).join(' '); // Fix: How does p_sep_by_space affect the count if there is a space? Included in count presumably? if (flags.indexOf('-') !== -1) { // left-justified (pad to right) repl += padding; } else { // right-justified (pad to left) repl = padding + repl; } } return repl; }; return format.replace(regex, doReplace); }
{ "language": "en", "url": "https://stackoverflow.com/questions/15287923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Caliburn.Micro No target found for method I'm using Caliburn.Micro for my WP7 project and I keep getting this strange error for some of my pages. I can't reproduce it myself but it very often appears in Bugsense logs. This is how I use it. XAML: cal:Message.Attach="[Event Loaded] = [Action Init()]" And in my ViewModel: public async Task Init() {...} Or on other pages just public void Init() {...} This is stacktrace from Bugsense: 0 System.Exception: No target found for method Init. 1 at Caliburn.Micro.ActionMessage.Invoke(Object eventArgs) 2 at System.Windows.Interactivity.TriggerAction.CallInvoke(Object parameter) 3 at System.Windows.Interactivity.TriggerBase.InvokeActions(Object parameter) 4 at System.Windows.Interactivity.EventTriggerBase.OnEvent(EventArgs eventArgs) 5 at System.Windows.Interactivity.EventTriggerBase.OnEventImpl(Object sender, EventArgs eventArgs) 6 at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) 7 at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName) Any ideas on how I can determine what's wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/26297384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load a Bitmap into VB 6 PictureBox I wrote a library which has a function call that returns a System.Drawing.Bitmap. Everything works great and I can access it just fine from a C# WPF application. However, now I need to make it work with a VB 6 application and for the life of me I can`t get it to work. I have a VB6 picturebox (note: this could be changed to an image control if necessary; we just need the image to display on the screen somehow) Right now I have tried the following unsuccessfully: Set Form1.PictureBox1.Image = myImage <-- This causes invalid use of property on 'Form1.PictureBox1.Image' Form1.PictureBox1.Image = myImage <-- This causes invalid use of property on 'Form1.PictureBox1.Image' Form1.PictureBox1.Picture = myImage <-- This cause 'type mismatch' Help please! I don`t know VB at all let alone VB 6.
{ "language": "en", "url": "https://stackoverflow.com/questions/33784902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parsing a HTML file in Java I am currently in the process of developing an application that will request some information from Websites. What I'm looking to do is parse the HTML files through a connection online. I was just wondering, by parsing the Website will it put any strain on the server, will it have to download any excess information or will it simply connect to the site as I would do through my browser and then scan the source? If this is putting extra strain on the Website then I'm going to have to make a special request to some of the companies I'm scanning. However if not then I have the permission to do this. I hope this made some sort of sense. Kind regards, Jamie. A: No extra strain on other people servers. The server will get your simple HTML GET request, it won't even be aware that you're then parsing the page/html. Have you checked this: JSoup? A: Consider doing the parsing and the crawling/scraping in separate steps. If you do that, you can probably use an existing open-source crawler such as crawler4j that already has support for politeness delays, robots.txt, etc. If you just blindly go grabbing content from somebody's site with a bot, the odds are good that you're going to get banned (or worse, if the admin is feeling particularly vindictive or creative that day). A: Depends on the website. If you do this to Google then most likely you will be on a hold for a day. If you parse Wikipedia, (which I have done myself) it won't be a problem because its already a huge, huge website. If you want to do it the right way, first respect robots.txt, then try to scatter your requests. Also try to do it when the traffic is low. Like around midnight and not at 8AM or 6PM when people get to computers. A: Besides Hank Gay's recommendation, I can only suggest that you can also re-use some open-source HTML parser, such as Jsoup, for parsing/processing the downloaded HTML files. A: You could use htmlunit. It gives you virtual gui less browser. A: Your Java program hitting other people's server to download the content of a URL won't put any more strain on the server than a web browser doing so-- essentially they're precisely the same operation. In fact, you probably put less strain on them, because your program probably won't be bothered about downloading images, scripts etc that a web browser would. BUT: * *if you start bombarding a server of a company with moderate resources with downloads or start exhibiting obvious "robot" patterns (e.g. downloading precisely every second), they'll probably block you; so put some sensible constraints on what you do (e.g. every consecutive download to the same server happens at random intervals of between 10 and 20 seconds); *when you make your request, you probably want to set the "referer" request header either to mimic an actual browser, or to be open about what it is (invent a name for your "robot", create a page explaining what it does and include a URL to that page in the referer header)-- many server owners will let through legitimate, well-behaved robots, but block "suspicious" ones where it's not clear what they're doing; *on a similar note, if you're doing things "legally", don't fetch pages that the site's "robot.txt" files prohibits you from fetching. Of course, within some bounds of "non-malicious activity", in general it's perfectly legal for you to make whatever request you want whenever you want to whatever server. But equally, that server has a right to serve or deny you that page. So to prevent yourself from being blocked, one way or another, you need to either get approval from the server owners, or "keep a low profile" in your requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/6537321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show chaing slider value in console I have a slider and span which display the value of the changing value like this: var slider = document.getElementById("myRange"); var output = document.getElementById("dynamicSet"); output.innerHTML = slider.value; // Display the default slider value // Update the current slider value (each time you drag the slider handle) let update = () => output.innerHTML = slider.value; slider.addEventListener('input', update); update(); const setAmount = document.getElementById("dynamicSet").innerHTML; console.log(setAmount); <div class="slidecontainer"> <p>Aantal sets: <span id="dynamicSet"></span></p> <input type="range" min="1" max="10" value="50" class="slider" id="myRange"> </div> The webpage displays the changing value which works great! However when I try to console log it, it just shows the initial value the slider is at. I am trying to push this value to a DB (with a clikc of a submit button) but I noticed the value stayed the same as in the initial when opening the page: I need the back end value to change as well. How can do this? i thought that the even listener already took care of this.. A: please check this, hope it will work :-) var slider = document.getElementById("myRange"); var output = document.getElementById("dynamicSet"); var isShow = true output.innerHTML = slider.value update=()=>{ output.innerHTML = slider.value; // Display the default slider value console.log(slider.value) } // Update the current slider value (each time you drag the slider handle) //let update = () => output.innerHTML = slider.value; slider.addEventListener('input', update); <div class="slidecontainer"> <p>Aantal sets: <span id="dynamicSet"></span></p> <input type="range" min="1" max="10" value="50" class="slider" id="myRange"> </div> A: you can try this let update = () => { output.innerHTML = slider.value; console.log(slider.value) }
{ "language": "en", "url": "https://stackoverflow.com/questions/61076647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monte-Carlo Simulation for the sum of die I am very new to programming so I apologise in advance for my lack of knowledge. I want to find the probability of obtaining the sum k when throwing m die. I am not looking for a direct answer, I just want to ask if I am on the right track and what I can improve. I begin with a function that calculates the sum of an array of m die: function dicesum(m) j = rand((1:6), m) sum(j) end Now I am trying specific values to see if I can find a pattern (but without much luck). I have tried m = 2 (two die). What I am trying to do is to write a function which checks whether the sum of the two die is k and if it is, it calculates the probability. My attempt is very naive but I am hoping someone can point me in the right direction: m = 2 x, y = rand(1:6), rand(1:6) z = x+y if z == dicesum(m) Probability = ??/6^m I want to somehow find the number of 'elements' in dicesum(2) in order to calculate the probability. For example, consider the case when dicesum(2) = 8. With two die, the possible outcomes are (2,6),(6,2), (5,3), (3,5), (4,4), (4,4). The probability being (2/36)*3. I understand that the general case is far more complicated but I just want an idea of how to being this problem. Thanks in advance for any help. A: If I understand correctly, you want to use simulation to approximate the probability of obtaining a sum of k when roll m dice. What I recommend is creating a function that will take k and m as arguments and repeat the simulation a large number of times. The following might help you get started: function Simulate(m,k,Nsim=10^4) #Initialize the counter cnt=0 #Repeat the experiment Nsim times for sim in 1:Nsim #Simulate roll of m dice s = sum(rand(1:6,m)) #Increment counter if sum matches k if s == k cnt += 1 end end #Return the estimated probability return cnt/Nsim end prob = Simulate(3,4) The estimate is approximately .0131. A: You can also perform your simulation in a vectorized style as shown below. Its less efficient in terms of memory allocation because it creates a vector s of length Nsim, whereas the loop code uses a single integer to count, cnt. Sometimes unnecessary memory allocation can cause performance issues. In this case, it turns out that the vectorized code is about twice as fast. Usually, loops are a bit faster. Someone more familiar with the internals of Julia might be able to offer an explanation. function Simulate1(m,k,Nsim=10^4) #Simulate roll of m dice Nsim times s = sum(rand(1:6,Nsim,m),2) #Relative frequency of matches prob = mean(s .== k) return prob end
{ "language": "en", "url": "https://stackoverflow.com/questions/48480722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i add transitions to my current JavaScript code? I am currently working on a website project, and i have put together this code (JavaScript) for a slider using an online YouTube tutorial. <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <script type="text/javascript"> var imagecount = 1; var total = 2; function slide (x){ var Image = document.getElementById('img'); imagecount = imagecount + x; if(imagecount > total){imagecount = 1;} if(imagecount < 1){imagecount = total;} Image.src = "images/img"+ imagecount +".png"; } window.setInterval(function slideA () { var Image = document.getElementById('img'); imagecount = imagecount + 1; if(imagecount > total){ imagecount = 1;} if(imagecount < 1){ imagecount = total;} Image.src = "images/img"+ imagecount +".png"; },5000); </script> </head> <title></title> <body onload="slideA()" > <div id="container"> <div id="header"> <div id="logo"> <img src="big states.png" alt="Logo"> </div> </div> <div id="nav"> <ul> <li><a class="active" href="#home">HOME</a></li> <li><a href="#menu">MENU</a></li> <li><a href="#about">ABOUT</a></li> <li><a href="#gallery">GALLERY</a></li> <li><a href="#reviews">REVIEWS</a></li> <li><a href="#contact">CONTACT</a></li> </ul> </div> </div> <div id="bgimg"> <img src="sliderbackground.jpg"> </div> <div class="slidercontainer"> <img src="images/img1.png" id="img"> <div id="arrow-right"><img href="#" onclick="slide(1)" src="arrow-right.png" class="right" onmouseover="this.src='right-hover.png';" onmouseout="this.src='arrow-right.png';" /> </div> <div id="arrow-left"><img href="#" onclick="slide(-1)" src="arrow-left.png" class="left" onmouseover="this.src='left-hover.png';" onmouseout="this.src='arrow-left.png';" /> </div> </div> </body> </html> However the tutorial did not show how to add transitions into the slider and that is what i need help on. There are two transition effects i am looking for which are: * *OnLoad the image should fade in. *The image should swipe left when changing. A: Take a look at css transitions and/or animations. You could just update the css in your Javascript code like this: CSS #img { /* Initialize with 0% opacity (invisible) */ opacity: 0%; /* Use prefix for cross browser compatibility */ transition: opacity 1s; -o-transition: opacity 1s; -moz-transition: opacity 1s; -webkit-transition: opacity 1s; } Javascript Image.onload = function(){ this.style.opacity = "100%"; } You can use the same technique for swiping with the left property with a relative position in CSS. Adding it to the code var imagecount = 1; var total = 2; function slide (x){ var Image = document.getElementById('img'); imagecount = imagecount + x; if(imagecount > total){imagecount = 1;} if(imagecount < 1){imagecount = total;} Image.src = "images/img"+ imagecount +".png"; Image.style.opacity = "0%"; // Reset the opacity to 0% when reloading the image ! } window.setInterval(function slideA () { var Image = document.getElementById('img'); imagecount = imagecount + 1; if(imagecount > total){ imagecount = 1;} if(imagecount < 1){ imagecount = total;} Image.src = "images/img"+ imagecount +".png"; Image.style.opacity = "0%"; // Reset the opacity to 0% when reloading the image ! },5000); Then simply add it in the html node: <img src="images/img1.png" id="img" onload="this.style.opacity = '100%'">
{ "language": "en", "url": "https://stackoverflow.com/questions/35928732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: AWS ElasticSearch Service throws 403 forbidden on document insert I am trying to upload data into AWS ElasticSearch using hive query. The Intermediate table used within Hive query has following structure. CREATE TABLE uid_taxonomy_1_day_es( UID String ,VISITS INT ,TAXONOMY_LABEL_1 INT ,TAXONOMY_LABEL_2 INT ,TAXONOMY_LABEL_3 INT ,DAY_OF_YEAR INT) STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler' TBLPROPERTIES('es.nodes' = 'https://search-cust-360-view- 6cj2j4mcytbtrpodzffnh3uadi.us-east-1.es.amazonaws.com', 'es.port' = '443', 'es.index.auto.create' = 'false', 'es.batch.size.entries' = '1000', 'es.batch.write.retry.count' = '10000', 'es.batch.write.retry.wait' = '10s', 'es.batch.write.refresh' = 'false','es.nodes.discovery' = 'false','es.nodes.client.only' = 'false', 'es.resource' = 'urltaxonomy/uids', 'es.query' = '?q=*', 'es.nodes.wan.only' = 'true'); The actual load query takes around half hour in loading the data. And so in between at some random record it will throw 403 forbidden error. Here is the stacktrace. Caused by: org.elasticsearch.hadoop.rest.EsHadoopInvalidRequest: [HEAD] on [urltaxonomy] failed; server[https://search-cust-360-view-6cj2j4mcytbtrpodzffnh3uadi.us-east-1.es.amazonaws.com:443] returned [403|Forbidden:] at org.elasticsearch.hadoop.rest.RestClient.checkResponse(RestClient.java:505) at org.elasticsearch.hadoop.rest.RestClient.executeNotFoundAllowed(RestClient.java:476) at org.elasticsearch.hadoop.rest.RestClient.exists(RestClient.java:537) at org.elasticsearch.hadoop.rest.RestClient.touch(RestClient.java:543) at org.elasticsearch.hadoop.rest.RestRepository.touch(RestRepository.java:412) at org.elasticsearch.hadoop.rest.RestService.initSingleIndex(RestService.java:606) at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:594) at org.elasticsearch.hadoop.mr.EsOutputFormat$EsRecordWriter.init(EsOutputFormat.java:173) The error happens only intermittently by which mean if i try to insert that failed record, it works fine. I am thinking its some thing to do with my intermediate table structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/44299980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firebase Cohorts in BigQuery I am trying to replicate Firebase Cohorts using BigQuery. I tried the query from this post: Firebase exported to BigQuery: retention cohorts query, but the results I get don't make much sense. I manage to get the users for period_lag 0 similar to what I can see in Firebase, however, the rest of the numbers don't look right: Results: There is one of the period_lag missing (only see 0,1 and 3 -> no 2) and the user counts for each lag period don't look right either! I would expect to see something like that: Firebase Cohort: I'm pretty sure that the issue is in how I replaced the parameters in the original query with those from Firebase. Here are the bits that I have updated in the original query: #standardSQL WITH activities AS ( SELECT answers.user_dim.app_info.app_instance_id AS id, FORMAT_DATE('%Y-%m', DATE(TIMESTAMP_MICROS(answers.user_dim.first_open_timestamp_micros))) AS period FROM `dataset.app_events_*` AS answers JOIN `dataset.app_events_*` AS questions ON questions.user_dim.app_info.app_instance_id = answers.user_dim.app_info.app_instance_id -- WHERE CONCAT('|', questions.tags, '|') LIKE '%|google-bigquery|%' (...) WHERE cohorts_size.cohort >= FORMAT_DATE('%Y-%m', DATE('2017-11-01')) ORDER BY cohort, period_lag, period_label So I'm using user_dim.first_open_timestamp_micros instead of create_date and user_dim.app_info.app_instance_id instead of id and parent_id. Any idea what I'm doing wrong? A: I think there is a misunderstanding in the concept of how and which data to retrieve into the activities table. Let me state the differences between the case presented in the other StackOverflow question you linked, and the case you are trying to reproduce: * *In the other question, answers.creation_date refers to a date value that is not fix, and can have different values for a single user. I mean, the same user can post two different answers in two different dates, that way, you will end up with two activities entries like: {[ID:user1, date:2018-01],[ID:user1, date:2018-02],[ID:user2, date:2018-01]}. *In your question, the use of answers.user_dim.first_open_timestamp_micros refers to a date value that is fixed in the past, because as stated in the documentation, that variable refers to The time (in microseconds) at which the user first opened the app. That value is unique, and therefore, for each user you will only have one activities entry, like:{[ID:user1, date:2018-01],[ID:user2, date:2018-02],[ID:user3, date:2018-01]}. I think that is the reason why you are not getting information about the lagged retention of users, because you are not recording each time a user accesses the application, but only the first time they did. Instead of using answers.user_dim.first_open_timestamp_micros, you should look for another value from the ones available in the documentation link I shared before, possibly event_dim.date or event_dim.timestamp_micros, although you will have to take into account that these fields refer to an event and not to a user, so you should do some pre-processing first. For testing purposes, you can use some of the publicly available BigQuery exports for Firebase. Finally, as a side note, it is pointless to JOIN a table with itself, so regarding your edited Standard SQL query, it should better be: #standardSQL WITH activities AS ( SELECT answers.user_dim.app_info.app_instance_id AS id, FORMAT_DATE('%Y-%m', DATE(TIMESTAMP_MICROS(answers.user_dim.first_open_timestamp_micros))) AS period FROM `dataset.app_events_*` AS answers GROUP BY id, period
{ "language": "en", "url": "https://stackoverflow.com/questions/48731113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Json object in post not recognized as object in web api I have an angular client and want to execute a get request to my web api backend to get a list of items from the underlying Dapper Db Wrapper. Dapper allows me to pass in parameters as an anonymous object which would in csharp look like this: connection.GetList<T>(new {myParam1:"a", myParam2: true}); What I want to achieve is, to create this parameter object in my angular frontend and pass it in a post request to the server which would then pass it on to the GetList function. The problem here is that the web api does not deserialize it as an (anonymous) object, but rather and IEnumerable of JTokens? My web api signature is this: public async Task<IHttpActionResult> MyFunction([FromBody]dynamic whereCond) I have also tried to pass the object as string wrapped in an outer object like so (angular client): this.migController.MigrationGetMigrationReports({whereCond: JSON.stringify({NotMigrated: true, MissingTargetFiles: 0})}) and then on the server I manually deserialize it as JObject: string obj = whereCond.whereCond; dynamic pObj = JObject.Parse(obj); But this results in the exact same result: pObj is an IEnumerable and therefore I get an error message from the GetList call: An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context can anybody help? A: The answer to my question turned out rather simple: dynamic pObj = JObject.Parse(obj).ToObject<ExpandoObject>(); I had to cast it as ExpandoObject not just dynamic. @Tsahi: this is not a design problem. My intention was to provide the server with parameters (filter) which is a quite common task for a client to reduce the dataset to be transferred. We could debate a standard way how to provide these parameters, however. In my special case the most practical way is the anonymous object.
{ "language": "en", "url": "https://stackoverflow.com/questions/69296360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Call C# function from asp.net Good morning, I have the following asp Image and would like to add the on mouse over event, as follow: <asp:Image ID="MapImage" runat="server" Height="601px" Width="469px" OnMouseOver="OnMouseOverMap"/> I have also added the following method on the C# code: protected void OnMouseOverMap(object sender, EventArgs e) { int i = 9; } I also have created the same method without the parameters but I cannot manage to call that C# function. Can somebody help me with this issue?, How can I do to call the C# function from the ASP code. Cheers! A: There is no OnMouseOver server-side event on asp:Image object. What you can do you can write js function called on client-side onmouseover event and inside that function trigger click on hidden button or you can change Image to ImageButton and trigger click on that image. <asp:Image ID="MapImage" runat="server" Height="601px" Width="469px" onmouseover="javascript:foo()"/> <asp:Button ID="Button1" runat="server" style="display:none" OnClick="OnMouseOverMap" /> And in js function: function foo() { document.getElementById('<%= Button1.ClientID %>').click(); } A: I am pretty sure that you are supposed to insert javascript code there and not a "code behind event handler reference". See ASP NET image onmouseover not working for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/26176769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Does canvas drawing work in Ionic 2? I am currently using a html5 canvas and by using ionic 2 (tap)="markPoint($event)" on the canvas in html, I am getting the position of the tap event. Below is the function which should place the mark: public markPoint(event) { var position = event.center; let ctx = this.canvas.getContext('2d'); ctx.beginPath(); ctx.arc(position.x, position.y, 20, 0, 2 * Math.PI); ctx.fillStyle = '#00DD00'; ctx.fill(); } I am setting the canvas like so, where canvas is the id set in the html: this.canvas = document.getElementById('canvas'); I don't see an issue with this code, however I am also not sure whether or not this is the best way to make marks within an application in ionic 2. Do you know if this should work, and if not why? Also if there are any better ways it would be awesome to here about them. A: First of all we have to make more typescript<6> friendly. It's not enough just to get the canvas object like another HTML element using the id. In this case we should help a little, so my first change will be: this.canvas = document.getElementById('canvas'); FOR => this.canvas = <HTMLCanvasElement>document.getElementById('canvas'); Then your function will look something like this: public markPoint(event) { var position = event.center; let ctx: CanvasRenderingContext2D = this.canvas.getContext("2d"); ctx.beginPath(); ctx.arc(position.x, position.y, 20, 0, 2 * Math.PI); ctx.fillStyle = '#00DD00'; ctx.fill(); } Hope this help.
{ "language": "en", "url": "https://stackoverflow.com/questions/37911266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: can't catch adal:loginSuccess when not using popup I have an angularjs SPA with ui.router. in my module config I have: $locationProvider.html5Mode(true).hashPrefix('!'); $urlRouterProvider.otherwise('/'); $stateProvider .state('welcome', { url: '/', template: '<div><button type=\"button\" class=\"btn btn-primary\" ui-sref=\"login\"><i class=\"fa fa-sign-in\"></i>&nbsp;&nbsp;Login</button></div>', }) .state('login', { url: '/login', template: '<h4> logging in ... </h4>', controller: 'LoginController', controllerAs: 'vm', requireADLogin: true }) .state('loggedin', { url: '/loggedin', templateUrl: '/app/logged-in.html', requireADLogin: true }) .state('logout', { url: '/logout', template: '<h4> logging out ... </h4>', controller: 'LogoutController' }) ; adalProvider.init( { instance: 'https://login.microsoftonline.com/', tenant: 'mytenant.onmicrosoft.com', clientId: 'myappid', extraQueryParameter: 'nux=1', popUp: true, cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost. }, $httpProvider ); in LoginController: function loginController($rootScope, $state, adalService) { /* jshint validthis:true */ var vm = this; vm.title = 'login'; vm.activate = activate; activate(); function activate() { adalService.login(); } $rootScope.$on('adal:loginSuccess', function (event, token) { console.log('loggedin'); $state.go('loggedin'); }); } if I remove the popUp setting, I can't catch the adal:loginSuccess and so I always get back to default state (welcome screen). Also, I know I can set the redirectUri, but I'm not sure how to do it. I've tried with http://myappurl/loggedin, trying to trigger the loggedin state, but it doesn't work. Thanks PS: template for welcome state is inline because for an unknown reason, if I use templateUrl, it throws an error (before introducing adal, it was working fine) A: I am trying to reproduce the issue, however failed. Here is the script which works well for your reference: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <base href="/"> <title></title> <script src="node_modules\angular\angular.js"></script> <script src="node_modules\adal-angular\lib\adal-angular.js"></script> <script src="node_modules\adal-angular\lib\adal.js"></script> <script src="node_modules\angular-ui-router\release\angular-ui-router.js"></script> <script src="node_modules\angular-route\angular-route.js"></script> </head> <body> <div ng-app="myApp"> <div ng-controller="LoginController"> <ul class="nav navbar-nav navbar-right"> <li ng-show="userInfo.isAuthenticated"><a class="btn btn-link" ng-click="logout()">Logout</a></li> <li ng-hide="userInfo.isAuthenticated" ><a class="btn btn-link" ng-click="login()">Login</a></li> <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> <div ui-view></div> </ul> </div> </div> <script> var myApp = angular.module('myApp', ['AdalAngular', 'ui.router', 'ngRoute']) .config(['$httpProvider', 'adalAuthenticationServiceProvider', '$stateProvider', '$routeProvider','$locationProvider','$urlRouterProvider', function ($httpProvider, adalProvider, $stateProvider, $routeProvider,$locationProvider,$urlRouterProvider) { $locationProvider.html5Mode(true,false).hashPrefix('!'); $stateProvider.state("home",{ template: "<h1>HELLO!</h1>" }).state("about",{ templateUrl: '/app/about.html', requireADLogin: true }) adalProvider.init( { instance: 'https://login.microsoftonline.com/', tenant: '', clientId: '', extraQueryParameter: 'nux=1', popUp:true }, $httpProvider ); }]) myApp.controller('LoginController', ['$rootScope','$scope', '$http', 'adalAuthenticationService', '$location','$stateParams','$state', function ($rootScope,$scope, $http, adalService, $location, $stateParams,$state) { $scope.login = function () { adalService.login(); }; $scope.logout = function () { adalService.logOut(); }; $rootScope.$on('adal:loginSuccess', function (event, token) { console.log('loggedin'); $state.go('about'); }); }]); </script> </body> </html> I used the latest version of adal-angular library(v1.0.14). This code sample will go to the about state after login with the popup page. Please let me know if the code works. And if you still have the problem, would you mind sharing with us a demo which could run?
{ "language": "en", "url": "https://stackoverflow.com/questions/42996623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: REACT: How to modify styles from another component The page of my site are build with these components: <Header /> <Routes /> <Footer /> Obviusly, Header and Footer for all the pages are always the same, but content loaded from Routes is not equal for each page. Ok, I make click over an option of the meny which is in Header component. I go to the page and the name of the option of the menu is correctly underlined. For example, I'm at home and click over FAQS, I go to FAQS page and FAQS option is underlined. But, I can go to whatever page from Routes or Footer component. For example, in Footer component I've got an option to go to FAQS page. If I click over this option, I go to FAQS page, but the style of FAQS option in the menu is not updated. I have checked that in this case are not called methods like componentDidMount or componentDidUpdate. Therefore, how can I update always the options of the menu which are in Header component? Edit I: header.js file import React, { Component } from "react"; import {Row, Col} from "react-bootstrap"; import "bootstrap/dist/css/bootstrap.min.css"; import { NavLink } from "react-router-dom"; import "../css/header.css"; import logo from "../images/logo.png"; export class Header extends Component{ constructor(props){ super(props); this.state = { option1: String(window.location).endsWith("/faqs"), option2: String(window.location).endsWith("/about"), option3: String(window.location).endsWith("/login") } this.handleClick = this.handleClick.bind(this); } componentDidMount(){ window.scrollTo(0, 0); console.log("Header.js(ComponentDidMount): Component cargado correctamente!!!"); } componentDidUpdate(){ window.scrollTo(0, 0); console.log("Header.js(componentDidUpdate): Component cargado correctamente!!!"); } removeUnderline(){ this.setState({ option1: false, option2: false, option3: false }) } handleClick(event){ this.removeUnderline(); if (event.target.id !== "logo"){ this.setState({ option1: event.target.id === "option1", option2: event.target.id === "option2", option3: event.target.id === "option3" }) } } render(){ return( <header style = {{width: 100 + "%"}}> <Row style = {{margin: 0}}> <Col md = {6} style = {{textAlign: "left"}}> <NavLink to="/" onClick = {this.handleClick}> <img id = "logo" src = {logo} alt = "Breaded" /> </NavLink> </Col> <Col md = {6} style = {{textAlign: "right", paddingTop: 25 + "px", paddingRight: 20 + "px"}}> <NavLink to="/faqs" style = {{textDecoration: (this.state.option1) ? "underline" : "none", color: "#000000"}}> <span id = "option1" onClick = {this.handleClick} className = "option-menu">FAQS</span> </NavLink>&nbsp;|&nbsp; <NavLink to="/about" style = {{textDecoration: (this.state.option2) ? "underline" : "none", color: "#000000"}}> <span id = "option2" onClick = {this.handleClick} className = "option-menu">About us</span> </NavLink>&nbsp;|&nbsp; <NavLink to="/login" style = {{textDecoration: (this.state.option3) ? "underline" : "none", color: "#000000"}}> <span id = "option3" onClick = {this.handleClick} className = "option-menu">Login</span> </NavLink> </Col> </Row> </header> ) } } footer.js file import React from "react"; import {Row, Col} from "react-bootstrap"; import "bootstrap/dist/css/bootstrap.min.css"; import InstagramIcon from '@material-ui/icons/Instagram'; import FaceboookIcon from '@material-ui/icons/Facebook'; import {NavLink} from "react-router-dom"; export const Footer = () => { return( <footer style = {{width: 100 + "%", fontSize: 12 + "pt"}}> <Row style = {{margin: 0, textAlign: "center", marginTop: 75 + "px"}}> <Col md = {12}> <InstagramIcon style = {{fontSize: 28 + "px"}} /> <FaceboookIcon style = {{fontSize: 28 + "px"}} /> </Col> </Row> <Row style = {{margin: 0, textAlign: "center", marginTop: 15 + "px", fontWeight: "bold"}}> <Col md = {2}><NavLink to="/login" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>Login</NavLink></Col> <Col md = {2}><NavLink to="/contactus" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>Contact us</NavLink></Col> <Col md = {4}><NavLink to="/about" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>About us</NavLink></Col> <Col md = {2}><NavLink to="/faqs" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>FAQ</NavLink></Col> <Col md = {2}><NavLink to="/privacy" style = {{fontSize: 12 + "pt", color: "#000000", textDecoration: "none"}}>Privacy Policy</NavLink></Col> </Row> <Row style = {{marginTop: 50 + "px", marginBottom: 50 + "px"}}> <Col md = {12} style = {{fontSize: 10 + "pt"}}>@Copyright 2020 Breaded</Col> </Row> </footer> ) }; Edit II: Router are wrapping to each component: Header, Routes and Footer export const Container = () => { return( <div> <Router> <Header /> <Routes /> <Footer /> </Router> </div> ) } routes.js import React from "react"; import { Home } from "./pages/home/home"; import { About } from "./pages/about"; import FAQ from "./pages/faq/faq"; import { Plans } from "./pages/plans/plans"; import { P404 } from "./pages/notfound"; import { Switch, Route, } from "react-router-dom"; export const Routes = () => { return( <Switch> <Route exact path="/" component={Home} /> <Route exact path="/about" component={About} /> <Route exact path="/faqs" component={FAQ} /> <Route exact path="/plans" component={Plans} /> <Route component={P404} /> </Switch> ) } What am I doing wrong? A: The way you are applying your css text effects is not ideal. It works in header, but requires a ton of unnecessary logic that is not present in your Footer. And copying all that code would be a big violation of DRY. But even better than abstracting the logic and applying to both components, react router has activeClassName and activeStyle that you can use to style active NavLinks. Just use them similarly in both Header and Footer. Using activeClassName and showing only the parts of the code you need here: // Header.js <Col md = {6} style = {{textAlign: "left"}}> <NavLink to="/" onClick = {this.handleClick}> <img id = "logo" src = {logo} alt = "Breaded" /> </NavLink> </Col> <Col md = {6} style = {...}> <NavLink to="/faqs" activeClassName="active-nav-link"> <span ... >FAQS</span> </NavLink>&nbsp;|&nbsp; <NavLink to="/about" activeClassName="active-nav-link"> <span ... >About us</span> </NavLink>&nbsp;|&nbsp; <NavLink to="/login" activeClassName="active-nav-link"> <span ... >Login</span> </NavLink> </Col> You can do the same in Footer: // Footer.js <Col md = {2}> <NavLink to="/login" activeClassName="active-nav-link"> Login </NavLink> </Col> <Col md = {2}> <NavLink to="/contactus" activeClassName="active-nav-link"> Contact us </NavLink> </Col> <Col md = {4}> <NavLink to="/about" activeClassName="active-nav-link"> About us </NavLink> </Col> <Col md = {2}> <NavLink to="/faqs" activeClassName="active-nav-link"> FAQ </NavLink> </Col> <Col md = {2}> <NavLink to="/privacy" activeClassName="active-nav-link"> Privacy Policy </NavLink> </Col> And then in some associated css file, you can say: .active-nav-link { text-decoration: underline } I don't remember if the NavLink returns an <a> or an <li> with a nested <a>, so that might affect how you write your css. You can also use activeStyle and do inline styles as an object, as you had been doing in your original code. Either way will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/63104234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: boost::asio::async_read texutal stop condition? I'm writing a server with Boost, something pretty simple - accept an XML message, process, reply. But I'm running into trouble at telling it when to stop reading. This is what I have right now: (_index is the buffer into which the data is read) std::size_t tcp_connection::completion_condition(const boost::system::error_code& error, std::size_t bytes_transferred) { int ret = -1; std::istream is(&_index); std::string s; is >> s; if (s.find("</end_tag>") != std::string.npos) ret = 0; return ret; } void tcp_connection::start() { // Get index from server boost::asio::async_read(_socket, _index, &(tcp_connection::completion_condition), boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } This doesn't compile, since I have to define completion_condition as static to pass it to async_read; and I can't define _index as static since (obviously) I need it to be specific to the class. Is there some other way to give parameters to completion_condition? How do I get it to recognize the ending tag and call the reading handler? A: You can pass pointers to member functions. The syntax for doing it with C++ is tricky, but boost::bind hides it and makes it fairly easy to do. An example would be making completion_condition non-static and passing it to async_read as such:boost::bind(&tcp_connection::completion_condition, this, _1, _2) &tcp_connection::completion_condition is a pointer to the function. this is the object of type tcp_connection to call the function on. _1 and _2 are placeholders; they will be replaced with the two parameters the function is called with.
{ "language": "en", "url": "https://stackoverflow.com/questions/5258793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get data and sort from MySQL two tables I have table_1 and table_2 and they are the same structure, but different data. Need to get all the data from that tables in sort of create_date and no matter from which table (it can be 1 row from table_1, 3 rows from table_2 and then again from table_1). Is it possible? How? or shout I get two queries and then sort by date with PHP? EDIT: Sorry for first part, I thought I can do it from there, but seems like i can't :/ i have very big query like this SELECT table_1.id, table_1.created, table_1.qty, table_1.comments, table_1.last_update, table_7.firstname, SUBSTRING(table_7.lastname, 1, 1) AS lastname, table_8.title country, table_3.value AS sim, table_1.offer_request, table_5.manufacturer AS manufacturer, table_4.name AS model, table_6.value AS specifications, table_9.value as shipping, table_1.model AS mid, table_1.user_id, table_1.callme, table_1.phoneprice, table_1.phoneprice_eur, table_1.currency, table_1.sel_buy_show_all, table_1.seller_buyer FROM (`table_1`) LEFT JOIN `table_3` ON `table_3`.`id` = `table_1`.`sim` LEFT JOIN `table_4` ON `table_4`.`id` = `table_1`.`model` LEFT JOIN `table_5` ON `table_5`.`id` = `table_1`.`manufacturer` LEFT JOIN `table_6` ON `table_6`.`id` = `table_1`.`specifications` LEFT JOIN `table_7` ON `table_7`.`id` = `table_1`.`user_id` LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id` LEFT JOIN `table_9` ON `table_9`.`id` = `table_1`.`types` WHERE `table_1`.`status` = '1' AND `table_1`.`deleted` = '0' ORDER BY `last_update` DESC LIMIT 200 And there is table_1 which structure is the same as table_2, and I need somehow to insert table_2 to the query with all joins like table_1 A: If I got your question right, you can use union like this - select * from table_1 union select * from table_2 order by create_date desc EDIT Create a view like this - create view table_1And2 as select * from table_1 union select * from table_2 table_1And2 is not a good name, give a meaningful name. And modify your long query like this - SELECT table_1And2.id, table_1And2.created, table_1And2.qty, table_1And2.comments, table_1And2.last_update, table_7.firstname, SUBSTRING(table_7.lastname, 1, 1) AS lastname, table_8.title country, table_3.value AS sim, table_1And2.offer_request, table_5.manufacturer AS manufacturer, table_4.name AS model, table_6.value AS specifications, table_9.value as shipping, table_1And2.model AS mid, table_1And2.user_id, table_1And2.callme, table_1And2.phoneprice, table_1And2.phoneprice_eur, table_1And2.currency, table_1And2.sel_buy_show_all, table_1And2.seller_buyer FROM (`table_1And2`) LEFT JOIN `table_3` ON `table_3`.`id` = `table_1And2`.`sim` LEFT JOIN `table_4` ON `table_4`.`id` = `table_1And2`.`model` LEFT JOIN `table_5` ON `table_5`.`id` = `table_1And2`.`manufacturer` LEFT JOIN `table_6` ON `table_6`.`id` = `table_1And2`.`specifications` LEFT JOIN `table_7` ON `table_7`.`id` = `table_1And2`.`user_id` LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id` LEFT JOIN `table_9` ON `table_9`.`id` = `table_1And2`.`types` WHERE `table_1And2`.`status` = '1' AND `table_1And2`.`deleted` = '0' ORDER BY `last_update` DESC LIMIT 200 A: Also I see the answer of @Rehban is a good one for you, I will produce another solution if you do not need view: SELECT mainTable.id, mainTable.created, mainTable.qty, mainTable.comments, mainTable.last_update, table_7.firstname, SUBSTRING(table_7.lastname, 1, 1) AS lastname, table_8.title country, table_3.value AS sim, mainTable.offer_request, table_5.manufacturer AS manufacturer, table_4.name AS model, table_6.value AS specifications, table_9.value as shipping, mainTable.model AS mid, mainTable.user_id, mainTable.callme, mainTable.phoneprice, mainTable.phoneprice_eur, mainTable.currency, mainTable.sel_buy_show_all, mainTable.seller_buyer FROM (Select * From `table_1` union Select * From `table_2`) as mainTable LEFT JOIN `table_3` ON `table_3`.`id` = `mainTable `.`sim` LEFT JOIN `table_4` ON `table_4`.`id` = `mainTable `.`model` LEFT JOIN `table_5` ON `table_5`.`id` = `mainTable `.`manufacturer` LEFT JOIN `table_6` ON `table_6`.`id` = `mainTable `.`specifications` LEFT JOIN `table_7` ON `table_7`.`id` = `mainTable `.`user_id` LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id` LEFT JOIN `table_9` ON `table_9`.`id` = `mainTable `.`types` WHERE `mainTable `.`status` = '1' AND `mainTable `.`deleted` = '0' ORDER BY `last_update` DESC LIMIT 200
{ "language": "en", "url": "https://stackoverflow.com/questions/36819794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ordered Asynchronous AJAX Calls I'm creating a script that performs several functions and I want to update the user as the functions are completed. I have nested $.ajax() calls with each subsequent call in the previous call's success block. There are a total of 4 calls made for each loop. Let's call them scan_1 through scan_4. The success block of scan_1 calls scan_2 and so on down the chain. For example, let's say I'm looping over 3 objects. I want the process to go like this: Loop 1 * *scan_1 *scan_2 *scan_3 *scan_4 Loop 2 * *scan_1 *scan_2 *scan_3 *scan_4 Loop 3 * *scan_1 *scan_2 *scan_3 *scan_4 The problem is that it's running through all the scan_1 calls first. I must be missing something, but I can't seem to figure it out. Any advice would be much appreciated. For reference, here is a snippet of scan_1 (irrelevant stuff snipped): for(var i = 1; i <= 3; i++) { $.ajax({ type: 'GET', url: url, data: 'do=scan&step=1&' + string, dataType: 'json', success: function (result) { if(result.proceed == 'true') { $('#scan_progress').append(result.message); scan_2(); } else { $('#scan_progress').append(result.message); } } }); } Thoughts? Thanks in advance. A: Sounds like you need to use jQuery deferred. It basically allows you to chain multiple event handlers to the jQuery Ajax object and gives you finer control over when the callbacks are invoked. Further reading: * *http://msdn.microsoft.com/en-us/scriptjunkie/gg723713 *http://www.erichynds.com/jquery/using-deferreds-in-jquery/ A: It's asynchronous - the "success" fires sometime in the future. The script does not wait for it to respond. Since you're firing off three requests in your loop, they will all be "scan1". "scan_2" will be called as each request completes. Change the request to synchronous if you want to control the order of events. A: You are starting by sending off three ajax calls at once. Scan1 (loop 1) Scan1 (loop 2) Scan1 (loop 3) When each Scan 1 completes, it's subsequent Scan 2, and then Scan 3 are called. What did you actually want to happen? Scan 1 2 and 3 of loop 1, then 1 2 and 3 of loop 2, and then 1 2 and 3 of loop 3? That would require more nesting, or possibly deferred objects. A: Instead of using the success callback for each $.ajax() call, you can store each set of AJAX requests (their jqXHR objects) in an array and wait for all of them to resolve: function scan_1 () { //setup array to store jqXHR objects (deferred objects) var jqXHRs = []; for(var i = 1; i <= 3; i++) { //push a new index onto the array, `$.ajax()` returns an object that will resolve when the response is returned jqXHRs[jqXHRs.length] = $.ajax({ type: 'GET', url: url, data: 'do=scan&step=1&' + string, dataType: 'json' }); } //wait for all four of the AJAX requests to resolve before running `scan_2()` $.when(jqXHRs).then(function () { if(result.proceed == 'true') { scan_2(); } }); } A: I've had similar problems working heavily with SharePoint web services - you often need to pull data from multiple sources to generate input for a single process. To solve it I embedded this kind of functionality into my AJAX abstraction library. You can easily define a request which will trigger a set of handlers when complete. However each request can be defined with multiple http calls. Here's the component (and detailed documentation): DPAJAX at DepressedPress.com This simple example creates one request with three calls and then passes that information, in the call order, to a single handler: // The handler function function AddUp(Nums) { alert(Nums[1] + Nums[2] + Nums[3]) }; // Create the pool myPool = DP_AJAX.createPool(); // Create the request myRequest = DP_AJAX.createRequest(AddUp); // Add the calls to the request myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [5,10]); myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [4,6]); myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [7,13]); // Add the request to the pool myPool.addRequest(myRequest); Note that unlike many of the other solutions provided this method does not force single threading of the calls being made - each will still run as quickly (or as slowly) as the environment allows but the single handler will only be called when all are complete. It also supports the setting of timeout values and retry attempts if your service is a little flakey. I've found it insanely useful (and incredibly simple to understand from a code perspective). No more chaining, no more counting calls and saving output. Just "set it and forget it".
{ "language": "en", "url": "https://stackoverflow.com/questions/9401951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace cells having inf value by 1 Given the following Columns 1 through 17 0.3108 0.7273 Inf 0.2878 -0.0947 0.1286 -0.3108 0.5634 0.2822 0.2362 -0.2628 0.0960 -0.1675 -0.0934 -0.1710 -0.3077 -0.2726 Columns 18 through 20 -0.0630 -0.5097 0.1823 How to replace inf values by 1. I know how to do it using a loop but is there a way to do it without? What if want to save it with another name?i.e. data remains same data1=data except inf is replaced by 1? A: Use isinf to detect Inf, and use the output as a logical index into your array: data(isinf(data)) = 1;
{ "language": "en", "url": "https://stackoverflow.com/questions/10122700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vb.net readline or readkey don't want to stop my program my code is working i tried it separately but the problem here is that when i'm putting them together , the readkey or readline don't stop the program and the do loop is not working too, can someone take a look please thank in advance Dim count As Integer Dim first(5) As Integer Dim temp As Integer Dim answer As String Sub Main() Do Console.WriteLine("Please enter your first number") first(0) = Console.ReadLine Console.WriteLine("Please enter your second number") first(1) = Console.ReadLine Console.WriteLine("Please enter your third number") first(2) = Console.ReadLine Console.WriteLine("Please enter your fourth number") first(3) = Console.ReadLine Console.WriteLine("Please enter your fifth number") first(4) = Console.ReadLine Console.WriteLine("Please enter your sixth number") first(5) = Console.ReadLine randomnumber() Console.WriteLine("do you want to continue?") answer = Console.ReadLine Loop Until (answer = "n" Or answer = "No") Console.ReadKey() End Sub Sub randomnumber() Dim r As New List(Of Integer) Dim rg As New Random Dim rn As Integer Dim arraywinner(5) As Integer Do rn = rg.Next(1, 40) If Not r.Contains(rn) Then r.Add(rn) End If Loop Until r.Count = 6 'store bane random value in array' arraywinner(0) = r(0) arraywinner(1) = r(1) arraywinner(2) = r(2) arraywinner(3) = r(3) arraywinner(4) = r(4) arraywinner(5) = r(5) 'print random numbers count = 0 While count <= 5 Console.WriteLine("the randoms numbers are : " & arraywinner(count)) count = count + 1 End While 'look for the amount of number temp = 0 For count1 As Integer = 0 To 5 For count2 As Integer = 0 To 5 If arraywinner(count1) = first(count2) Then temp = temp + 1 End If Next Next If temp = 1 Or temp = 0 Then Console.WriteLine("You have got " & temp & " number") Else Console.WriteLine("You have got " & temp & " numbers") End If money(temp) End Sub Sub money(ByVal t1 As Integer) 'prend cash' If temp = 6 Then Console.WriteLine("Jackpot $$$$$$$$$$$$$") ElseIf temp = 3 Then Console.WriteLine(" money = 120") ElseIf temp = 4 Then Console.WriteLine("money = 500") ElseIf temp = 5 Then Console.WriteLine("money= 10,000") Else Console.WriteLine(" try next time") End End If End Sub A: You have two problems in money(): Sub money(ByVal t1 As Integer) 'prend cash' If temp = 6 Then Console.WriteLine("Jackpot $$$$$$$$$$$$$") ElseIf temp = 3 Then Console.WriteLine(" money = 120") ElseIf temp = 4 Then Console.WriteLine("money = 500") ElseIf temp = 5 Then Console.WriteLine("money= 10,000") Else Console.WriteLine(" try next time") End End If End Sub Your parameter is t1, but you're using temp in all of your code. As written, it will still work since temp is global, but you should either change the code to use t1, or not pass in that parameter at all. Secondly, you have End in the block for 0, 1, or 2 matches. The End statement Terminates execution immediately., which means the program just stops. Get rid of that line. There are so many other things you could change, but that should fix your immediate problem... A: I moved all the display code to Sub Main. This way your Functions with your business rules code can easily be moved if you were to change platforms. For example a Windows Forms application. Then all you would have to change is the display code which is all in one place. Module Module1 Private rg As New Random Public Sub Main() 'keep variables with as narrow a scope as possible Dim answer As String = Nothing 'This line initializes and array of strings called words Dim words = {"first", "second", "third", "fourth", "fifth", "sixth"} Dim WinnersChosen(5) As Integer Do 'To shorten your code use a For loop For index = 0 To 5 Console.WriteLine($"Please enter your {words(index)} number") WinnersChosen(index) = CInt(Console.ReadLine) Next Dim RandomWinners = GetRandomWinners() Console.WriteLine("The random winners are:") For Each i As Integer In RandomWinners Console.WriteLine(i) Next Dim WinnersCount = FindWinnersCount(RandomWinners, WinnersChosen) If WinnersCount = 1 Then Console.WriteLine($"You have guessed {WinnersCount} number") Else Console.WriteLine($"You have guessed {WinnersCount} numbers") End If Dim Winnings = Money(WinnersCount) 'The formatting :N0 will add the commas to the number Console.WriteLine($"Your winnings are {Winnings:N0}") Console.WriteLine("do you want to continue? y/n") answer = Console.ReadLine.ToLower Loop Until answer = "n" Console.ReadKey() End Sub 'Too much happening in the Sub 'Try to have a Sub or Function do only one job 'Name the Sub accordingly Private Function GetRandomWinners() As List(Of Integer) Dim RandomWinners As New List(Of Integer) Dim rn As Integer 'Good use of .Contains and good logic in Loop Until Do rn = rg.Next(1, 40) If Not RandomWinners.Contains(rn) Then RandomWinners.Add(rn) End If Loop Until RandomWinners.Count = 6 Return RandomWinners End Function Private Function FindWinnersCount(r As List(Of Integer), WinnersChosen() As Integer) As Integer Dim temp As Integer For count1 As Integer = 0 To 5 For count2 As Integer = 0 To 5 If r(count1) = WinnersChosen(count2) Then temp = temp + 1 End If Next Next Return temp End Function Private Function Money(Count As Integer) As Integer 'A Select Case reads a little cleaner Select Case Count Case 3 Return 120 Case 4 Return 500 Case 5 Return 10000 Case 6 Return 1000000 Case Else Return 0 End Select End Function End Module
{ "language": "en", "url": "https://stackoverflow.com/questions/54969166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shifting registers to right in the mic-1 without fetches this is the first time I post a question here so feel free to give me some feedback were something not described in the proper manner. To the actual question: I was wondering if there was a way to shift a word in one of the registers TO THE RIGHT by 2 bytes without fetches or the arithmetical shifter (EX with fetch: just write the word to memory address 0x0 and fetch 0x0 -> << 8 copy it back in OPC or whatever then OR to the desired register, fetch address 0x1 and OR again to the register without shifting to left this time). So a register containing 0xcccc1111 should become 0x0000cccc Here is a small description of the micro-architecture of the mic-1. Thanks for the help The purpose is to copy a word that starts from memory 0x2 into LV in a more efficient fashion: this should work but it uses both fetch and write and it's probably complete trash :( MAR=0; rd; PC=1; H=PC=PC+1; PC=PC+H; fetch; MDR= MDR <<8; rd; LV=MDR<<8; rd; PC=PC+1; H=MBRU << 8; fetch; LV = LV OR H; H = MBRU; LV = LV OR H;
{ "language": "en", "url": "https://stackoverflow.com/questions/53485161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Averaging an increasing number of columns of a dataframe I have a data frame (wc2) with 7 columns: cm5 cm10 cm15 cm20 cm25 cm30 run_time 1 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0 2 0.4084525 0.4028010 0.3617393 0.2595060 0.1294412 0.1220099 2 3 0.4087809 0.4042515 0.3711077 0.3119956 0.2241836 0.1290348 4 4 0.4088547 0.4045780 0.3732053 0.3218224 0.2611785 0.1720426 6 5 0.4088770 0.4046887 0.3739936 0.3255557 0.2739738 0.2081264 8 6 0.4088953 0.4047649 0.3744183 0.3273794 0.2798225 0.2273250 10 For every row (run_time) I want to average first the 1st column, then the 1st and 2nd columns, then the 1st, 2nd and 3rd columns and so on until the 6th column. The averaged result should be in a new column or a new data frame (I don't mind). I did it using the following code: wc2$dia10 <- wc2$cm5 wc2$dia20 <- rowMeans(wc2[c("cm5", "cm10")]) wc2$dia30 <- rowMeans(wc2[c("cm5", "cm10", "cm15")]) wc2$dia40 <- rowMeans(wc2[c("cm5", "cm10", "cm15", "cm20")]) wc2$dia50 <- rowMeans(wc2[c("cm5", "cm10", "cm15", "cm20", "cm25")]) wc2$dia60 <- rowMeans(wc2[c("cm5", "cm10", "cm15", "cm20", "cm25", "cm30")]) From my basic knowledge of R I gather there is a much better way of doing that but I can't figure out how. Especially for when I'll have a bigger number of columns. I had a look at the answer for "Sum over and increasing number of columns of a data frame in R" but couldn't understand or apply it to my data. Thanks for any help A: You can use Reduce with accumulate = TRUE argument as follows, sapply(Reduce(c, 1:(ncol(df)-1), accumulate = TRUE)[-1], function(i) rowMeans(df[i])) Or to get the exact output, setNames(data.frame(df[1],sapply(Reduce(c, 1:(ncol(df)-1),accumulate = TRUE)[-1], function(i) rowMeans(df[i]))), paste0('dia', seq(from = 10, to = ncol(df[-1])*10, by = 10))) Or as @A5C1D2H2I1M1N2O1R2T1 suggests in comments, do.call(cbind, setNames(lapply(1:6, function(x) rowMeans(df[1:x])), paste0("dia", seq(10, 60, 10))) Both giving, dia10 dia20 dia30 dia40 dia50 dia60 1 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 2 0.4084525 0.4056268 0.3909976 0.3581247 0.3123880 0.2806583 3 0.4087809 0.4065162 0.3947134 0.3740339 0.3440639 0.3082257 4 0.4088547 0.4067164 0.3955460 0.3771151 0.3539278 0.3236136 5 0.4088770 0.4067829 0.3958531 0.3782787 0.3574178 0.3325359 6 0.4088953 0.4068301 0.3960262 0.3788645 0.3590561 0.3371009 Or to add it to the original data frame, then, cbind(df, setNames(lapply(1:6, function(x) rowMeans(df[1:x])), paste0("dia", seq(10, 60, 10)))) A: Here is an alternative method with apply and cumsum. Using rowMeans is almost surely preferable, but this method runs through the calculation in one pass. setNames(data.frame(t(apply(dat[1:6], 1, cumsum) / 1:6)), paste0("dia", seq(10, 60, 10))) dia10 dia20 dia30 dia40 dia50 dia60 1 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 0.1221060 2 0.4084525 0.4056268 0.3909976 0.3581247 0.3123880 0.2806583 3 0.4087809 0.4065162 0.3947134 0.3740339 0.3440639 0.3082257 4 0.4088547 0.4067164 0.3955460 0.3771151 0.3539278 0.3236136 5 0.4088770 0.4067829 0.3958531 0.3782787 0.3574178 0.3325359 6 0.4088953 0.4068301 0.3960262 0.3788645 0.3590561 0.3371009 Using the smarter Reduce("+" with accumulate suggested by @alexis-laz, we could do mapply("/", Reduce("+", dat[1:6], accumulate = TRUE), 1:6) or to get a data.frame with the desired names setNames(data.frame(mapply("/", Reduce("+", dat[1:6], accumulate = TRUE), 1:6)), paste0("dia", seq(10, 60, 10))) The uglier code below follows the same idea, without mapply setNames(data.frame(Reduce("+", dat[1:6], accumulate = TRUE)) / rep(1:6, each=nrow(dat)), paste0("dia", seq(10, 60, 10)))
{ "language": "en", "url": "https://stackoverflow.com/questions/45634033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MediaWiki: Global default '' is invalid for field editfont Anyone see and know what this error means and/or how to fix it? I place it in a google search and it doesn't appear to be something that anyone normally has an issue with: Global default '' is invalid for field editfont Backtrace: #0 /srv/http/SupportWiki/includes/Preferences.php(1152): Preferences::getPreferences(Object(User)) #1 /srv/http/SupportWiki/includes/specials/SpecialPreferences.php(43): Preferences::getFormObject(Object(User)) #2 /srv/http/SupportWiki/includes/SpecialPage.php(559): SpecialPreferences->execute(NULL) #3 /srv/http/SupportWiki/includes/Wiki.php(254): SpecialPage::executePath(Object(Title)) #4 /srv/http/SupportWiki/includes/Wiki.php(64): MediaWiki->handleSpecialCases(Object(Title), Object(OutputPage), Object(WebRequest)) #5 /srv/http/SupportWiki/index.php(117): MediaWiki->performRequestForTitle(Object(Title), NULL, Object(OutputPage), Object(User), Object(WebRequest)) #6 {main} A: I was running MediaWiki 1.16.0. I upgraded to MediaWiki 1.16.2 and this resolved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/5379639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting if SKAction is done running, Swift I want to change the value of a variable after an action has been run and not during it is running. This is my code: override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if gameNotStarted { if firePosition.x != 320 || firePosition.y > 280 { fire.runAction(fireButtonReturn) iapButton.runAction(iapButtonReturn) aboutButton.runAction(abtButtonReturn) if fire.hasActions() == false { println("has no actions") firePosition.x = 320 firePosition.y = 280 } } } } The three actions I am running have exactly the same duration so I only need one to check if they have finished running. After they have finished running I want to change the value offirePosition.x andfirePosition.y. It is very important that fire position values change exactly after the action has been run and absolutely not before the actions are done running. However with my current code I never run theif fire.hasActions() ... part according to results and console. I found similar questions, they were in obj-c. Thanks for your help. A: You should use a completion-handler for your kind of problem: //Run the action iapButton.runAction(iapButtonReturn, //After action is done, just call the completion-handler. completion: { firePosition.x = 320 firePosition.y = 280 } ) Or you could use a SKAction.sequence and add your actions inside a SKAction.block: var block = SKAction.runBlock({ fire.runAction(fireButtonReturn) iapButton.runAction(iapButtonReturn) aboutButton.runAction(abtButtonReturn) }) var finish = SKAction.runBlock({ firePosition.x = 320 firePosition.y = 280 }) var sequence = SKAction.sequence([block, SKAction.waitForDuration(yourWaitDuration), finish]) self.runAction(sequence) A: you should use a completion handler: fire.runAction(fireButtonReturn, completion: { println("has no actions") firePosition.x = 320 firePosition.y = 280 } ) the problem with your solution is, that the action is initiated with the runAction call but then runs in the background while the main thread continues the execution (and therefore reaches it before the action is finished). A: extension SKNode { func actionForKeyIsRunning(key: String) -> Bool { if self.actionForKey(key) != nil { return true } else { return false } } } You can use it : if myShip.actionForKeyIsRunning("swipedLeft") { print("swipe in action..") }
{ "language": "en", "url": "https://stackoverflow.com/questions/29731925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Modify the height of Bootstrap Carousel control? The blue section of the following image shows the triggering area of the bootstrap carousel. I took the screenshot from the bootstrap doc. I would like to modify the height of the triggering region (e.g. From 100% of the carousel height to 50%). May I know how can I modify it? Thanks in advance A: To solve this, just modify the properties of .carousel-control-prev and .carousel-control-prev in the CSS. .carousel-control-prev, .carousel-control-next { height: 25%; top: 37.5%; }; <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <body> <div class="container"> <div class="row"> <div class="col"> <div id="carouselExampleIndicators" class="carousel slide my-4" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img class="d-block img-fluid" src="http://placehold.it/900x350" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="http://placehold.it/900x350" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="http://placehold.it/900x350" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> </div> </body> I have no idea why the top property could not override in the demo. But it works in my project.
{ "language": "en", "url": "https://stackoverflow.com/questions/60844311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Choosing approach for an IM client-server app Update: totally re-wrote this to be more succint. I'm looking at a new application, one part of which will be very similar to standard IM clients, i.e text chat, ability to send attachments, maybe some real-time interaction like a multi-user whiteboard. It will be client-server, i.e all traffic goes through my central server. That means if I want to support cross-communication with other IM systems, I am still free to pick any protocol for my own client<-->server communication - my server can use XMPP or whatever to talk to other systems. Clients are expected to include desktop apps, but probably also browser-based as well either through Flex/Silverlight or HTML/AJAX. I see 3 options for my own client-server communication layer: * *XMPP. The benefits are clients already exist as do open-source servers. However it requires the most up-front research/learning and also appears like it might raise legal issues due to GPL. *Custom sockets. A server app makes connections with the clients, allowing any text/binary data to be sent very fast. However this approach requires building said server from scratch, and also makes a JS client tricky *Servlets (or similar web server). Using tried and tested Java web-stack, clients send HTTP requests similar to AJAX-based websites. The benefit is the server is easy to write using well-established technologies, and easy to talk to. But what restrictions would this bring? Is it appropriate technology for real-time communication? Advice and suggests are welcome, especially what pros and cons surround using a web-server approach as compared to a socket-based approach. A: I think you are re-inventing the wheel. Consider using OpenFire or Tigase which are Java-based and very proven in this IM server space. All the boiler-plate can be leveraged. You tasks would be to add custom behaviors by writing plug-ins.
{ "language": "en", "url": "https://stackoverflow.com/questions/2917652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is my Modal form posting a null model back to the controller I have a partial view that I load in a Modal..in the index view the model div with the HTML.Partial looks like this. <div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modalEditDBInfoContent" style="background-color:white; border-radius:10px; box-shadow:10px;"> @Html.Partial("_EditDatabaseInfo") </div> </div> </div> the partial view code is @model Hybridinator.Domain.Entities.Database <br /> <br /> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="editModelTitle">Edit Database Info</h4> </div> <div class="modal-body"> @using (Html.BeginForm("EditDatabaseInfo", "Database", FormMethod.Post, new { @class = "modal-body" })) { <div class="form-group"> <div id="databaselabel" >@Html.LabelFor(m => m.database, "Database")</div> <div id="databaseedit" >@Html.EditorFor(m => m.database)</div> </div> <div class="form-group"> <div id="databaseserverlabel" >@Html.LabelFor(m => m.database_server, "Database Server")</div> <div id="databaseserveredit" >@Html.EditorFor(m => m.database_server)</div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button class="btn btn-inverse btn-primary" type="submit">Save</button> </div> } </div> If fire this controller successfully [HttpPost] public ActionResult EditDatabaseInfo(Database database) { string s = database.database; //do other stuff return RedirectToAction("Index"); } Everything works fine up until I try to access the model in the controller post which should be passed into ActionResult method. The Model object is null Object reference not set to an instance of an object. anyone see what Im missing here? A: You have to pass the model in Header from the view and from controller and in partialview too lisk below Please get look deeply in bold text and the text in between ** ** **@model Hybridinator.Domain.Entities.Database** <div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modalEditDBInfoContent" style="background-color:white; border-radius:10px; box-shadow:10px;"> @Html.Partial("_EditDatabaseInfo", **Model** ) </div> </div> [HttpPost] public ActionResult EditDatabaseInfo(Database database) { string s = database.database; //do other stuff // **you have to get the model value in here and pass it to index action** return RedirectToAction(**"Index", modelValue**); } public ActionResult Index(**ModelClass classValue**) { //pass the model value into index view. return View(**"Index", classValue**); } A: Change the Model in view, partial view and in action . Instead of passing entity model, create view model and pass it in view as well as partial view. consider the following @model **DatabaseModel** <div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modalEditDBInfoContent" style="background-color: white; border-radius: 10px; box-shadow: 10px;"> @Html.Partial("_EditDatabaseInfo", **Model**) </div> </div> </div> @model DatabaseModel <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="editModelTitle">Edit Database Info</h4> </div> <div class="modal-body"> @using (Html.BeginForm( new { @class = "modal-body" })) { <div class="form-group"> <div id="databaselabel" >@Html.LabelFor(m => m.DatabaseName, "Database")</div> <div id="databaseedit" >@Html.EditorFor(m => m.DatabaseName)</div> </div> <div class="form-group"> <div id="databaseserverlabel" >@Html.LabelFor(m => m.DatabaseServer, "Database Server")</div> <div id="databaseserveredit" >@Html.EditorFor(m => m.DatabaseServer)</div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button class="btn btn-inverse btn-primary" type="submit">Save</button> </div> } </div> public class DatabaseModel { public string DatabaseName { get; set; } public string DatabaseServer { get; set; } } As of my knowledge Database is a key word, because of that it is getting null
{ "language": "en", "url": "https://stackoverflow.com/questions/26921678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Efficiently Modifying CGColor I have an iPhone app where I'm "adding" a lot of CGColors together by breaking them down into their components, averaging the components, and then making a new color with the new components. When I run this code, Instruments finds that I'm leaking lots of CGColors, and the app runs slowly. I feel like I could solve the memory leak issue if there were a way to do what I'm doing without using CGColorCreate(colorspace, components) every time. This is the code for the color "adding" const CGFloat *cs=CGColorGetComponents(drawColor); const CGFloat *csA=CGColorGetComponents(add->drawColor); CGFloat r=(cs[0]*w+csA[0]*aW)/1; CGFloat g=(cs[1]*w+csA[1]*aW)/1; CGFloat b=(cs[2]*w+csA[2]*aW)/1; CGFloat components[]={r, g, b, 1.f}; drawColor=CGColorCreate(CGColorSpaceCreateDeviceRGB(), components); Any help would be really appreciated, even if the help is "add the colors less often." I'm sure I'm not the only person trying to modify CGColors. EDIT: So, rob's comment put me on the right track, but I'm getting malloc double free errors because the method with the color adding is called multiple times before a new drawColor is assigned. Is there a way to check whether drawColor exists before I release it? Here is the new relevant code. CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB(); CGColorRelease(drawColor); drawColor=CGColorCreate(colorSpace, components); CGColorSpaceRelease(colorSpace); A: Pretty sure you just need to CGColorRelease(drawColor) to prevent the leak. See how that helps your performance. A: If you're leaking CGColor objects, the first step to solving your problem is to stop leaking them. You need to call CGColorRelease when you're done with a color object. For example, you are obviously leaking the drawColor object in your example code. You should be doing this: CGColorRelease(drawColor); drawColor=CGColorCreate(CGColorSpaceCreateDeviceRGB(), components); to release the old object referenced by drawColor before you assign the new object to drawColor. CGColor objects are immutable, so you won't be able to just modify your existing objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/8920865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ModelMapper map one object into three In my Java project I am using ModelMapper for mapping from entity object into DTO object. My entity have inside object hierarchy that has three Long properties. My DTO object has only one Long properties, so I created custom map to map between them. public class MyMap extends PropertyMap<DTO, Entity> { /** * Main function that is called when mapping objects. */ @Override protected void configure() { final Converter<Long, Hierarchy> hierarchyToId = context -> { if (context.getSource() != null) { final Long Id = context.getSource(); final HierarchyDto dto = calculateHierarchy(Id) // map dto to entity. final Hierarchy hierarchy = new Hierarchy(); hierarchy.setFirstId(dto.getFirstId()); hierarchy.setSecondId(dto.getSecondId()); hierarchy.setThirdId(dto.getThirdId()); return hierarchy; } return null; }; // map objects. this.using(hierarchyToId).map(this.source.getId(), this.destination.getHierarchy()); } } This give me an error : java.lang.NullPointerException: null ... ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.modelmapper.ConfigurationException: ModelMapper configuration errors: 1) The destination property com....DTO.setId() matches multiple source property hierarchies: com....getHierarchy()/com....getFirstId() com....getHierarchy()/com....getSecondId() com....getHierarchy()/com....getThirdId() 1 error] with root cause org.modelmapper.ConfigurationException: ModelMapper configuration errors: I understand that Mapper has problems that I map one object into 3 but what do I need to do that it will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/35771649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: toggle custom image in a UIBarButtonItem I've been breaking my head for the past two days searching and trying some of my own solutions. I placed a UIBarButtonItem through IB with an image in the top bar to act as a mute/unmute button . Everything works except the image doesn't change. I used the following code and it compiles but no change if( mute == YES ) { UIImage *unmuteImage = [UIImage imageNamed:@"audio-on.png"]; [self.muteButton setImage:unmuteImage]; [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"muteKey"]; } else { UIImage *muteImage = [UIImage imageNamed:@"audio-off.png"]; [self.muteButton setImage:muteImage]; [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"muteKey"]; } A: I finally figured it out...only took a couple of days but I've been too busy to post up a solution. We'll I finally got time and am happy to post my solution. I had a hunch that this would'nt work unless it was done 100% programmatically, and I was right. Here's the final solution to my problem: if(mute == YES) { UIImage *image = [UIImage imageNamed:@"audio-off.png"]; UIButton *myMuteButton = [UIButton buttonWithType:UIButtonTypeCustom]; myMuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height ); [myMuteButton setImage:image forState:UIControlStateNormal]; [myMuteButton addTarget:self action:@selector(mute) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *myMuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myMuteButton]; navBar.leftBarButtonItem = myMuteBarButtonItem; [myMuteBarButtonItem release]; } else { UIImage *image = [UIImage imageNamed:@"audio-on.png"]; UIButton *myUnmuteButton = [UIButton buttonWithType:UIButtonTypeCustom]; myUnmuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height ); [myUnmuteButton setImage:image forState:UIControlStateNormal]; [myUnmuteButton addTarget:self action:@selector(mute) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *myUnmuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myUnmuteButton]; navBar.leftBarButtonItem = myUnmuteBarButtonItem; [myUnmuteBarButtonItem release]; } the good news is I finally finished my app and submitted it to the app store. Hopefully everything will go smooth and am looking forward to it! A: Swift, I set mine around an instance var, and used that to toggle my switch. I also had 3 buttons in my nav bar. private var activeStaff:Staff? { didSet { let image = (activeStaff == nil) ? UIImage(named: "active")! : UIImage(named: "notActive")! let button = UIBarButtonItem(image: image, style: .Plain, target: self, action: "activePressed:") if navigationItem.rightBarButtonItems?.count == 3 { navigationItem.rightBarButtonItems?.removeAtIndex(0) } navigationItem.rightBarButtonItems?.insert(button, atIndex: 0) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/3117971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is there a margin around hr and img tags? I am trying to remove the whitespace around hr and img tags, I have not had any luck yet, Here is a JSFiddle. Can someone show me how to do this? Is it a good idea to use hrs instead of divs when creating a sepearation/surrounding? Should I use a div instead? Can someone tell me which one is the better option. Sorry for the short question. SOME CODE : <img class="banner margin_padding" src="http://goo.gl/ftvYk5"> <hr class="line margin_padding"/> <hr class="line margin_padding"/> <hr class="line margin_padding"/> img.banner { height: 200px; width: 100%; } hr.line { background-color: red; color: red; height: 20px; } .margin_padding { margin: 0px; padding: 0px; } EDIT : Borders have a default border size I forgot about and the image should be displayed block A: Add display:block to your img tag and border:0 to your hr tag. .margin_padding { margin: 0; padding: 0; border: 0; display: block; } A: What you see is the default margin of the <body> tag. The actual value depends on the browser. A common practice to avoid most browser's different default values is explicitly setting margin and padding to 0: html, body { margin: 0; padding: 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/23599976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to set Cells value to 1 if condition met else existing value incremented by 1 for a column in VBA-Excel I have a table in sheet1 with two columns Name and Loan Amount and a similar table in sheet2 with an additional column called Counter. Example: Table in Sheet1 Table in Sheet2 Name Loan Amount Name Loan Amount Counter Ajit 8000 Ajit 8000 2 Rahul 8001 Rahul 8001 3 Gaurav 8002 Gaurav 8002 4 varun 8003 Varun 8003 2 Nama 30004 2 Sutra 30005 4 Patra 30006 5 Pakhi 30007 6 Ratan 30008 5 If Name in sheet1 matches with the Name in sheet2 the Loan Amount corresponding to the Name in sheet1 should be set in sheet2 for same Name. Also Counter should be set to 1. And if Name does not match in both the sheets then Counter in sheet2 for those names should be incremented by 1 so that resulted table in sheet2 look like: Output Table in Sheet2 Name Loan Amount Counter, Ajit 8000 1 Rahul 8001 1 Gaurav 8002 1 Varun 8003 1 Nama 30004 3 Sutra 30005 5 Patra 30006 6 Pakhi 30007 7 Ratan 30008 6 Please help me out with this how can I achieve this result in VBA excel. Please see what I am doing so far to achieving this but i am not getting how to increase counter where names do not match: Private Sub CommandButton1_Click() Dim i As Integer Dim j As Integer Dim Count1 As Integer Dim Count2 As Integer Count1 = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count Count2 = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count For i = 2 To Count1 For j = 2 To Count2 If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then Worksheets("Sheet2").Cells(j, 2).Value = Worksheets("Sheet1").Cells(i, 2).Value Worksheets("Sheet2").Cells(j, 3).Value = 1 End If Next j Next i End Sub But through I am not getting how to increment the cells value for which names are not matching in both sheets. A: UPDATED : As per your Error and Tested Private Sub CommandButton1_Click() Dim i As Integer 's Dim j As Integer Dim Count1 As Integer Dim Count2 As Integer Dim cell As Range Count1 = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count Count2 = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count For i = 2 To Count1 For j = 2 To Count2 If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then Worksheets("Sheet2").Cells(j, 2).Value = Worksheets("Sheet1").Cells(i, 2).Value Worksheets("Sheet2").Cells(j, 3).Value = 0 Exit For End If Next j Next i For Each cell In Range("C2:" & "C" & Cells(Rows.Count, "C").End(xlUp).Row) cell.Value = cell.Value + 1 Next End Sub Let me know, if you have gotten issues. A: Private Sub CommandButton1_Click() Dim i As Integer Dim j As Integer Total1 = Worksheets("Sheet1").Range("A1").CurrentRegion.Rows.Count Total2 = Worksheets("Sheet2").Range("A1").CurrentRegion.Rows.Count MsgBox Total1 For i = 2 To Total1 For j = 2 To Total2 If Worksheets("Sheet1").Cells(i, 1).Value = Worksheets("Sheet2").Cells(j, 1).Value Then Worksheets("Sheet2").Cells(j, 2).Value = Worksheets("Sheet1").Cells(i, 2).Value Worksheets("Sheet2").Cells(j, 3).Value = 1 End If Next j Next i For j = 2 To Total2 If Worksheets("Sheet1").Cells(i, 1).Value <> 1 Then Worksheets("Sheet2").Cells(j, 3).Value = Worksheets("Sheet2").Cells(j, 3).Value + 1 End If Next j End Sub This code is also working fine for the above solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/25095368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get just inserted id lua-sqlite3 Im trying to get just inserted autoincremented id: local luasql = require "luasql.sqlite3" dbname = "dbname" table1 = "table1" table2 = "table2" env = luasql.sqlite3() con = env:connect(dbname) -- Create table1 res1 = con:execute(string.format("CREATE TABLE '%s' (" .. "id INTEGER PRIMARY KEY AUTOINCREMENT, " .. "test1 varchar(32), " .. "test2 varchar(32))", con:escape(table1))) -- Create table2 res2 = con:execute(string.format("CREATE TABLE '%s' (" .. "id INTEGER PRIMARY KEY AUTOINCREMENT, " .. "id_of_row_in_table_1 varchar(32), " .. "test2 varchar(32))", con:escape(table2))) -- Insert data into table1 last_inserted_id = con:execute(string.format("INSERT INTO '%s' ('%s', '%s')", con:escape(table1), 'test1', 'test2', con:escape('1'), con:escape('1'))) print(last_inserted_id) -- unfortunately this do not return just inserted id -- Insert data into table2 res = con:execute(string.format("INSERT INTO '%s' ('%s', '%s')", con:escape(table2), 'last_inserted_id', 'test2', con:escape(last_inserted_id), con:escape('1'))) How to get the last inserted id? I consider an insert function should return just inserted id but it don't. A: You could do something like this (I'm using lsqlite3 so adjust accordingly): db = sqlite3.open(':memory:') db:execute [[ create table xxx(xxx); insert into xxx values('one'); insert into xxx values('two'); insert into xxx values('three'); ]] sql = [[select last_insert_rowid() as num;]] for ans in db:nrows(sql) do print(ans.num) end
{ "language": "en", "url": "https://stackoverflow.com/questions/35998955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a NodeJS based web server to take advantage of HTTP2 on windows platform I am using windows 2012 server and want to host some static HTML/CSS/JS/image files on a nodejs based web server. I do not want to use IIS as I want to take advantages of HTTP2 & want to push files from server to client. I looked at Using node.js as a simple web server which talks about how to create a node based webserver. Another option is to use http-server node package. My question is: * *These solutions are over two year old. Do we have a better option available now? *Does any of these two options supports HTTP2? I would prefer using a existing node module rather then reinventing the wheel. A: You could try NGINX, it can support HTTP/2. http://nginx.org/en/docs/windows.html Run your node applications by using default node, nodemon, pm2... Then use NGINX as a static web server and you can reverse proxy your node apps. A: If you want to use Node then this article seems to cover the basics: https://webapplog.com/http2-server-push-node-express/ and it seems the node-spdy module is the best option (it includes support for HTTP/2 despite the name). There is a node-http2 module but it seems much less well maintained and doesn't support Express (the most popular HTTP framework for Node). However, as discussed in the comments, while not the question you asked, I recommend running a traditional web server (e.g. Apache, Nginx or IIS) in front of NodeJS or any other traditionally back end server. While NodeJS is very flexible and most (if not all) of the functionality of a webserver can be added to it, a traditional web server comes out of the box with a lot of functionality and requires just configuration rather than programming and/or pulling in multiple other modules to set it up properly. For just serving static files Node seems the wrong solution to me so, for the rest of my answer I'll discuss not not using Node directly for the reasons given above but instead using a front end webserver. I don't know IIS too well but from a quick Google it seems HTTP/2 was only introduced in IIS 10 and, as far as I know, even IIS 10 doesn't support Push except through API calls so I agree with your decision not to use that for now. Nginx could be installed instead of IIS, as suggested, and while it supports HTTP/2 it doesn't yet support HTTP/2 (though Cloudflare have added it and run on Nginx so imagine it won't be long coming). Apache fully supports HTTP/2 including server push. Packaged windows versions of Apache can be downloaded from Apache Lounge so is probably the easiest way of supporting HTTP/2 push on Windows Server and would be my recommendation for the scenario you've given. While I mostly use Apache on Linux boxes I've a number of servers on Windows and have quite happily been running Apache on that as a Service (so it automatically restarts on server reboot) with no issues so not sure what "bad experience" you had previously but it really is quite stable to me. To set up Apache on a Windows Server use the following steps: * *Download the last version from Apache Lounge. *Unzip the files and save them to C:\ (or C:\Program Files\ if you prefer but update all the config to change the default C:\apache24 to C:\Program Files\) *Edit the conf\httpd.conf file to check ServerRoot, DocumentRoot and any Directory values are set to where you want it (C:\Apache24 by default). *Run a DOS->Command Prompt as Administrator *In the Administrator CD to the Apache location and the bin director. *Run httpd.exe and deal with any error messages (note port 80 must be free so stop anything else running on that report). *Check you get the default "It works!" message on http://localhost/ *Install Apache as a service by killing the httpd.exe process and instead running httpd.exe -install. *Start the Apache24 service and again verify you get the "It works!" message on http://localhost/ To add HTTP/2 and HTTPS (necessary for HTTP/2 on all browsers), uncomment the following lines from httpd.conf: LoadModule http2_module modules/mod_http2.so ... LoadModule socache_shmcb_module modules/mod_socache_shmcb.so ... LoadModule ssl_module modules/mod_ssl.so ... Include conf/extra/httpd-ssl.conf Install a cert and key to conf/server.crt and conf/server.key - note Apache 2.4 expects the cert file to include the cert plus any intermediary certs in X509 Base 64 DER format so should look something like this when opened in a text editor: -----BEGIN CERTIFICATE----- MII...etc. -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MII...etc. -----END CERTIFICATE----- Where the first cert is the server cert and the 2nd and subsequent certs are the intermediaries. You should make sure you're running good HTTPS config (the defaults in Apache are very poor), but the defaults will do for now. I've a blog post on that here. Restart Apache in the service menu and check you can access https://localhost (ignoring any cert error assuming your cert does not cover localhost). To add HTTP/2 to Apache Edit the conf/extra/httpd-ssl.conf file to add the following near the top (e.g. after the Listen 443 line): Protocols h2 http/1.1 Restart Apache in the service menu and check you can access https://localhost (ignoring any cert error assuming your cert does not cover localhost) and you should see h2 as the protocol in the developer tools of your web browser. To use HTTP/2 push in Apache add the following to push a style sheet: Header add Link "</path/to/css/styles.css>;rel=preload;as=style" env=!cssloaded And you should see it pushed to your page in developer tools. Again, I've a blog post on that if you want more information on this. If you do want to use Node for some (or all) of your calls you can uncomment the following line from conf/httpd.conf: LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so And then add the following config: ProxyPass /nodecontent http://127.0.0.1:8000/ Which will send any of those requests to node service running on port 8000. Restart to pick up this config. If your node service adds any HTTP headers like this: link:</path/to/style/styles.css>;rel=preload;as=style Then Apache should pick them up and push them too. For example if using Express you can use the following to set the headers: app.get('/test/', function (req, res) { res.header('link','</path/to/style.css>;rel=preload;as=style'); res.send('This is a test page which also uses Apache to push a CSS file!\n'); }); Finally, while on the subject of HTTP/2 push this article includes a lot of interesting food for thought: https://jakearchibald.com/2017/h2-push-tougher-than-i-thought/ A: I know this is a fairly old question, but I thought I would give an answer for those that come here looking for info. Node now has a native http2 module and there are some examples on the web that show exactly how to implement a static web server. NOTE: At the time of this answer Node 9.6.1 is current and the native module is still experimental Example https://dexecure.com/blog/how-to-create-http2-static-file-server-nodejs-with-examples/ NOTE: I have no affiliation to the author of the example
{ "language": "en", "url": "https://stackoverflow.com/questions/44997938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flask HTTP Server won't allow upload of multiple files at once import os from flask import Flask, request, redirect, url_for from werkzeug import secure_filename UPLOAD_FOLDER = '/home/ubuntu/shared/' app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'POST': file = request.files['file'] if file: filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('index')) return """ <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method="post" enctype="multipart/form-data"> <p><input type="file" multiple="" name="file"> <input type="submit" value="Upload"> </form> <p>%s</p> """ % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],)) if __name__ == "__main__": app.run(host='0.0.0.0', port=8000, debug=False) If I launch the server and select 2 files through the form, it only uploads one of them. I tried for serveral hours and read about 15 topics on it, including the documentation. Nada :c Edit: I also tried changing: file = request.files['file'] into: file = request.files.getlist('file') would not work either. The type of quotes have no effect either. Wasn't that a python3 thing? A: import os, ssl from flask import Flask, request, redirect, url_for from werkzeug import secure_filename UPLOAD_FOLDER = '/home/ubuntu/shared/' certfile = "/home/ubuntu/keys/fullchain.pem" keyfile = "/home/ubuntu/keys/privkey.pem" ecdh_curve = "secp384r1" cipherlist = "ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305" sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) sslcontext.options |= ssl.OP_NO_TLSv1 sslcontext.options |= ssl.OP_NO_TLSv1_1 sslcontext.protocol = ssl.PROTOCOL_TLSv1_2 sslcontext.set_ciphers(cipherlist) sslcontext.set_ecdh_curve(ecdh_curve) sslcontext.load_cert_chain(certfile, keyfile) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'POST': my_data = request.files.getlist('file') my_pass = request.form['password'] if my_data and my_pass == 'yakumo': for file in my_data: my_handler(file) return redirect(url_for('index')) return """ <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file multiple name=file> <input type="password" name="password" value=""> <input type=submit value=Upload> </form> <p>%s</p> """ % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],)) def my_handler(f): filename = secure_filename(f.filename) f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) if __name__ == "__main__": app.run(host='0.0.0.0', port=8000, ssl_context=sslcontext, threaded=True, debug=False) I made a very rookie mistake and didn't for-loop over the multiple files being uploaded. The code here was tested without issues with 4 simultaneous file uploads. I hope it will be useful to someone. Edit: Code updated with some sweet TLS_1.2 and a password field. Enjoy a reasonably secure upload server. Password is transferred over HTTPS.
{ "language": "en", "url": "https://stackoverflow.com/questions/45017210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implement Scenario outline in a cucumber-protractor through step definitions and page objects Does anyone know why this step might be showing as "undefined" when I try to run it. below you will see an example where I am trying to experiment with cucumber scenario outline and my "examples:" section has 1 entry. Also, the page objects and step def is enclosed. For some reason when I try to run it , I get an error like this: 1) Scenario: Verify user can search # ..\features\automation\regression\samplezz.feature:13 √ Before # ..\support\world.js:21 √ Given I navigate to the ea site # ..\step_definitions\ea_page_steps.js:4 √ Then I click on the search icon # ..\step_definitions\ea_page_steps.js:8 ? When I search for the word angular Undefined. Implement with the following snippet: When('I search for the word angular', function (callback) { // Write code here that turns the phrase above into concrete actions callback(null, 'pending'); }); Here is the feature file Feature: sampleZZ The purpose of this feature file is to navigate to the eaAutomationa site Scenario Outline: Verify user can search Given I navigate to the ea site Then I click on the search icon When I search for the word <word> Examples: |word| |angular| here is the step def: let {Given, Then, When} = require('cucumber'); Given(/^I navigate to the ea site$/, function(){ return browser.get(this.url.ud); }); Then(/^I click on the search icon$/, function(){ return this.pages.udPage.click_Search(); }); When(/^I search for the word "([^"]*)" $/, function(word){ return this.pages.udPage.enter_SearchText(word) }); Here are the page objects class UDPage extends require('../base_page.js') { constructor() { super(); this.eaautomation = by.css('#new_searchicon > i'); this.eaLogo = by.css('//#header_logo'); }; click_Search() { return element(this.eaautomation).click(); } enter_SearchText(text){ return element(this.eaautomation).sendKeys(text); } } module.exports = UDPage; Note: I have a universal constructor in the framework and therefore I don't have to import any pages when I write my test. Could someone help me understand what is the wrong with the step 3 that it keeps showing undefined? using following "dependencies": { "chai": "4.1.2", "chai-as-promised": "7.1.1", "chakram": "1.5.0", "cucumber": "4.0.0", "cucumber-html-reporter": "3.0.4", "fs": "0.0.2", "path": "0.12.7", "protractor": "5.3.0", "protractor-cucumber-framework": "4.2.0" } EDITED- to add the config.js let path = require('path'), environment = require('./environment'); exports.config = Object.assign({}, environment, { seleniumAddress: 'http://localhost:4444/wd/hub', // 'http://localhost:4444/wd/hub' to run locally capabilities: { "browserName": "chrome", "shardTestFiles": true, "maxInstances": 1, "ignoreProtectedModeSettings": true }, specs:[ '../features/automation/regression/sample2.feature', ], params: { environment: 'qa1', // dit, qa4, or qa1 platform: 'browser', // browser or mobile path: { page_objects: path.resolve(__dirname + '/../page_objects'), // Default directory for the page objects page_factory: path.resolve(__dirname + '/../page_objects/page_factory.js'), // Default page factory location projectRoot: path.resolve(__dirname + '/../') // Default root for the automation } } }); A: Remove the double quote around "([^"]*)" in step definition, there is no quote in feature file. When(/^I search for the word ([^"]*)$/, function(word){}); enter_SearchText(text) { var me = this; // wait 15 seconds return browser.sleep(15*1000).then(function(){ return element(me.eaautomation).sendKeys(text); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/49838734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Parse and display a table in Jsoup android i have some problems with jsoup. this is the link i want to parse: http://roosters.gepro-osi.nl/roosters/rooster.php?klassen%5B%5D=L2vp&type=Klasrooster&wijzigingen=1&school=905/ . I want to select te table content and display it nice and clean in my app. this is the script i already have: package rsg.deborgen.nl; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Lindenborg1Activity extends Activity { Button btn_2p; // blog url static final String BLOG_URL = "http://roosters.gepro-osi.nl/roosters/rooster.php?klassen%5B%5D=L2vp&type=Klasrooster&wijzigingen=1&school=905/"; @Override public void onCreate(Bundle savedInstanceState) { // set layout view super.onCreate(savedInstanceState); setContentView(R.layout.main); btn_2p =(Button) findViewById(R.id.button1); btn_2p.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub // process // set layout view setContentView(R.layout.rooster); try { ((TextView)findViewById(R.id.tv)).setText(getBlogStats()); } catch (Exception ex) { ((TextView)findViewById(R.id.tv)).setText("Error"); } } protected String getBlogStats() throws Exception { String result = ""; // get html document structure Document document = Jsoup.connect(BLOG_URL).get(); // selector query Elements nodeBlogStats = document.select("td.tableheader"); // check results if(nodeBlogStats.size() > 0) { // get value result = nodeBlogStats.get(0).text(); } // return return result; (i leaved away the end because of it was going wrong with code block) but if i run it now it shows me the whole site and i want only the text in the table. so please help me, thanks! (Ps. this script is from another tut but i can't remeber its name and sorry for my nooblism and bad english :D ) A: try document.select("tr.AccentDark td.tableheader")
{ "language": "en", "url": "https://stackoverflow.com/questions/10541386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get every nth line into different arrays I need to create a program that seperates every name and each type of scores the students are taking.(test finals etc) The file I'm reading looks like this: *Puckett, Karen 10 10 9.5 10 10 8 9.5 10 10 10 9 10 10 10 0 4 3 5 3 5 2 3 2 1.5 1 5 3.5 17.5 24 22 23.5 22 23 90 91 96 * It repeats for a total of 16 students. The method I created for the name looks like this so far: public static String[] name(String output, int i) { String[] names = new String[16]; String name = nulll while (i<16) { name = ???; names[i] = name; i++; } return names; } If i find what I need to set the name variable to I think I will be able to repeat them for each method and finish the rest of the requirements. variable i starts at 0 and comes from the main method and output is the string I made from the text file I'm reading from, and also comes from the main method.
{ "language": "en", "url": "https://stackoverflow.com/questions/33554828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generating synonyms using pyDictionary I would like to return all the synonyms for a particular word using pyDictionary. However, I can only retrieve the first five synonyms. for example; >>>from PyDictionary import PyDictionary >>>dictionary=PyDictionary() >>>dictionary.synonym("beautiful") >>>[u'alluring', u'cute', u'fascinating', u'magnificent', u'marvelous'] Extended list [u'alluring', u'cute', u'fascinating', u'magnificent', u'marvelous', 'delicate', 'dazzling', 'delightful', 'elegant','fascinating' etc]. See thesaurus for the full list as pyDictionary uses Thesaurus. Any idea on how to retrieve the complete list of synonyms for a word? and besides WordNet, are they any other recommended lexical databases for synonym generation that can be used with python? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/44660864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "Adding" Dictionaries in Python? Possible Duplicate: python dict.add_by_value(dict_2) ? My input is two dictionaries that have string keys and integer values. I want to add the two dictionaries so that the result has all the keys of the input dictionaries, and the values are the sum of the input dictionaries' values. For clarity, if a key appears in only one of the inputs, that key/value will appear in the result, whereas if the key appears in both dictionaries, the sum of values will appear in the result. For example, say my input is: a = dict() a['cat'] = 1 a['fish'] = 10 a['aardvark'] = 1000 b = dict() b['cat'] = 2 b['dog'] = 200 b['aardvark'] = 2000 I would like the result to be: {'cat': 3, 'fish': 10, 'dog': 200, 'aardvark': 3000} Knowing Python there must be a one-liner to get this done (it doesn't really have to be one line...). Any thoughts? A: How about that: dict( [ (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ] ) Or without creating an intermediate list (generator is enough): dict( (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) ) Post Scriptum: As a commentator addressed correctly, there is a way to implement that easier with the new (from Py2.7) collections.Counter class. As much I remember, this version was not available when I wrote the answer: from collections import Counter dict(Counter(a)+Counter(b)) A: One liner (as sortof requested): get key lists, add them, discard duplicates, iterate over result with list comprehension, return (key,value) pairs for the sum if the key is in both dicts, or just the individual values if not. Wrap in dict. >>> dict([(x,a[x]+b[x]) if (x in a and x in b) else (x,a[x]) if (x in a) else (x,b[x]) for x in set(a.keys()+b.keys())]) {'aardvark': 3000, 'fish': 10, 'dog': 200, 'cat': 3} A: result in a: for elem in b: a[elem] = a.get(elem, 0) + b[elem] result in c: c = dict(a) for elem in b: c[elem] = a.get(elem, 0) + b[elem] A: Not in one line, but ... import itertools import collections a = dict() a['cat'] = 1 a['fish'] = 10 a['aardvark'] = 1000 b = dict() b['cat'] = 2 b['dog'] = 200 b['aardvark'] = 2000 c = collections.defaultdict(int) for k, v in itertools.chain(a.iteritems(), b.iteritems()): c[k] += v You can easily extend it to a larger number of dictionaries.
{ "language": "en", "url": "https://stackoverflow.com/questions/1031199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Maven Surefire Plugin doesn't run expected tests in directory In a maven submodule, I have unit tests and acceptance tests with cucumber. I want mvn test to run only the unit tests. The structure is the following: Initially, the problem was that the mvn test goal was running only the cucumber tests (acceptance tests). So I noticed that the Maven Surefire Plugin, that manages what will be run in the mvn test goal, was defined in the parent pom. So I decided to override it in the child pom by defining the Maven Surefire Plugin in the child pom as well, and changing some configurations with the tag, trying to make it so that mvn test would only run the unit tests: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> <configuration> <reuseForks>true</reuseForks> <forkCount>1</forkCount> <includes> <include>unittests/**/*</include> </includes> </configuration> </plugin> According to surefire's documentation, the path specified in the tag is relative to the directory containing generated test classes, typically src/test/java. However, it would make more sense to call it testSourceDirectory, because when I run mvn -X test I get the following: [DEBUG] (s) projectBuildDirectory = /home/myname/parent-module/child-module/target [DEBUG] (s) redirectTestOutputToFile = false [DEBUG] (s) remoteRepositories = [ id: central url: https://repo.maven.apache.org/maven2 layout: default snapshots: [enabled => false, update => daily] releases: [enabled => true, update => never] ] [DEBUG] (s) reportFormat = brief [DEBUG] (s) reportsDirectory = /home/myname/parent-module/child-module/target/surefire-reports [DEBUG] (f) rerunFailingTestsCount = 0 [DEBUG] (f) reuseForks = true [DEBUG] (s) runOrder = alphabetical [DEBUG] (s) session = org.apache.maven.execution.MavenSession@58434b19 [DEBUG] (f) shutdown = testset [DEBUG] (s) skip = false [DEBUG] (f) skipAfterFailureCount = 0 [DEBUG] (s) skipTests = false [DEBUG] (s) suiteXmlFiles = [] [DEBUG] (s) tempDir = surefire [DEBUG] (s) testClassesDirectory = /home/myname/parent-module/child-module/target/test-classes [DEBUG] (s) testFailureIgnore = false [DEBUG] (s) testNGArtifactName = org.testng:testng [DEBUG] (s) testSourceDirectory = /home/myname/parent-module/child-module/src/test/java [DEBUG] (s) threadCountClasses = 0 [DEBUG] (s) threadCountMethods = 0 [DEBUG] (s) threadCountSuites = 0 [DEBUG] (s) trimStackTrace = true [DEBUG] (s) useFile = true [DEBUG] (s) useManifestOnlyJar = true [DEBUG] (f) useModulePath = true [DEBUG] (s) useSystemClassLoader = true [DEBUG] (s) useUnlimitedThreads = false [DEBUG] (s) workingDirectory = /home/myname/parent-module/child-module Currently, with the include tag that I added, it finds no tests to run. I have some questions, for example, why does the documentation mention testClassesDirectory if that 's where the .class files are instead of Test*.java files, because that's what we want to include, right? .java tests, not the .class compiled ones. Also, assuming the include tags are relative to testSourceDirectory instead of testClassesDirectory, why doesn't my include work? Because my testSourceDirectory is pointing to /home/myname/parent-module/child-module/src/test/java, if I put next to it unittests/**/* it should skip any directories with the ** glob and get any files with the * glob, right?
{ "language": "en", "url": "https://stackoverflow.com/questions/74208913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to log out from AWS Cognito in ASP.NET Core I'm trying to implement authentication using AWS Cognito in a ASP.NET Core 5 web app. I can get authenticated, but now I want to implement a logout function. I can kind of get the logout to work, in that ASP.NET thinks I'm not authenticated. In my Startup.cs I have: options.SignedOutRedirectUri = Configuration["Authentication:Cognito:SignedOutRedirectUri"]; options.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProviderForSignOut = context => { var logoutUri = options.SignedOutRedirectUri; context.Response.Redirect(logoutUri); context.HandleResponse(); return Task.CompletedTask; } }; In my appsettings.json I have: "SignedOutRedirectUri": "https://mydomain.auth.us-east-2.amazoncognito.com/logout?client_id=<<clientid>>&response_type=code&redirect_uri=https://localhost:44306/Home/LoggedOut" In my Logout controller, I have: await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); return Redirect("/Home/LoggedOut"); So when I click my Logout link, I am redirected to /Home/LoggedOut and I am no longer authenticated (in that User.Identity.IsAuthenticated = false). But when I go to any page with [Authorize] on it, it automatically re-authenticates me to the same user I was logged in as - it never gives me a chance to log in as a different user. I want it to take me to the Cognito login dialog and ask me to authenticate again. So it looks like something is not getting cleared somewhere, I suppose on the AWS Cognito side of things. Why isn't this sending me back to the login dialog to re-authenticate? I thought a GET to the AWS /logout endpoint was supposed to that. A: I think the issue is the parameters of the URL you are constructing for AWS Logout endpoint. (you haven't set logout_uri) https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html example 1 shows the required parameters to logout and redirect back to the client. Here is how I've done it. options.Events = new OpenIdConnectEvents() { OnRedirectToIdentityProviderForSignOut = context => { context.ProtocolMessage.IssuerAddress = GetAbsoluteUri(Configuration["Authentication:Cognito:EndSessionEndPoint"], Configuration["Authentication:Cognito:Authority"]); context.ProtocolMessage.SetParameter("client_id", Configuration["Authentication:Cognito:ClientId"]); context.ProtocolMessage.SetParameter("logout_uri", "https://localhost:5001"); return Task.CompletedTask; } }; The logout_uri must match exactly the configured signout url on AWS app client settings. Helper method private string GetAbsoluteUri(string signoutUri, string authority) { var signOutUri = new Uri(signoutUri, UriKind.RelativeOrAbsolute); var authorityUri = new Uri(authority, UriKind.Absolute); var uri = signOutUri.IsAbsoluteUri ? signOutUri : new Uri(authorityUri, signOutUri); return uri.AbsoluteUri; } Logging out is done with the two lines below. As you worked out, the first line is logging you out locally by clearing out the local authentication cookie, the second line ordinarily would call off to an end_session endpoint on your IDP to log out of your IDP, however as cognito doesn't have and end_session endpoint, you override that when you configure the middleware via OnRedirectToIdentityProviderForSignOut event, instructing it instead to call off to the logout endpoint that cognito does have, and that's where this URL is used. Since you hadn't constructed that correctly it never logs out of cognito. public async Task Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); } and the configuration values ... "EndSessionEndPoint": "logout", "ClientId": "<your client id>", "Authority": "https://<your domain>.auth.<your region>.amazoncognito.com" ... hopefully that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/67322899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python sort in a dictionary and a set I'm creating a book index and I have read in a text file of words and their pages and have created this dictionary called 'index' index={'spanning tree': {16, 99}, 'vertex': {54}, 'depth first search': {55}, 'shortest path': {55}, 'connected': {28, 54}, 'neighbor': {64, 27, 77}, 'path': {72, 19}} Now I want to alphabetize the keys and put the numbers in chronological order- Am I able to do this in the dictionary format or do I need to convert it to a list or a string? I tried doing this... ind=list(index) ind.sort() return ind and I got a list of the keys in alphabetical order but am not sure how to approach the numbers because they are in sets... Any advice? A: You'll have to convert the sets to lists too if you want to apply ordering. The sorted() function gives you a sorted list from any iterable, letting you skip a step: for key in sorted(index): print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key])))) Short demo: >>> sorted(index) ['connected', 'depth first search', 'neighbor', 'path', 'shortest path', 'spanning tree', 'vertex'] >>> sorted(index['connected']) [28, 54] >>> for key in sorted(index): ... print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key])))) ... connected 28, 54 depth first search 55 neighbor 27, 64, 77 path 19, 72 shortest path 55 spanning tree 16, 99 vertex 54 A: You can use the collections module in the standard library which has an OrderedDict type which is just a dict that remembers order of insertion. If you want a dictionary in alphabetical order, where your values are ordered lists: sorted_index = collections.OrderedDict(sorted(zip(index, map(sorted, index.values())))) Since that is a bit of an ugly line you can expand it out as. sorted_items = sorted(index.items()) sorted_items = [(k, sorted(v)) for k, v in sorted_items] sorted_index = collections.OrderedDict(sorted_items)
{ "language": "en", "url": "https://stackoverflow.com/questions/17845170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to let MySQL NOW() function return the user time I ran into a very tricky MySQL issue.. Our DB is using type DateTime for the updated_at column, and now is too late to change it back to TimeStamp. I'm thus trying to add a trigger to update this updated_at column on table changing. The following is what I did: CREATE TRIGGER foo_schema.bar_datetime_trigger BEFORE UPDATE ON foo_schema.bar FOR EACH ROW set NEW.updated_at = NOW(); The NOW() function here returns the DB time; however, what I actually want is to set the udpated_at as the user time (Meaning the time of the user who made changes to table bar). Is it possible to handle this in MySQL?
{ "language": "en", "url": "https://stackoverflow.com/questions/27241979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does a Hidden Window appear when taking a screenshot in WPF using C#? I have a WPF application that helps me take Screenshots of the entire screen. The application contains a small Window with a button inside, which if I click on, a capture of the screen is taken, and saved on my drive. I wanted to hide this little Window just before the capture is taken, so it won't be included in the capture, here's what I tried : StartSnipping = new RelayCommand(() => { // I hide it here !! WindowVisibility = Visibility.Hidden; //Than I take the screen shot var screen = Screen.PrimaryScreen; var bitmap = new Bitmap(screen.Bounds.Width, screen.Bounds.Height); using (var graphics = Graphics.FromImage(bitmap)) { graphics.CopyFromScreen(new Point(screen.Bounds.Left, screen.Bounds.Top), new Point(0, 0), screen.Bounds.Size); } //I save the screen shot bitmap.Save(@"C:/Users/Aymen/Desktop/test.png", ImageFormat.Png); }); Now, assuming that the line : WindowVisibility = Visibility.Hidden; really works, well, I'm sure of this because after all that method completes running, the window is indeed hidden. And assuming that the screenshot is successfully taken and saved and still contains that window, which is supposed to be hidden like 1 second before the screen capture, my question is : Why this hidden window is still appearing in the screenshot ?? and what should I do to make it not appear in the screenshot ?? A: Not sure but it seems that using : WindowVisibility = Visibility.Hidden; Doesn't help keeping the window from appearing when taking a screenshot, I had to hide the window using the .Hide() method: Application.Current.MainWindow.Hide(); That worked just well, bust still doesn't have any explanation why the Visibility.Hidden keeps the window appearing in screenshots.
{ "language": "en", "url": "https://stackoverflow.com/questions/24828845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using a ssl enabled node.js sveltekit app alongside tomcat server which is currently hosting apps in https I am currently having a server with tomcat web server hosting few apps in https. Now we built a sveltekit app that is not static. I am trying to add this app be exposed as a https site. I found many articles that point out using apache as a reverse proxy and pointing to the node.js app. However in my case, there are already 2 apps on tomcat running in https. I this case, kindly confirm if i need to move all the ssl logic to the apache and setup tomcat to run in http and allow apache to receive https and forward to tomcat as http and return the response back. I am also starting to experiment with this, but wanted to know if this is a production ready approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/74703378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }