text
stringlengths
15
59.8k
meta
dict
Q: Sending arrays to REST services in CakePHP I'm currently writing a REST service using CakePHP and I was wondering how can I send an array of item_ids through REST to an action. class ItemsController extends AppController { var $components = array('RequestHandler'); var $helpers = array('Text', 'Xml'); function index() { } function create($itemsArr) { //handle $itemsArr here and sends data as xml to views. } } I guess my real question is, How will the request look like? http://mysite/items/create/??? I guess I can pass the values as 1 argument using implode(someSeperator, array) but is there a better solution? Thanks in advance A: This is not REST. REST is about using HTTP, not XML! A typical HTTP REQUEST to create an item would be like this PUT http://mysite/items/ HTTP/1.1 Host: xxxxx <myitem> <text> asdasdas </text> </myitem> And you can use whatever you want in the body of the request. XML, JSON, PHP SERIALIZE or your own data format. A: If you truly want to be RESTful about this, you'd definitely want to use a POST request to create records. That's if you care to be strict about the standard, but it would also help you because I'm reading that your array's length could vary tremendously - sometimes 1 ID, perhaps 30 other times, etc. URI query strings do (or used to?) have a maximum character limit that you could conceivably bump up against. If you roll with a POST request, you could easily passing in a comma-delimited list (think about how a field name with multiple checkboxes is passed) or, my favorite mechanism, a JSON-encoded array (represented as a string that can easily be JSON-decoded on the other side. A: This actually applies to any web page, not just CakePHP. Any web page which wants to send a large number of fields has to include them all in their POST request. If you had a web page form with 50 inputs and a submit at the bottom, the page would by default serialise the data and send it in the form request. If you don't want all the data sent in seperate bars, then using a seperator would work fine too and would mean they all went in 1 parameter. Somthing like: http://mysite/items/create?mydata=23-45-65-32-43-54-23-23-656-77 A: another option: $safedata = base64_encode(serialize($arrayofdata)); and pass it to URL as safe string. then uncompress it: $data = unserialize(base64_decode($safedata);
{ "language": "en", "url": "https://stackoverflow.com/questions/901014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why am I getting this 'enum' is not a class or a namespace error? I need call a method with this signature in my Manager class: void createPlayer(Player& player, PlayerType& playerType); I have a Player defined like so: using namespace std; enum PlayerType { FORWARD, DEFENSEMAN, GOALIE }; class Player { public: Player(); void setType(PlayerType); private: PlayerType type; }; This is how I try to call the method in main ... #include "Player.h" #include "Manager.h" int main() { Manager manager; Player player; PlayerType t = PlayerType::FORWARD; manager.createPlayer(player, t); return 0; } ... but it fails to compile with this error: Main.cc: In function ‘int main()’: Main.cc:12:18: error: ‘PlayerType’ is not a class or namespace Any ideas? Note: I cannot change the signature of the createPlayer method. A: Unfortunately enum by default doesn't create an enum namespace. So when declaring: enum PlayerType { FORWARD, DEFENSEMAN, GOALIE }; you'll have to use it like this: auto x = FORWARD; Thankfully, though, C++11 introduced enum class or enum struct to solve this issue: enum class PlayerType { FORWARD, DEFENSEMAN, GOALIE }; You'll then be able to access it like you did: auto x = PlayerType::FORWARD; A: enum doesn´t create a namespace. Therefor PlayerType t = PlayerType::FORWARD; should be changed to: PlayerType t = FORWARD; Notice that c++11 introduce enum classes, which have a namespace. Beside this MSVC has an extension which treats (regular) enums like they have namespace. So your code should actually work with MSVC. A: Your error seems to be in this line: PlayerType t = PlayerType::FORWARD; As far as I know, the scope resolution operator (::) is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions (like Visual Studio). Therefore you can't use it to reference an specific value from the enumerator. Also, C++98 enums have the problem of polluting the namespace in which they are defined which can lead to name clash. Luckily C++11 solved this introducing the enum class. For more information check Stroustrup's FAQ: http://www.stroustrup.com/C++11FAQ.html#enum A: add a static function say getForward: class Player { public: Player(); void setType(PlayerType); static PlayerType getForward { return FORWARD; } private: PlayerType type; }; Then use it in main: manager.createPlayer(player, Player::getForward()); This should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/22238391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to efficiently redirect url in Cloudfront without S3 My requirement is to redirect url from Cloudfront. So for this I see there are possibilities to do using Lambda function as mentioned here. My application is not hosted in S3, rather it is hosted in Apache webserver which is running on some EC2 instance. Because redirect rules are many so I would like Lambda function to read configuration of redirect mapping from some other place but I do not know what could be the other place. I see it is possible to read either from S3 or SNS topic. Could you please suggest what is the best practice to store redirect mapping and handle redirect via Lambda? As I understood it is not possible to do using Route53 to read mapping and then do redirect. Please correct me if I am wrong. I am new to this and would request your expert guidance! A: I think you are mistaking some concepts. If I got it right you need a CDN for an Apache server on EC2. In that case you want Cloudfront with EC2 as origin . https://aws.amazon.com/cloudfront/getting-started/EC2/
{ "language": "en", "url": "https://stackoverflow.com/questions/65863424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Servlet running under Grails How can I run a servlet (UploadAction from GWTUpload project) under grails? I've successfully added the servlet and use it from the web.xml file. However, I really want to wrap some logic around the doPost/doGet methods using the grails framework (gorm). Can I just subclass the servlet as a Controller, maybe just instantiate the servlet in the controller and call init()? I'm not sure how to do this properly. A: The simplest thing that comes to my mind is: * *write a grails controller, instantiate the servlet (once, in the contstructor or in @PostConstruct) and call init()` *map the controller method (via UrlMappings.groovy) to the url that your servlet would be mapped *call servlet.service(request, response). It's a bit of a hack though. Another way is to get ahold of a spring (grails) bean in a filter applied to the servlet, with WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()) and invoke the custom logic there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7956661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fluid grid layout I am creating a form. In the form I have 20+ html controls i.e. textboxes, checkboxes, textarea. I want to arrange all the html elements in a table format. But when the screen sizes is reduces the number of column should get reduced. example. Initially there will be 4 columns. when screen size reduces no of columns becomes 3. on further screen size reduction no of columns becomes 2 and then to 1. How this can be achieved? A: Use Flexbox Layout to design flexible responsive layout structure: * {box-sizing: border-box;} /* Style Row */ .row { display: -webkit-flex; -webkit-flex-wrap: wrap; display: flex; flex-wrap: wrap; } /* Make the columns stack on top of each other */ .row > .column { width: 100%; padding-right: 15px; padding-left: 15px; } /* Responsive layout - makes a two column-layout (50%/50% split) */ @media screen and (min-width: 600px) { .row > .column { flex: 0 0 50%; max-width: 50%; } } /* Responsive layout - makes a four column-layout (25%/25% split) */ @media screen and (min-width: 991px) { .row > .column { flex: 0 0 25%; max-width: 25%; } } <p>Resize this frame to see the responsive effect!</p> <div class="row"> <!-- First Column --> <div class="column" style="background-color: #dc3545;"> <h2>Column 1</h2> <p>Some Text...</p> <p>Some Text...</p> <p>Some Text...</p> </div> <!-- Second Column --> <div class="column" style="background-color: #ffc107;"> <h2>Column 2</h2> <p>Some Text...</p> <p>Some Text...</p> <p>Some Text...</p> </div> <!-- Third Column --> <div class="column" style="background-color: #007eff;"> <h2>Column 3</h2> <p>Some Text...</p> <p>Some Text...</p> <p>Some Text...</p> </div> <!-- Fourth Column --> <div class="column" style="background-color: #28a745;"> <h2>Column 4</h2> <p>Some Text...</p> <p>Some Text...</p> <p>Some Text...</p> </div> </div> Reference: Create a Mixed Column Layout
{ "language": "en", "url": "https://stackoverflow.com/questions/58703918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: split column in multiple columns in sql view I have created a view for the Leco results and it is attached here as ‘Leco Teble’ excel file. I would like to have same view in database with ‘expanded table’ column based on the sample ID’s as given in the expanded table. Would you please arrange with one of your team member to create a script to expand the table in the same view. Last column in the table “Shift” should be picked up based on the time with the sample ID. 6am to 6pm is day shift.
{ "language": "en", "url": "https://stackoverflow.com/questions/74809044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting records from fact table and dimension table I want to delete records from target table as records deleted from a source. I used merge/rows and delete stop both individuals, but I solved my problem in delete case when I deleted record from source. Then, after transformation fact table had only that record which was deleted from the source while it must had all those instead of this. I want the same method for the dim table also.enter image description here
{ "language": "en", "url": "https://stackoverflow.com/questions/48112927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alert to detect the available space on the hard drive I would like to know if it is possible to create an alert in a google cloud platform instance, to identify that a hard drive of an instance is 90% busy, for example, and that this sends a notification to some user. I await your response, and thanks in advance. A: You can use Google Stackdrive to setup alerts and have an email sent. However, disk percentage busy is not an available metric. You can chose from Disk Read I/O and Disk Write I/O bytes per second and set a threshold for the metric. * *Go to the Google Console Stackdriver section. Click on Monitoring. *Select Alerting -> Create Policy in the left panel. *Create your alerting policy based upon Conditions and Notifications You can create custom metrics. This link describes how. Creating Custom Metrics
{ "language": "en", "url": "https://stackoverflow.com/questions/52930459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Missing choices 11 in case statement and failed synthesizing module LIBRARY ieee; USE ieee.std_logic_1164.ALL; entity mucodec is port ( din : IN std_logic_vector(2 downto 0); valid : IN std_logic; clr : IN std_logic; clk : IN std_logic; dout : INOUT std_logic_vector(7 downto 0); dvalid : OUT std_logic; error : OUT std_logic); end mucodec; architecture Behavioral of mucodec is type state_type is (St_RESET, St_ERROR, St_BOS_1, St_BOS_2, St_BOS_3, St_BOS_4, St_EOS_1, St_EOS_2, St_EOS_3, St_EOS_4, St_DECODE, St_Out); signal state, next_state : state_type := St_RESET; -- Define additional signal needed here as needed begin sync_process: process (clk, clr) begin if clr = '1' then state <= St_RESET; elsif rising_edge(clk) then state <= next_state; end if; end process; state_logic: process (state) begin -- Next State Logic -- Complete the following: next_state <= state; case(state) is when St_RESET => if (valid = '1') THEN next_state <= St_BOS_1; end if; when St_ERROR => if (valid = '1' and din = "000") THEN if (valid = '1' and din = "111") THEN if (valid = '1' and din = "000") THEN if ( valid = '1' and din = "111") THEN next_state <= St_DECODE; else next_state <= St_ERROR; end if; end if; end if; end if; when St_BOS_1 => if (valid = '1' and din = "000") THEN next_state <= St_BOS_2; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_BOS_2 => if (valid = '1' and din = "111") THEN next_state <= St_BOS_3; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_BOS_3 => if (valid = '1' and din = "000") THEN next_state <= St_BOS_4; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_BOS_4 => if (valid = '1' and din = "111") THEN next_state <= St_DECODE; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_EOS_1 => if (valid = '1' and din = "111") THEN next_state <= St_EOS_2; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_EOS_2 => if (valid = '1' and din = "000") THEN next_state <= St_EOS_3; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_EOS_3 => if (valid = '1' and din = "111") THEN next_state <= St_EOS_4; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; else next_state <= St_BOS_1; end if; when St_EOS_4 => if (valid = '1' and din = "000") THEN next_state <= St_Out; elsif (valid = '1' and din > "111") THEN next_state <= St_ERROR; end if; when St_DECODE => if (valid = '1') THEN for i in 0 to 7 loop if (din = "001") THEN if (din = "010") THEN dout <= x"41"; elsif (din = "011") THEN dout <= x"42"; elsif (din = "100") THEN dout <= x"43"; elsif (din = "101") THEN dout <= x"44"; elsif (din = "110") THEN dout <= x"45"; end if; elsif (din = "010") THEN if (din = "001") THEN dout <= x"46"; elsif (din = "011") THEN dout <= x"47"; elsif (din = "100") THEN dout <= x"48"; elsif (din = "101") THEN dout <= x"49"; elsif (din = "110") THEN dout <= x"4A"; end if; elsif (din = "011") THEN if (din = "001") THEN dout <= x"4B"; elsif (din = "010") THEN dout <= x"4C"; elsif (din = "100") THEN dout <= x"4D"; elsif (din = "101") THEN dout <= x"4E"; elsif (din = "110") THEN dout <= x"4F"; end if; elsif (din = "100") THEN if (din = "001") THEN dout <= x"50"; elsif (din = "010") THEN dout <= x"51"; elsif (din = "011") THEN dout <= x"52"; elsif (din = "101") THEN dout <= x"53"; elsif (din = "110") THEN dout <= x"54"; end if; elsif (din = "101") THEN if (din = "001") THEN dout <= x"55"; elsif (din = "010") THEN dout <= x"56"; elsif (din = "011") THEN dout <= x"57"; elsif (din = "100") THEN dout <= x"58"; elsif (din = "110") THEN dout <= x"59"; end if; elsif (din = "110") THEN if (din = "001") THEN dout <= x"5A"; elsif (din = "010") THEN dout <= x"5B"; elsif (din = "011") THEN dout <= x"5C"; elsif (din = "100") THEN dout <= x"5D"; elsif (din = "101") THEN dout <= x"5E"; end if; end if; dvalid <= '1'; end loop; next_state <= St_EOS_1; end if; end case; end process; output_logic: process (state) begin if (state = St_Out and valid = '1') THEN next_state <= St_RESET; end if; end process; end Behavioral; A: I suggest checking your code. It is missing a choice for St_Out of the state signal. Case statement must cover all possible values. This can be done using the when others => case, but this may not be suitable. You will also have issues with this code. Your state_logic process is missing many signals. This will lead to simulation synthesis mismatch. You need to put every signal read inside the process inside the sensitivity list for an asynchronous process. An easy fix for this is to use the VHDL 2008 process(all). This will force the compiler to work what the sensitivity list should be from the code inside the process.
{ "language": "en", "url": "https://stackoverflow.com/questions/74027551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: working out an average I have a nested list like so: temperature = [["Jan", 12, 18, 16, 18], ["Feb", 10, 20, 50, 50], ["Mar", 23, 32, 10, 32]] the list contains all the months up until December with the 3 highest temp recorded over the entire month and then the highest out of the 3 appended to the end of the list. I have worked out the highest temp for each month in the following way: def sortTemp(): for temp in temperatures: temp = [temp[0], temp[4]] highest.append(temp) highest.sort() print(highest) This works, however I had to work out the max values beforehand, and append it to the temperature list as explained above. Is there an easier way to do this? Also, how do I work out the average temp of each month using the data provided in the temperature list, sorted by the highest average? Output should be like: AverageTemp = [["Month", AverageTemp], ["Month", AverageTemp]] A: You can use a list comprehension to compute the averages >>> AverageTemp = [[i[0], sum(i[1:])/len(i[1:])] for i in temperature] >>> AverageTemp [['Jan', 16.0], ['Feb', 32.5], ['Mar', 24.25]] Or if you have numpy >>> import numpy as np >>> AverageTemp = [[i[0], np.mean(i[1:])] for i in temperature] >>> AverageTemp [['Jan', 16.0], ['Feb', 32.5], ['Mar', 24.25]] Then to sort you can use the key and reverse arguments >>> AverageTemp = sorted([[i[0], np.mean(i[1:])] for i in temperature], key = lambda i: i[1], reverse = True) >>> AverageTemp [['Feb', 32.5], ['Mar', 24.25], ['Jan', 16.0]] A: You can use a list comprehension within sorted function : >>> from operator import itemgetter >>> sorted([[l[0],sum(l[1:])/4]for l in temperature],key=itemgetter(1),reverse=True) [['Feb', 32], ['Mar', 24], ['Jan', 16]] In preceding code you first loop over your list then get the first element and the avg of the rest by [l[0],sum(l[1:])/4] and use operator.itemgetter as the key of your sorted function to sort your result based on the second item (the average) A: Understanding more about list comprehension and slice notation will really help you do this simply with pythonic code. To explain @CoryKramer's first answer: >>> AverageTemp = [[i[0], sum(i[1:4])/len(i[1:4])] for i in temperature] >>> AverageTemp [['Jan', 15], ['Feb', 26], ['Mar', 21]] What he is doing is using i to cycle through the lists in temperature (which is a list of lists) and then using slice notation to get the info you need. So, obviously i[0] is your month, but the notation sum(i[1:4]) gets the sum of the items in the list from index 1 to the 3 using slice notation. He then divides by the length and creates the list of lists AverageTemp with the information you need. Note: I have edited his answer to not include the high temperature twice per the comment from @TigerhawkT3. A: That's not a very good structure for the given data: you have differentiated items (name of a month, temperatures, maximum temperature) as undifferentiated list elements. I would recommend dictionaries or objects. months = {"Jan":[12, 18, 16], "Feb":[10, 20, 50], "Mar":[23, 32, 10]} for month in sorted(months, key=lambda x: sum(months.get(x))/len(months.get(x)), reverse=True): temps = months.get(month) print(month, max(temps), sum(temps)/len(temps)) Result: Feb 50 26.666666666666668 Mar 32 21.666666666666668 Jan 18 15.333333333333334 class Month: def __init__(self, name, *temps): self.name = name self.temps = temps def average(self): return sum(self.temps)/len(self.temps) def maximum(self): return max(self.temps) months = [Month('Jan', 12, 18, 16), Month('Feb', 10, 20, 50), Month('Mar', 23, 32, 10)] for month in sorted(months, key=lambda x: x.average(), reverse=True): print(month.name, month.maximum(), month.average()) Result: Feb 50 26.666666666666668 Mar 32 21.666666666666668 Jan 18 15.333333333333334
{ "language": "en", "url": "https://stackoverflow.com/questions/30652369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Symbol to method call Is there a way to transform a symbol to a method call? I know it's possible for a String, but not for a symbol. I have this code in conveyance.rb: def boats boats = [] User.all.each{ |u| boats += u.boats} boats end def boats_nb self.boats.length end def cars cars = [] User.all.each{ |u| cars += u.cars} cars end def cars_nb self.cars.length end I would like to know if there is a means to make a method like that: def conveyances(:symb) c = [] User.all.each{ |u| c += u.to_method(:symb) } c end def conveyances_nb(:symb) User.to_method(:symb).length end A: You could use Object#public_send method: def conveyqnces_nb(symb) User.public_send(symb).length end or, if you would like, Object#send might be suitable. The difference is that send allows to call private and protected methods, while public_send acts as typical method call - it raises an error if method is private or protected and the caller object isn't allowed to call it. A: Use the #send instance method u.send(:symb)
{ "language": "en", "url": "https://stackoverflow.com/questions/20124104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: input css rendering inconsistencies across browsers The input button is incorrectly higher than the input field. I used Firebug to copy all the styles applied to the 3 elements in question (the containing p element and the 2 child input elements) to replicate the problem. http://jsfiddle.net/XBjz3/ I have a feeling it's to do with me using negative relative positioning on the input button. Displays as it should in * *Firefox 12 *Chrome 19 *Internet Explorer 9 Displays wrong in * *Android 2.3.5 browser *iOS 5.1 browser *Safari 5.1.7 *Opera 11.6 It's strange that it displays fine in Chrome when the 3 other webkit browsers renders it incorrectly. A: Instead of using top:-0.5em; You can use bottom : 0.4em; As its not good practice to use negative values for position. A: check this one i hope this will help you.. HTML <p> <input type="password" class="pw-box" id="pwbox-33" name="post_password"> <input type="submit" class="pw-submit" value="Submit" name="Submit"> </p> CSS p { width:50%; display: inline; float: left; padding-left: 1%; padding-right: 1%; position: relative; font-size: 1em; line-height: 1.5em; margin:20px 0 0 20px; background:rgba(0,0,0,0.1); } #pwbox-33 { width: 200px; border:0; background: #606D80; border-top:solid 1px #1F3453; color: #DCE0E6; margin: 0; padding: 0.5em; text-shadow: 0 1px 0 #1F1F20; vertical-align: top; } .pw-submit{ cursor: pointer; background:#2B4C7E; color: #DCE0E6; padding: 0.5em 1em; position: absolute; text-shadow: 0 -1px 0 #1F1F20; top: -0.3em; border:0; font-size:12px; font-family:arial; left:200px; border-bottom:solid 0.5em #0E2952; outline:0; } http://jsfiddle.net/YjNJ5/3/ A: Found a solution that looks exactly the same as intended. http://jsfiddle.net/XBjz3/8/ Here are the changes from the original. #pwbox-33 { vertical-align: bottom; } .pw-submit { top: 0; vertical-align: bottom; } Tested to work on Firefox, Chrome, IE, Safari, Opera, and Android stock browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/10647491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone simulator screenshot not capturing device bezel I'm trying to capture a simulator screenshot using Xcode 12. Right now, even though the "Show Device Bezels" option is enabled (and it shows the bezels on the screen), when I take the screenshot, the bezel isn't part of the resulting screenshot. I've tried through the camera button on the simulator, through the "Save Screen" menu item, through "xcrun simctl screenshot" command-line as well, but it doesn't work correctly. Weirdly, it was working fine just yesterday, but I was playing with setting the "defaults write com.apple.screencapture disable-shadow -bool TRUE" from the command-line (to prevent the shadow in video capture of the window) ... I'm not sure if that's related to this issue, and I flipped it back to FALSE, but that doesn't seem to help either. I've also tried restarting the simulator, restarting the Mac, switching "Show Bezel" on/off, using Xcode11, erasing contents of simulator.... but it's still not working. Very frustrating. This is what it looks like: Any tips of what I can try? Thanks. A: The bezel is not saved as part of the screenshots from Simulator.app / simctl. The only option you have is whether or not the framebuffer mask is applied. If you want the bezel, you'll need to use the macOS screenshot support. Hit shift-cmd-4, then hit space to toogle from "draw the rectangle" mode to "select the window" mode. Then click on the window to take a screenshot.
{ "language": "en", "url": "https://stackoverflow.com/questions/64178350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Redundant distributed NFS file system and replication factor > 1. Is it safe for Kafka deployment? I have a cluster Kafka set up where the log.dir is set to a mounted NFS path pointing to distributed file system which all the brokers have access to. Since the distributed file system provides all the redundancy I need, is it really necessary have a replication factor > 1? Also, I read in this article https://engineering.skybettingandgaming.com/2018/07/10/kafka-nfs/ that you are not recommended to have the logs on an NFS mounted filesystem. Does this still hold and does anyone have any more experience in doing this? A: From the storage side, maybe this is safe, but your single replica is only able to be read / sent from a single broker. If that machine goes down, the data will still be available on your backend, sure, but you cannot serve requests for it without knowing there is another replica for that topic (replication factor < 2).
{ "language": "en", "url": "https://stackoverflow.com/questions/54127793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Output only one blank line fresh-line outputs a newline only if we are not already at start of the line, in other words goes to the next line but never produces a blank line, in other words outputs a maximum of one consecutive newline character. I need a function that outputs a blank line only if we have not just output one already, in other words outputs a maximum of two consecutive newline characters. Or put another way, I'm looking for an idempotent blank-line function, one which will output exactly one blank line even if called several times. What's the best way to do this? A: If I understand correctly your question, I think you can use the following property of fresh-line (see the manual): fresh-line returns true if it outputs a newline; otherwise it returns false. to define something like: (defun my-fresh-line () (unless (fresh-line) (terpri))) If, on the other hand, you want always a blank line after the current written text, be it terminated with a new line or not, you can define something like: (define blank-line () (fresh-line) (terpri)) and then call it after the current output.
{ "language": "en", "url": "https://stackoverflow.com/questions/52175542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jboss-eap-6.1 oracle driver definition when installed as deployment I have several Jboss EAP 6.1 installations working with Oracle driver installed as a module. This is the standard configuration I use in standalone.xml: <datasource jndi-name="java:jboss/fooDatasource" pool-name="java:jboss/fooDatasource" enabled="true" use-java-context="false" > <connection-url>jdbc:oracle:thin:@1.2.3.4:1527/SOMEDB.foo</connection-url> <driver>oracle</driver> <security> <user-name>xxxxx</user-name> <password>xxxxxxxxx</password> </security> [...] </datasource> <driver name="oracle" module="oracle.jdbc"> <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class> <datasource-class>oracle.jdbc.OracleDriver</datasource-class> </driver> The ojdbc6.jar is in $JBOSS_HOME/modules/system/layers/base/oracle/jdbc/main/ together with the appropriate module.xml and everything works fine. Now a customer required to install the driver as a deployment, so I moved ojdbc6.jar to $JBOSS_HOME/standalone/deployments/ and I see from logs that it is deployed without errors: [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) JBAS010403: Deploying JDBC-compliant driver class oracle.jdbc.OracleDriver (version 11.2) INFO [org.jboss.as.server] (ServerService Thread Pool -- 25) JBAS018559: Deployed "ojdbc6.jar" (runtime-name : "ojdbc6.jar") But I don't know how to edit my standalone.xml to make it work again: i tried to edit the driver definition "module" attribute with several different values (ojdbc6.jar, deployment.ojdbc6.jar, oracle.jdbc.OracleDriver...) but none seem to "match" and Jboss keeps throwing errors at startup: ERROR [org.jboss.as.controller.management-operation] (ServerService Thread Pool -- 24) JBAS014613: Operation ("add") failed - address: ([ ("subsystem" => "datasources"), ("jdbc-driver" => "oracle") ]) - failure description: "JBAS010441: Failed to load module for driver [ojdbc6.jar]" [...] INFO [org.jboss.as.controller] (Controller Boot Thread) JBAS014774: Service status report JBAS014775: New missing/unsatisfied dependencies: service jboss.jdbc-driver.oracle (missing) dependents: [service jboss.driver-demander.java:jboss/spiDatasource, service jboss.data-source.java:jboss/fooDatasource] Could anyone please provide a working example of the driver definition? Thanks A: Ok, I found the answer myself. Surprisingly, all the guides I found around explain how to do this configuration via web admin interface or via jboss-cli, but no one in the Jboss community seem to bother explaining how to manually edit the standalone.xml to do the job. This is a working example (basically I just deleted the entire Oracle driver definition section and replaced the driver name in the datasource definition with the name of the runtime name of the deployed jar file): <datasource jta="false" jndi-name="java:/jdbc/fooDS" pool-name="foo-ds" use-ccm="false"> <connection-url>jdbc:oracle:thin:@1.2.3.4:1527/SOMEDB.foo</connection-url> <driver-class>oracle.jdbc.OracleDriver</driver-class> <driver>ojdbc6.jar</driver> [...] other datasource stuff here </datasource> # DELETE FROM HERE... <driver name="oracle" module="oracle.jdbc"> <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class> <datasource-class>oracle.jdbc.OracleDriver</datasource-class> </driver> # ...TO HERE That's all. A: Probably you have to mention in this way... <subsystem xmlns="urn:jboss:domain:datasources:1.1"> <datasources> <datasource jndi-name="java:jboss/XXX" pool-name="XXX" enabled="true" use-java-context="true"> <connection-url>jdbc:oracle:thin:@SID:PORT:DBNAME</connection-url> <driver>oracle</driver> <security> <user-name>user</user-name> <password>password</password> </security> </datasource> <drivers> <driver name="oracle" module="com.oracle"> <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class> <datasource-class>oracle.jdbc.OracleDriver</datasource-class> </driver> </drivers> </datasources> </subsystem> A: * *Create directories like x1/x2/main *Create module.xml file under main directory *Keep ojdbc6-11.1.1.3.0.jar in main directory level In Module.xml <module xmlns="urn:jboss:module:1.1" name="x1.x2"> <properties> <property name="jboss.api" value="unsupported"/> </properties> <resources> <resource-root path="ojdbc6-11.1.1.3.0.jar"/> </resources> <dependencies> <module name="javax.api"/> <module name="javax.transaction.api"/> <module name="javax.servlet.api" optional="true"/> </dependencies> In domain.xml <datasource jndi-name="java:/TestName" pool-name="TestName" enabled="true" use-java-context="true"> <connection-url>jdbc:oracle:thin:@ldap://xxxxx:3000/UKXXX,cn=OracleContext,dc=dcm,dc=XXXX</connection-url> <driver>dps</driver> <security> <user-name>XXXXX</user-name> <password>*****</password> </security> </datasource> <drivers> <driver name="dps" module="x1.x2"> <xa-datasource-class>oracle.jdbc.driver.OracleDriver</xa-datasource-class> </driver> </driver> </drivers> Try to keep the correct ojdbc jar, some versions won't work :)
{ "language": "en", "url": "https://stackoverflow.com/questions/25687972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: prototype.js innerHTML does not work with IE Apparently IE (10) does not like this piece of code: $('size_list').innerHTML = '<form id="dropdown_menu"><select id="dropdown_options"></select></form>'; The dropdown menu is not being generated. I get an Unknown Run Time error, which is really "helpful". The next line of code is: $('dropdown_options').innerHTML = '<option>Choose size</option>'; But when I debug - I don't even get till here. The 'size_list' element is just a simple empty div: <div id="size_list" style="float:right; margin-top: -22px;"></div> I found some info that states .innerHTML does not really work with IE, but I have many other places in my script where I assign even bigger chunks of HTML to div elements, through .innerHTML and all works. Except the upper stated assigning of dropdown form. A: Try this: $('#size_list').html('<form id="dropdown_menu"><select id="dropdown_options"></select></form>'); $('#dropdown_options').html('<option>Choose size</option>'); You can't use a hammer as a wrench... Or use document.getElementById('size_list').innerHTML or use $('#size_list').html() Don't forget to put a # before an id selector in jQuery and a . before a class selector otherwise jQuery tries to find a <size_list> tag which won't exist in the DOM tree. A: First of all, while it may be convenient to add select options using the direct insert html methods, it rarely works universally. The bulletproof way to add options to a select is to build them up one at a time in a loop, assigning their value and label the old-fashioned way. var form = new Element('form', {id: 'dropdown_menu' }); var picker = new Element('select', {id: 'dropdown_options', size: 1 }); $('size_list').insert(form); form.insert(picker); picker.options[picker.options.length] = new Option('Choose size', ''); // want to add a list of elements in a loop? $w('Foo Bar Baz').each(function(val){ picker.options[picker.options.length] = new Option(val, val); }); IE has never dealt with modifications of the select element gracefully at all, this goes back to IE 5 when I first started trying to do this sort of thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/22169660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery focus after submit on last input field edited On jQuery keyup on two IDs a function is executed. $('#supplier_name').keyup(function(){ clearTimeout(typingTimer); if ($('#supplier_name').val) { typingTimer = setTimeout(doneTyping, doneTypingInterval); } $.cookie("inputFocus", "#supplier_name"); }); After this the form is submitted. I want to do jQuery .focus on the ID which led the keyup function to execute. So if I entered text into #supplier_name after form submit I want the focus to be on that. Vice versa with #aircraft_type. EDIT: I am trying to do this via cookies however it doesn't seem to be working. How do I do this with the following jQuery code: <script> $(document).ready(function() { $("#state").change(function () { this.form.submit(); }) $.cookie("inputFocus").focus(); $("#supplier_name").val($("#supplier_name").val()); $("#aircraft_type").val($("#aircraft_type").val()); var typingTimer; var doneTypingInterval = 800; $('#supplier_name').keyup(function(){ clearTimeout(typingTimer); if ($('#supplier_name').val) { typingTimer = setTimeout(doneTyping, doneTypingInterval); } $.cookie("inputFocus", "#supplier_name"); }); $('#aircraft_type').keyup(function(){ clearTimeout(typingTimer); if ($('#aircraft_type').val) { typingTimer = setTimeout(doneTyping, doneTypingInterval); } $.cookie("inputFocus", "#aircraft_type"); }); function doneTyping () { $("form").submit(); } }); </script> A: The solution to the above problem was to create an object to use focus() and to add the jQquery cookie plug-in. The change is below: "$.cookie("inputFocus").focus();" to "$($.cookie("inputFocus")).focus()" Added the below code to the page: ""
{ "language": "en", "url": "https://stackoverflow.com/questions/14593381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass all uncaught errors from the framework to Crashlytics with custom parameter I got uncaught errors form the framework to Crashlytics. But it is difficult to fix the issue because I don't know which screen or record caused the error. For example below error, I only know that it is invalid image from CacheNetworkImage package. But It is very difficult to find out which screen or which record. Is there any way to pass screen name or custom parameter. I can't find the way to record. Fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: Exception: Invalid image data. Error thrown Instance of 'ErrorDescription'. at .instantiateImageCodec(dart:ui) at ImageLoader.loadAsync(_image_loader.dart:59) at new MultiImageStreamCompleter.(multi_image_stream_completer.dart:25) Below code pass all uncaught errors from the framework to Crashlytics. FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError; A: Use setCustomKey to add values to reports. FirebaseCrashlytics.instance.setCustomKey('str_key', 'hello'); See Customize your Firebase Crashlytics crash reports for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/72818307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EclipseFP on Indigo, issues with Maven? I'm trying to install EclipseFP, using the usual Eclipse "Install new software" approach. However, at the "Installation Details" window, it says "This operation cannot be completed", giving me the following details: Cannot complete the install because one or more required items could not be found. Software currently installed: Shared profile 1.0.0.1316138547364 (SharedProfile_epp.package.java 1.0.0.1316138547364) Missing requirement: Shared profile 1.0.0.1316138547364 (SharedProfile_epp.package.java 1.0.0.1316138547364) requires 'org.maven.ide.eclipse [1.0.100.20110804-1717]' but it could not be found I just barely downloaded a fresh Eclipse: Eclipse IDE for Java Developers Version: Indigo Service Release 1 Build id: 20110916-0149 Does EclipseFP actually work on Indigo? Do I need to download an older Eclipse? Or perhaps there are additional steps I need to take to install Maven? (I don't want to download/install Maven if I don't have to.) A: Since Kane neglected to turn his comment into an answer, I may as well state it plainly here: This issue arises when you put the Eclipse folder in a location where Windows will have issues with access control (e.g. the Program Files folder). By moving the folder to my personal user's folder, I was able to use Eclipse normally without this issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/8059427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: audio html5 with jquery to play next track I have html5 like this <audio controls class="audioPlayer" > <source class="iSong" src="1.mp3" type="audio/mpeg"> <source class="iSong" src="2.mp3" type="audio/mpeg"> <source class="iSong" src="3.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> I want add jquery for button nextSong because my song always play only last one. A: Adding multiple sources to an audio element does not create a playlist, it is to support different audio formats and your browser will simply play the first one it can, which is why you say only the last one is playing. To have multiple songs you choose between you will have to write some javascript. Here is some information on audio in javascript. It sounds like you will have to create a separate button for playing the next song, add a click event that changes the source of the audio element and plays it.
{ "language": "en", "url": "https://stackoverflow.com/questions/36092740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Issue querying a materialized view redshift I've created a materialized view in redshift as follows: create materialized view stats as select * from t1 however when i try to query it: select * from stats I get this error: [2022-06-26 15:09:35] [XX000] ERROR: Failed assertion at rewriteHandler.c:883 - CheckMvInternalTables(mv_id). invalid MV internal tables. I can't find anything on the internet about this so I'm a bit at a loss. Any clues on where i can go with this? A: Solution: Set AutoRefresh to ON on the mv (as it defaults to off). Or manually trigger the refresh.
{ "language": "en", "url": "https://stackoverflow.com/questions/72761906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Code is working properly but if data is empty that time validation is not working i have made a code generated random number and save all number in database(that part of code is working) but i have problem in validation without enter any no on view page redirect this url admin_manage_epin.ctp, validation not working admin_create_epin.ctp(view) <tr> Add E-pin:(No of E-Pin) <td><?php echo $this->Form->input('e_pin',array('label'=>false));?></td> </tr> epins_controllers.php(controller) public function admin_create_epin(){ if(!empty($this->data)){ $limit = $this->data['Epin']['e_pin']; for($i=0;$i<$limit;$i++) { $random = substr(number_format(time() * rand(),0,'',''),0,11)."<br/>"; $this->data['Epin']['e_pin'] = $random; $this->Epin->id =null; $this->Epin->save($this->data); } $this->Session->setFlash("Epin has been added"); $this->Redirect(array('action'=>'admin_manage_epin')); } } epin.php(model) <?php class Epin extends appModel{ var $name ="Epin"; var $validate = array( 'e_pin'=>array( 'rule'=>'notEmpty', 'message'=>'Please type No of epin' )); } ?> i think i have problem in my controller function admin_create_epin thanks A: You should probably check if the actual field is empty - since submitting a form will still have an array: if(!empty($this->data['Epin']['e_pin'])) { Within your for() loop, you should be using create() and don't set id: for($i=0;$i<$limit;$i++) { $this->Epin->create(); $random = substr(number_format(time() * rand(),0,'',''),0,11)."<br/>"; $this->data['Epin']['e_pin'] = $random; //... Your redirect should be lowercase: $this->redirect(... It's quite difficult to understand what you're actually asking, but if you're trying to redirect if the form was submitted empty, the redirect should be one more level out: } $this->Session->setFlash("Epin has been added"); $this->Redirect(array('action'=>'admin_manage_epin')); }
{ "language": "en", "url": "https://stackoverflow.com/questions/10396743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Choose a number from a a given pmf in theano Say I have an array p = [ 0.27, 0.23, 0.1, 0.15, 0.2 ,0.05]. Let p be a probability mass function for a Random Variable X. Now, I am writing a theano code, where I have a p generated at each iteration and I also have n weight matrices. (Here[n = 6].) Now, in each iteration I would want to select one of these weight matrices for further propagation. Could someone help out regarding how to write this piece of code. I am not sure I can write the exact code required to enable backpropagation(i.e. have the gradients corrected properly) Note that all the W_is as well as the enter p are model parameters. Edit W1,W2,W3,W4,W5,W6,x,eps = T.dmatrices("W1","W2","W3","W4","W5","W6","x","eps") b1,b2,b3,b4,b5,b6,pi = T.dcols("b1","b2","b3","b4","b5","b6","pi") h_encoder = T.tanh(T.dot(W1,x) + b1) rng = T.shared_randomstreams.RandomStreams(seed=124) i = rng.choice(size=(1,), a=self.num_model, p=T.nnet.softmax(pi)) mu_encoder = T.dot(W2[i[0]*self.dimZ:(1+i[0])*self.dimZ].nonzero(),h_encoder) + b2[i[0]*self.dimZ:(1+i[0])*self.dimZ].nonzero() log_sigma_encoder = (0.5*(T.dot(W3[i[0]*self.dimZ:(1+i[0])*self.dimZ].nonzero(),h_encoder)))+ b3[i[0]*self.dimZ:(1+i[0])*self.dimZ].nonzero() z = mu_encoder + T.exp(log_sigma_encoder)*eps` and my grad vaiables are gradvariables = [W1,W2,W3,W4,W5,b1,b2,b3,b4,b5,pi] Ignore the other variables as they are defined somewhere else. Now, I get the following error Traceback (most recent call last): File "trainmnist_mixture.py", line 55, in encoder.createGradientFunctions() File "/home/amartya/Variational-Autoencoder/Theano/VariationalAutoencoder_mixture.py", line 118, in createGradientFunctions derivatives = T.grad(logp,gradvariables) File "/usr/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/gradient.py", line 543, in grad grad_dict, wrt, cost_name) File "/usr/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/gradient.py", line 1273, in _populate_grad_dict rval = [access_grad_cache(elem) for elem in wrt] File "/usr/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/gradient.py", line 1233, in access_grad_cache term = access_term_cache(node)[idx] File "/usr/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/gradient.py", line 944, in access_term_cache output_grads = [access_grad_cache(var) for var in node.outputs] File "/usr/lib/python2.7/site-packages/Theano-0.6.0-py2.7.egg/theano/gradient.py", line 1243, in access_grad_cache term.type.why_null) theano.gradient.NullTypeGradError: tensor.grad encountered a NaN. This variable is Null because the grad method for input 0 (Subtensor{int64:int64:}.0) of the Nonzero op is mathematically undefined A: You can use the choice method of a RandomStreams instance. More on random numbers in Theano can be found in the documentation here and here. Here's an example: import numpy import theano import theano.tensor as tt import theano.tensor.shared_randomstreams n = 6 alpha = [1] * n seed = 1 w = theano.shared(numpy.random.randn(n, 2, 2).astype(theano.config.floatX)) p = theano.shared(numpy.random.dirichlet(alpha).astype(theano.config.floatX)) rng = tt.shared_randomstreams.RandomStreams(seed=seed) i = rng.choice(size=(1,), a=n, p=p) f = theano.function([], [p, i, w[i]]) print f() print f() print f() print f()
{ "language": "en", "url": "https://stackoverflow.com/questions/34154219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSRS-what is the syntax for the Target Server URL in SSRS2008R2 can anyone help me out with the syntax and example for the target server URL in SSRS 2008R2 inorder to deploy my reports?? A: are you deploying to sharepoint or a standalone (native-mode) report server? http://msdn.microsoft.com/en-us/library/ms155802(v=sql.105).aspx 10.In the TargetServerURL text box, type the URL of the target report server. Before you publish a report, you must set this property to a valid report server URL. When publishing to a report server running in native mode, use the URL of the virtual directory of the report server (for example, http://server/reportserver or https://server/reportserver). This is the virtual directory of the report server, not Report Manager. When publishing to a report server running in SharePoint integrated mode, use a URL to a SharePoint top-level site or subsite. If you do not specify a site, the default top-level site is used (for example, http://servername, http://servername/site or http://servername/site/subsite).
{ "language": "en", "url": "https://stackoverflow.com/questions/9926074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mailbox unavailable. The server response was: 5.7.1 Invalid credentials for relay At our office others can use the .NET SMTP client to send email via our Google Apps account. Using the exact same settings and credentials this does not work on a particular machine. It seems to be just this one machine with this issue. I get: Mailbox unavailable. The server response was: 5.7.1 Invalid credentials for relay We are all on the same external IP, so it's not A: Aha! We found the smoking gun. Here is what the message actually says: SmtpException: Mailbox unavailable. The server response was: 5.7.1 Invalid credentials for relay [ffff:fff:ffff:ffff:ffff:ffff:ffff:ffff] I've obfuscated the last part, but note that the IP address this appears to come from is an IPV6 address. Out relay whitelist only includes IPV4 addresses. So I turned IPV6 off on that machine - because honestly, what is that good for anyway?
{ "language": "en", "url": "https://stackoverflow.com/questions/40314298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to draw a Polygon on MapView, fill it, and put a onTouch Event on it Is it possible to set an EventListener in a drawn Polygon in a osmdroid MapView Overlay ? I would like to print on a Overlay and after touching it I would like to change its color or handle data behind a Polygon. For Example: Poly1: ID = 1337, P1(0,0),P2(1,0),......,Pn(0,0) Poly2: ID = 42 , P1(10,7),P2(18,39),......,Pn(10,7) After touching in Poly1 I want to know aha ID 1337 is pressed. An want to change its color. How could I implement such a behavior ? A: Use this documentation to draw the polygons Use this to listen for map clicks Use this to determine if a touch is inside one of the polygons I'm not sure that geometry library can run on android, so feel free to replace the third component. EDIT: Misread the question and associated it with google maps, sorry. A: Here is how to draw and fill a polygon (rectangle example): ArrayList bgRectPoints = new ArrayList<>(); GeoPoint pt1 = new GeoPoint(-15.953548, 126.036911); bgRectPoints.add(pt1); GeoPoint pt2 = pt1.destinationPoint(10000, 0); bgRectPoints.add(pt2); GeoPoint pt3 = pt2.destinationPoint(10000, 90); bgRectPoints.add(pt3); GeoPoint pt4 = pt3.destinationPoint(10000, 180); bgRectPoints.add(pt4); bgRectPoints.add(pt1); Polygon polygon = new Polygon(); polygon.setPoints(bgRectPoints); polygon.setFillColor(Color.BLACK); mapView.getOverlays().add(polygon); To receive touch/Tap initialize polygon like this: Polygon polygon = new Polygon(){ @Override public boolean onSingleTapConfirmed(MotionEvent event, MapView mapView) { Toast.makeText(context, "Polygon clicked!",Toast.LENGTH_SHORT).show(); return super.onSingleTapConfirmed(event, mapView); } }; More can be found here
{ "language": "en", "url": "https://stackoverflow.com/questions/14376869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why does my div dont go fullscreen? why does my button expand down in height and not equally to the top and bottom so it would cover the fullscreen? And the Border lines should stop at the size of the parent div... I cant make it work.. do you have any ideas? (to make the doggies disappear :DD) var main = function(){ $('#Music').click(function(){ $('#soundcloud').animate({ bottom:'0px' },200); $('body').animate({ bottom:'285px' }, 200); }); $('#Home').click(function(){ $('#title').css("-webkit-text-fill-color", "transparent") $('.dick').css("background-image", "url(RegenBack.jpg)") $('#soundcloud').animate({ bottom:'-285px' },200); $('body').animate({ bottom:'0px' },200); }); $('#button').mouseup(function () { var d = {}; $('#button').removeClass('shadow') $('#button').find('p').removeClass('textshadow') $('#button').find('p').css("visibility", "hidden") $('#button').css("z-index", "999") $('#button').removeClass('shadow') $('#button').animate({ width: '100%' },500,function() { $('#button').animate({ height: '100%' }, 500); }); }); $('#button').mousedown(function() { $('#button').find('p').addClass('textshadow') $('#button').addClass('shadow') }); }; $(document).ready(main); .menu{ overflow: hidden; margin-top: 50px; } #button p{ margin-left: auto; margin-right: auto; margin-top: -15px; font-size: 100px; font-family: mySecondFont; -webkit-user-select: none; /* Chrome/Safari */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* IE10+ */ } #button{ background: url(https://pbs.twimg.com/profile_images/378800000532546226/dbe5f0727b69487016ffd67a6689e75a.jpeg) fixed; width: 622px; height: 148px; margin-left: auto; margin-right: auto; margin-top: 200px; margin-bottom: auto; cursor: pointer; border-style: solid; border-width: 10px 10px 10px 10px; border-color: white black black white; border-radius: 10px; -webkit-box-shadow: inset -3px -3px 0px 0px rgba(255,255,255,1); } .textshadow{ background-color: #000000; color: transparent; text-shadow: 0px 2px 3px rgba(255,255,255,0.5); -webkit-background-clip: text; -moz-background-clip: text; background-clip: text; } .shadow { -webkit-box-shadow: inset 9px 9px 15px 0px rgba(0,0,0,0.75).inset -2px -2px 15px 0px rgba(255,255,255,1) !important; -moz-box-shadow: inset 9px 9px 15px 0px rgba(0,0,0,0.75), inset -2px -2px 15px 0px rgba(255,255,255,1) !important; box-shadow: inset 9px 9px 15px 0px rgba(0,0,0,0.75), inset -2px -2px 15px 0px rgba(255,255,255,1) !important; } #soundcloud{ bottom: -200px; /* start off behind the scenes */ height: 200px; position: fixed; width: 100%; background-color: #ffffff; } div div div div p{ border: 5px solid white; text-align: center; color: #ffffff; font-size: 70px; font-family: myFirstFont; text-decoration: none; } div div div div p:hover{ cursor: pointer; border-color: grey; text-decoration: none; color: grey; } #Music { margin-left: auto; margin-right: auto; width: 70%; } #Home { margin-left: auto; margin-right: auto; width: 70%; } #About { margin-left: auto; margin-right: auto; width: 70%; } #Media { margin-left: auto; margin-right: auto; width: 70%; } .dick { position: absolute; height: 100%; width: 100%; background-image: url(http://www.prevention.com/sites/default/files/imagecache/slideshow_display/dog-dogue-de-bordeaux-puppy-410x290.jpg); } #title { -webkit-user-select: none; /* Chrome/Safari */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* IE10+ */ cursor: default; overflow: hidden; float: inherit; background: url(Textur1.jpg) no-repeat fixed; -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-family: mySecondFont; font-size: 200px; margin-top: 50px; } div p{ text-align: center; font-size: 70px; color: #ffffff; } @font-face { font-family: myFirstFont; src: url(/Fonts/Bask/BaskOldFace.woff); } @font-face { font-family: mySecondFont; src: url(Fonts/Script/ScriptMTBold.woff); } body, hmtl{ height: 100%; width: 100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <!DOCTYPE html> <html> <head lang="de"> <meta charset="UTF-8"> <title>Bolle | Music</title> <link href="bootstrap-3.3.2-dist/css/bootstrap.css" rel="stylesheet"> <link href="Bolle%20Music.css" rel="stylesheet"> </head> <body> <div class="dick"> <div id="button"> <p>Get Happy</p> </div> </div> <div id="soundcloud"></div> <script src="jquery-1.11.2.min.js"></script> <script src="Ani.js"></script> </body> </html> Im thankful for any tips :) Greetings Bolle A: You have a margin-top property set to 200px on the button. That property stays after the button expands.
{ "language": "en", "url": "https://stackoverflow.com/questions/28462102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: combined coffee and js development with Gulp Using Gulp to streamline my build process on a per-save basis, while eliminating the need for "temp" files is my goal (and why I chose to use Gulp over Grunt) I've recently discovered that, apparently, the coffeescript compiler cannot handle dealing with basic Javascript as a source So this, errors out: gulp.task('scripts', function() { var stream = gulp.src([ "bower_components/d3/d3.js", "bower_components/angular/angular.js", "bower_components/foundation/js/foundation.js", "public-dev/scripts/app.js", "public-dev/scripts/**/*.js", "public-dev/scripts/**/*.coffee" ]) .pipe(coffee()) .pipe(concat('compiled.js')) .pipe(gulp.dest('./public/scripts')) ; return stream; }); This produces the output/errpr: [11:58:51] Starting 'scripts'... events.js:72 throw er; // Unhandled 'error' event ^ /var/www/node.fortiguard.dev/bower_components/d3/d3.js:1:2: error: reserved word "function" !function() { ^ How should I set this up, without again creating any temp files? What I liked about the LESS compiler, is that it can still be fed straight CSS files and it'd be fine. I was kind of hoping the Coffee compiler would react the same way A: I use gulp-add-src to do that. var gulp = require('gulp'), coffee = require('gulp-coffee'), concat = require('gulp-concat'), addsrc = require('gulp-add-src'); // Scripts gulp.task('coffee', function () { return gulp.src('src/coffee/**/*.coffee') .pipe(coffee()) .pipe(addsrc('src/coffee/lib/*.js')) .pipe(concat('compiled.js')) .pipe(gulp.dest('dist')); }); A: Sadly, it doesn't. What you can do, is using the underlying event-stream's merge method. Then you'll have one pipeline for the coffee files that gets compiled and one for the javascript side. Here is an example Gulpfile.coffee: coffee = require 'gulp-coffee' es = require 'event-stream' gulp.task 'scripts', () -> es.merge( gulp.src(["public-dev/app.js", "public-dev/scripts/**/*.js"]) # ... gulp.src("public-dev/**/*.coffee").pipe coffee() ) .pipe concat 'all.js' .pipe gulp.dest "build" A: I marked Patrick J. S.'s answer as "Correct" becuase in reality, this is exactly what I needed to do. That said, "event-stream" isn't what I ended up going with, simply because I needed to preserve my dependency structure of files, and event-stream's merge() method does not preserver order nor does it have options to. Instead I opted for a package called streamqueue, which does preserve order of glob. Probably slower, but order matters in my app unfortunately. In the future I will try to be as modular as possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/28486903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: oracle apex tabular form validation How to add validation to a newly created row in tabular form ?. in normal method when I add validation to a tabular form column it applies to the existing records but not for newly created rows which are added after page load.
{ "language": "en", "url": "https://stackoverflow.com/questions/46461759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - How Can I make this array work? So I've got an array, which gets random images and display them with certain text. Unfortunately, the text won't appear and the if it does, the hyperlink doesn't appear UNDER the image. Please someone help!! <?php define('RANDOM_IMAGES_COUNT', 3); define('RANDOM_IMAGES_FORMAT', '<img src="%s"><a href="%s"> alt="%s" title="%3$s" style="margin-right:10px"></a>'); #------------------------------------------------------------------------------ $images = array ( array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => '<a href=http://mylink.com/path/>Click Me</a>' ), array ( 'title' => 'Test 3', 'src' => 'pic3.jpg', 'href' => '<a href=http://mylink.com/path/>Click Me</a>' ), array ( 'title' => 'Test 4', 'src' => 'pic4.jpg', 'href' => '<a href=http://mylink.com/path/>Click Me</a>' ) ); #------------------------------------------------------------------------------ if ( count($images) < RANDOM_IMAGES_COUNT ) { trigger_error('Not enough images given', E_USER_WARNING); exit; } #------------------------------------------------------------------------------ for ($i = 0; $i < RANDOM_IMAGES_COUNT; $i++) { shuffle($images); $tmp = array_shift($images); printf( RANDOM_IMAGES_FORMAT, $tmp['src'],$tmp['href'], $tmp['title'] ); } ?> A: For the positioning of your link under the image, you'd have to work on your CSS. For proper working of the code sample, make following changes: * *Update RANDOM_IMAGES_FORMAT to define('RANDOM_IMAGES_FORMAT', '<img src="%s" /><a href="%s" alt="%s" title="%s" style="margin-right:10px">Click Me</a>'); *Change the array to: $images = array ( array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 3', 'src' => 'pic3.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 4', 'src' => 'pic4.jpg', 'href' => 'http://mylink.com/path/' ) ); *Use printf like this: printf( RANDOM_IMAGES_FORMAT, $tmp['src'], $tmp['href'], $tmp['title'], $tmp['title'] ); A: Your code have multiple issues: Constant RANDOM_IMAGES_FORMAT is poorly formatted as HTML it should look like: define('RANDOM_IMAGES_FORMAT', '<img src="%s" alt="%s" title="%3$s" style="margin-right:10px"><a href="%s"></a>'); As for that, the order of printf arguments should be reordered, because we have modified displaying them in RANDOM_IMAGES_FORMAT: printf( RANDOM_IMAGES_FORMAT, $tmp['src'],$tmp['href'], $tmp['title'] ); In your $images array, links should be only URL, not full links, as you defined then already in RANDOM_IMAGES_FORMAT. Full code you presented should look like this: define('RANDOM_IMAGES_COUNT', 3); define('RANDOM_IMAGES_FORMAT', '<img src="%s" alt="%s" title="%3$s" style="margin-right:10px"><a href="%s"></a>'); $images = array ( array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 3', 'src' => 'pic3.jpg', 'href' => 'http://mylink.com/path/' ), array ( 'title' => 'Test 4', 'src' => 'pic4.jpg', 'href' => 'http://mylink.com/path/' ) ); if ( count($images) < RANDOM_IMAGES_COUNT ) { trigger_error('Not enough images given', E_USER_WARNING); exit; } for ($i = 0; $i < RANDOM_IMAGES_COUNT; $i++) { shuffle($images); $tmp = array_shift($images); printf( RANDOM_IMAGES_FORMAT, $tmp['src'],$tmp['href'], $tmp['title'] ); } A: <img src="%s"><a href="%s"> alt="%s" title="%3$s" style="margin-right:10px"></a> do not close the tag a after href="%s" and put img inside of a tag, like this: <a><img/></a> A: Check define('RANDOM_IMAGES_FORMAT', '<img src="%s"><a href="%s"> alt="%s" title="%3$s" style="margin-right:10px"></a>'); and array ( 'title' => 'Test 2', 'src' => 'pic2.jpg', 'href' => '<a href=http://mylink.com/path/>Click Me</a>' ), their is a problem with href try to give only link in href
{ "language": "en", "url": "https://stackoverflow.com/questions/18588349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Angular 14 mat date picker won't work and display properly I have trouble with material date picker. I've imported this modules: MatFormFieldModule, MatInputModule, MatDatepickerModule, MatNativeDateModule but no luck. Only code that i have is in html template: <div> <mat-form-field appearance="fill"> <mat-label>Choose a date</mat-label> <input matInput > <mat-hint>MM/DD/YYYY</mat-hint> <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> </div> Any suggestion is welcome. Thank you! My ng version: Angular CLI: 14.2.8 Node: 18.12.1 (Unsupported) Package Manager: npm 8.19.2 OS: darwin x64 Angular: 14.2.9 ... animations, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package Version --------------------------------------------------------- @angular-devkit/architect 0.1402.8 @angular-devkit/build-angular 14.2.8 @angular-devkit/core 14.2.8 @angular-devkit/schematics 14.2.8 @angular/cli 14.2.8 @angular/material 7.0.0 @schematics/angular 14.2.8 rxjs 7.5.7 typescript 4.7.4
{ "language": "en", "url": "https://stackoverflow.com/questions/75448920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: What is the most efficient/elegant way to parse a flat table into a tree? Assume you have a flat table that stores an ordered tree hierarchy: Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 20 4 'Node 1.1.1' 2 10 5 'Node 2.1' 3 10 6 'Node 1.2' 1 20 Here's a diagram, where we have [id] Name. Root node 0 is fictional. [0] ROOT / \ [1] Node 1 [3] Node 2 / \ \ [2] Node 1.1 [6] Node 1.2 [5] Node 2.1 / [4] Node 1.1.1 What minimalistic approach would you use to output that to HTML (or text, for that matter) as a correctly ordered, correctly indented tree? Assume further you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly. Pseudo code or plain English is okay, this is purely a conceptional question. Bonus question: Is there a fundamentally better way to store a tree structure like this in a RDBMS? EDITS AND ADDITIONS To answer one commenter's (Mark Bessey's) question: A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted. The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay. The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though. Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable. I have posted my own solution so you guys can pull it to pieces. A: There are really good solutions which exploit the internal btree representation of sql indices. This is based on some great research done back around 1998. Here is an example table (in mysql). CREATE TABLE `node` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `tw` int(10) unsigned NOT NULL, `pa` int(10) unsigned DEFAULT NULL, `sz` int(10) unsigned DEFAULT NULL, `nc` int(11) GENERATED ALWAYS AS (tw+sz) STORED, PRIMARY KEY (`id`), KEY `node_tw_index` (`tw`), KEY `node_pa_index` (`pa`), KEY `node_nc_index` (`nc`), CONSTRAINT `node_pa_fk` FOREIGN KEY (`pa`) REFERENCES `node` (`tw`) ON DELETE CASCADE ) The only fields necessary for the tree representation are: * *tw: The Left to Right DFS Pre-order index, where root = 1. *pa: The reference (using tw) to the parent node, root has null. *sz: The size of the node's branch including itself. *nc: is used as syntactic sugar. it is tw+sz and represents the tw of the node's "next child". Here is an example 24 node population, ordered by tw: +-----+---------+----+------+------+------+ | id | name | tw | pa | sz | nc | +-----+---------+----+------+------+------+ | 1 | Root | 1 | NULL | 24 | 25 | | 2 | A | 2 | 1 | 14 | 16 | | 3 | AA | 3 | 2 | 1 | 4 | | 4 | AB | 4 | 2 | 7 | 11 | | 5 | ABA | 5 | 4 | 1 | 6 | | 6 | ABB | 6 | 4 | 3 | 9 | | 7 | ABBA | 7 | 6 | 1 | 8 | | 8 | ABBB | 8 | 6 | 1 | 9 | | 9 | ABC | 9 | 4 | 2 | 11 | | 10 | ABCD | 10 | 9 | 1 | 11 | | 11 | AC | 11 | 2 | 4 | 15 | | 12 | ACA | 12 | 11 | 2 | 14 | | 13 | ACAA | 13 | 12 | 1 | 14 | | 14 | ACB | 14 | 11 | 1 | 15 | | 15 | AD | 15 | 2 | 1 | 16 | | 16 | B | 16 | 1 | 1 | 17 | | 17 | C | 17 | 1 | 6 | 23 | | 359 | C0 | 18 | 17 | 5 | 23 | | 360 | C1 | 19 | 18 | 4 | 23 | | 361 | C2(res) | 20 | 19 | 3 | 23 | | 362 | C3 | 21 | 20 | 2 | 23 | | 363 | C4 | 22 | 21 | 1 | 23 | | 18 | D | 23 | 1 | 1 | 24 | | 19 | E | 24 | 1 | 1 | 25 | +-----+---------+----+------+------+------+ Every tree result can be done non-recursively. For instance, to get a list of ancestors of node at tw='22' Ancestors select anc.* from node me,node anc where me.tw=22 and anc.nc >= me.tw and anc.tw <= me.tw order by anc.tw; +-----+---------+----+------+------+------+ | id | name | tw | pa | sz | nc | +-----+---------+----+------+------+------+ | 1 | Root | 1 | NULL | 24 | 25 | | 17 | C | 17 | 1 | 6 | 23 | | 359 | C0 | 18 | 17 | 5 | 23 | | 360 | C1 | 19 | 18 | 4 | 23 | | 361 | C2(res) | 20 | 19 | 3 | 23 | | 362 | C3 | 21 | 20 | 2 | 23 | | 363 | C4 | 22 | 21 | 1 | 23 | +-----+---------+----+------+------+------+ Siblings and children are trivial - just use pa field ordering by tw. Descendants For example the set (branch) of nodes that are rooted at tw = 17. select des.* from node me,node des where me.tw=17 and des.tw < me.nc and des.tw >= me.tw order by des.tw; +-----+---------+----+------+------+------+ | id | name | tw | pa | sz | nc | +-----+---------+----+------+------+------+ | 17 | C | 17 | 1 | 6 | 23 | | 359 | C0 | 18 | 17 | 5 | 23 | | 360 | C1 | 19 | 18 | 4 | 23 | | 361 | C2(res) | 20 | 19 | 3 | 23 | | 362 | C3 | 21 | 20 | 2 | 23 | | 363 | C4 | 22 | 21 | 1 | 23 | +-----+---------+----+------+------+------+ Additional Notes This methodology is extremely useful for when there are a far greater number of reads than there are inserts or updates. Because the insertion, movement, or updating of a node in the tree requires the tree to be adjusted, it is necessary to lock the table before commencing with the action. The insertion/deletion cost is high because the tw index and sz (branch size) values will need to be updated on all the nodes after the insertion point, and for all ancestors respectively. Branch moving involves moving the tw value of the branch out of range, so it is also necessary to disable foreign key constraints when moving a branch. There are, essentially four queries required to move a branch: * *Move the branch out of range. *Close the gap that it left. (the remaining tree is now normalised). *Open the gap where it will go to. *Move the branch into it's new position. Adjust Tree Queries The opening/closing of gaps in the tree is an important sub-function used by create/update/delete methods, so I include it here. We need two parameters - a flag representing whether or not we are downsizing or upsizing, and the node's tw index. So, for example tw=18 (which has a branch size of 5). Let's assume that we are downsizing (removing tw) - this means that we are using '-' instead of '+' in the updates of the following example. We first use a (slightly altered) ancestor function to update the sz value. update node me, node anc set anc.sz = anc.sz - me.sz from node me, node anc where me.tw=18 and ((anc.nc >= me.tw and anc.tw < me.pa) or (anc.tw=me.pa)); Then we need to adjust the tw for those whose tw is higher than the branch to be removed. update node me, node anc set anc.tw = anc.tw - me.sz from node me, node anc where me.tw=18 and anc.tw >= me.tw; Then we need to adjust the parent for those whose pa's tw is higher than the branch to be removed. update node me, node anc set anc.pa = anc.pa - me.sz from node me, node anc where me.tw=18 and anc.pa >= me.tw; A: Well given the choice, I'd be using objects. I'd create an object for each record where each object has a children collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. Simple. But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on: function PrintLine(int pID, int level) foreach record where ParentID == pID print level*tabs + record-data PrintLine(record.ID, level + 1) PrintLine(0, 0) Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's nasty. If you have the choice, go the OOP route. A: If you use nested sets (sometimes referred to as Modified Pre-order Tree Traversal) you can extract the entire tree structure or any subtree within it in tree order with a single query, at the cost of inserts being more expensive, as you need to manage columns which describe an in-order path through thee tree structure. For django-mptt, I used a structure like this: id parent_id tree_id level lft rght -- --------- ------- ----- --- ---- 1 null 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12 Which describes a tree which looks like this (with id representing each item): 1 +-- 2 | +-- 3 | +-- 4 | +-- 5 +-- 6 +-- 7 Or, as a nested set diagram which makes it more obvious how the lft and rght values work: __________________________________________________________________________ | Root 1 | | ________________________________ ________________________________ | | | Child 1.1 | | Child 1.2 | | | | ___________ ___________ | | ___________ ___________ | | | | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | | 1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14 | |________________________________| |________________________________| | |__________________________________________________________________________| As you can see, to get the entire subtree for a given node, in tree order, you simply have to select all rows which have lft and rght values between its lft and rght values. It's also simple to retrieve the tree of ancestors for a given node. The level column is a bit of denormalisation for convenience more than anything and the tree_id column allows you to restart the lft and rght numbering for each top-level node, which reduces the number of columns affected by inserts, moves and deletions, as the lft and rght columns have to be adjusted accordingly when these operations take place in order to create or close gaps. I made some development notes at the time when I was trying to wrap my head around the queries required for each operation. In terms of actually working with this data to display a tree, I created a tree_item_iterator utility function which, for each node, should give you sufficient information to generate whatever kind of display you want. More info about MPTT: * *Trees in SQL *Storing Hierarchical Data in a Database *Managing Hierarchical Data in MySQL A: Now that MySQL 8.0 supports recursive queries, we can say that all popular SQL databases support recursive queries in standard syntax. WITH RECURSIVE MyTree AS ( SELECT * FROM MyTable WHERE ParentId IS NULL UNION ALL SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id ) SELECT * FROM MyTree; I tested recursive queries in MySQL 8.0 in my presentation Recursive Query Throwdown in 2017. Below is my original answer from 2008: There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods: * *Adjacency List (the "parent" column) and *Path Enumeration (the dotted-numbers in your name column). Another solution is called Nested Sets, and it can be stored in the same table too. Read "Trees and Hierarchies in SQL for Smarties" by Joe Celko for a lot more information on these designs. I usually prefer a design called Closure Table (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy. I cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP and in my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming. CREATE TABLE ClosureTable ( ancestor_id INT NOT NULL REFERENCES FlatTable(id), descendant_id INT NOT NULL REFERENCES FlatTable(id), PRIMARY KEY (ancestor_id, descendant_id) ); Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question: INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES (1,1), (1,2), (1,4), (1,6), (2,2), (2,4), (3,3), (3,5), (4,4), (5,5), (6,6); Now you can get a tree starting at node 1 like this: SELECT f.* FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) WHERE a.ancestor_id = 1; The output (in MySQL client) looks like the following: +----+ | id | +----+ | 1 | | 2 | | 4 | | 6 | +----+ In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1. Re: comment from e-satis about immediate children (or immediate parent). You can add a "path_length" column to the ClosureTable to make it easier to query specifically for an immediate child or parent (or any other distance). INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES (1,1,0), (1,2,1), (1,4,2), (1,6,1), (2,2,0), (2,4,1), (3,3,0), (3,5,1), (4,4,0), (5,5,0), (6,6,0); Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose path_length is 1. SELECT f.* FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) WHERE a.ancestor_id = 1 AND path_length = 1; +----+ | id | +----+ | 2 | | 6 | +----+ Re comment from @ashraf: "How about sorting the whole tree [by name]?" Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as name, and sort by the name. SELECT f.name FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) WHERE a.ancestor_id = 1 ORDER BY f.name; Re comment from @Nate: SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) JOIN ClosureTable b ON (b.descendant_id = a.descendant_id) WHERE a.ancestor_id = 1 GROUP BY a.descendant_id ORDER BY f.name +------------+-------------+ | name | breadcrumbs | +------------+-------------+ | Node 1 | 1 | | Node 1.1 | 1,2 | | Node 1.1.1 | 1,2,4 | | Node 1.2 | 1,6 | +------------+-------------+ A user suggested an edit today. SO moderators approved the edit, but I am reversing it. The edit suggested that the ORDER BY in the last query above should be ORDER BY b.path_length, f.name, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2". If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to MySQL Closure Table hierarchical database - How to pull information out in the correct order. A: This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int and Integer is annoying!), but it works. It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :) This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows. public class Node { private Node parent = null; private List<Node> children; private String name; private int id = -1; public Node(Node parent, int id, String name) { this.parent = parent; this.children = new ArrayList<Node>(); this.name = name; this.id = id; } public int getId() { return this.id; } public String getName() { return this.name; } public void addChild(Node child) { children.add(child); } public List<Node> getChildren() { return children; } public boolean isRoot() { return (this.parent == null); } @Override public String toString() { return "id=" + id + ", name=" + name + ", parent=" + parent; } } public class NodeBuilder { public static Node build(List<Map<String, String>> input) { // maps id of a node to it's Node object Map<Integer, Node> nodeMap = new HashMap<Integer, Node>(); // maps id of a node to the id of it's parent Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>(); // create special 'root' Node with id=0 Node root = new Node(null, 0, "root"); nodeMap.put(root.getId(), root); // iterate thru the input for (Map<String, String> map : input) { // expect each Map to have keys for "id", "name", "parent" ... a // real implementation would read from a SQL object or resultset int id = Integer.parseInt(map.get("id")); String name = map.get("name"); int parent = Integer.parseInt(map.get("parent")); Node node = new Node(null, id, name); nodeMap.put(id, node); childParentMap.put(id, parent); } // now that each Node is created, setup the child-parent relationships for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) { int nodeId = entry.getKey(); int parentId = entry.getValue(); Node child = nodeMap.get(nodeId); Node parent = nodeMap.get(parentId); parent.addChild(child); } return root; } } public class NodePrinter { static void printRootNode(Node root) { printNodes(root, 0); } static void printNodes(Node node, int indentLevel) { printNode(node, indentLevel); // recurse for (Node child : node.getChildren()) { printNodes(child, indentLevel + 1); } } static void printNode(Node node, int indentLevel) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < indentLevel; i++) { sb.append("\t"); } sb.append(node); System.out.println(sb.toString()); } public static void main(String[] args) { // setup dummy data List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>(); resultSet.add(newMap("1", "Node 1", "0")); resultSet.add(newMap("2", "Node 1.1", "1")); resultSet.add(newMap("3", "Node 2", "0")); resultSet.add(newMap("4", "Node 1.1.1", "2")); resultSet.add(newMap("5", "Node 2.1", "3")); resultSet.add(newMap("6", "Node 1.2", "1")); Node root = NodeBuilder.build(resultSet); printRootNode(root); } //convenience method for creating our dummy data private static Map<String, String> newMap(String id, String name, String parentId) { Map<String, String> row = new HashMap<String, String>(); row.put("id", id); row.put("name", name); row.put("parent", parentId); return row; } } A: Assuming that you know that the root elements are zero, here's the pseudocode to output to text: function PrintLevel (int curr, int level) //print the indents for (i=1; i<=level; i++) print a tab print curr \n; for each child in the table with a parent of curr PrintLevel (child, level+1) for each elementID where the parentid is zero PrintLevel(elementID, 0) A: It's a quite old question, but as it's got many views I think it's worth to present an alternative, and in my opinion very elegant, solution. In order to read a tree structure you can use recursive Common Table Expressions (CTEs). It gives a possibility to fetch whole tree structure at once, have the information about the level of the node, its parent node and order within children of the parent node. Let me show you how this would work in PostgreSQL 9.1. * *Create a structure CREATE TABLE tree ( id int NOT NULL, name varchar(32) NOT NULL, parent_id int NULL, node_order int NOT NULL, CONSTRAINT tree_pk PRIMARY KEY (id), CONSTRAINT tree_tree_fk FOREIGN KEY (parent_id) REFERENCES tree (id) NOT DEFERRABLE ); insert into tree values (0, 'ROOT', NULL, 0), (1, 'Node 1', 0, 10), (2, 'Node 1.1', 1, 10), (3, 'Node 2', 0, 20), (4, 'Node 1.1.1', 2, 10), (5, 'Node 2.1', 3, 10), (6, 'Node 1.2', 1, 20); *Write a query WITH RECURSIVE tree_search (id, name, level, parent_id, node_order) AS ( SELECT id, name, 0, parent_id, 1 FROM tree WHERE parent_id is NULL UNION ALL SELECT t.id, t.name, ts.level + 1, ts.id, t.node_order FROM tree t, tree_search ts WHERE t.parent_id = ts.id ) SELECT * FROM tree_search WHERE level > 0 ORDER BY level, parent_id, node_order; Here are the results: id | name | level | parent_id | node_order ----+------------+-------+-----------+------------ 1 | Node 1 | 1 | 0 | 10 3 | Node 2 | 1 | 0 | 20 2 | Node 1.1 | 2 | 1 | 10 6 | Node 1.2 | 2 | 1 | 20 5 | Node 2.1 | 2 | 3 | 10 4 | Node 1.1.1 | 3 | 2 | 10 (6 rows) The tree nodes are ordered by a level of depth. In the final output we would present them in the subsequent lines. For each level, they are ordered by parent_id and node_order within the parent. This tells us how to present them in the output - link node to the parent in this order. Having such a structure it wouldn't be difficult to make a really nice presentation in HTML. Recursive CTEs are available in PostgreSQL, IBM DB2, MS SQL Server, Oracle and SQLite. If you'd like to read more on recursive SQL queries, you can either check the documentation of your favourite DBMS or read my two articles covering this topic: * *Do It In SQL: Recursive Tree Traversal *Get to know the power of SQL recursive queries A: You can emulate any other data structure with a hashmap, so that's not a terrible limitation. Scanning from the top to the bottom, you create a hashmap for each row of the database, with an entry for each column. Add each of these hashmaps to a "master" hashmap, keyed on the id. If any node has a "parent" that you haven't seen yet, create an placeholder entry for it in the master hashmap, and fill it in when you see the actual node. To print it out, do a simple depth-first pass through the data, keeping track of indent level along the way. You can make this easier by keeping a "children" entry for each row, and populating it as you scan the data. As for whether there's a "better" way to store a tree in a database, that depends on how you're going to use the data. I've seen systems that had a known maximum depth that used a different table for each level in the hierarchy. That makes a lot of sense if the levels in the tree aren't quite equivalent after all (top level categories being different than the leaves). A: As of Oracle 9i, you can use CONNECT BY. SELECT LPAD(' ', (LEVEL - 1) * 4) || "Name" AS "Name" FROM (SELECT * FROM TMP_NODE ORDER BY "Order") CONNECT BY PRIOR "Id" = "ParentId" START WITH "Id" IN (SELECT "Id" FROM TMP_NODE WHERE "ParentId" = 0) As of SQL Server 2005, you can use a recursive common table expression (CTE). WITH [NodeList] ( [Id] , [ParentId] , [Level] , [Order] ) AS ( SELECT [Node].[Id] , [Node].[ParentId] , 0 AS [Level] , CONVERT([varchar](MAX), [Node].[Order]) AS [Order] FROM [Node] WHERE [Node].[ParentId] = 0 UNION ALL SELECT [Node].[Id] , [Node].[ParentId] , [NodeList].[Level] + 1 AS [Level] , [NodeList].[Order] + '|' + CONVERT([varchar](MAX), [Node].[Order]) AS [Order] FROM [Node] INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[ParentId] ) SELECT REPLICATE(' ', [NodeList].[Level] * 4) + [Node].[Name] AS [Name] FROM [Node] INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[Id] ORDER BY [NodeList].[Order] Both will output the following results. Name 'Node 1' ' Node 1.1' ' Node 1.1.1' ' Node 1.2' 'Node 2' ' Node 2.1' A: Bill's answer is pretty gosh-darned good, this answer adds some things to it which makes me wish SO supported threaded answers. Anyway I wanted to support the tree structure and the Order property. I included a single property in each Node called leftSibling that does the same thing Order is meant to do in the original question (maintain left-to-right order). mysql> desc nodes ; +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | | leftSibling | int(11) | NO | | 0 | | +-------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) mysql> desc adjacencies; +------------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+---------+------+-----+---------+----------------+ | relationId | int(11) | NO | PRI | NULL | auto_increment | | parent | int(11) | NO | | NULL | | | child | int(11) | NO | | NULL | | | pathLen | int(11) | NO | | NULL | | +------------+---------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) More detail and SQL code on my blog. Thanks Bill your answer was helpful in getting started! A: If nested hash maps or arrays can be created, then I can simply go down the table from the beginning and add each item to the nested array. I must trace each line to the root node in order to know which level in the nested array to insert into. I can employ memoization so that I do not need to look up the same parent over and over again. Edit: I would read the entire table into an array first, so it will not query the DB repeatedly. Of course this won't be practical if your table is very large. After the structure is built, I must do a depth first traverse through it and print out the HTML. There's no better fundamental way to store this information using one table (I could be wrong though ;), and would love to see a better solution ). However, if you create a scheme to employ dynamically created db tables, then you opened up a whole new world at the sacrifice of simplicity, and the risk of SQL hell ;). A: To Extend Bill's SQL solution you can basically do the same using a flat array. Further more if your strings all have the same lenght and your maximum number of children are known (say in a binary tree) you can do it using a single string (character array). If you have arbitrary number of children this complicates things a bit... I would have to check my old notes to see what can be done. Then, sacrificing a bit of memory, especially if your tree is sparse and/or unballanced, you can, with a bit of index math, access all the strings randomly by storing your tree, width first in the array like so (for a binary tree): String[] nodeArray = [L0root, L1child1, L1child2, L2Child1, L2Child2, L2Child3, L2Child4] ... yo know your string length, you know it I'm at work now so cannot spend much time on it but with interest I can fetch a bit of code to do this. We use to do it to search in binary trees made of DNA codons, a process built the tree, then we flattened it to search text patterns and when found, though index math (revers from above) we get the node back... very fast and efficient, tough our tree rarely had empty nodes, but we could searh gigabytes of data in a jiffy. A: Pre-order transversal with on-the-fly path enumeration on adjacency representation Nested sets from: * *Konchog https://stackoverflow.com/a/42781302/895245 *Jonny Buchanan https://stackoverflow.com/a/194031/895245 is the only efficient way I've seen of traversing, at the cost of slower updates. That's likely what most people will want for pre-order. Closure table from https://stackoverflow.com/a/192462/895245 is interesting, but I don't see how to enforce pre-order there: MySQL Closure Table hierarchical database - How to pull information out in the correct order Mostly for fun, here's a method that recursively calculates the 1.3.2.5. prefixes on the fly and sorts by them at the end, based only on the parent ID/child index representation. Upsides: * *updates only need to update the indexes of each sibling Downsides: * *n^2 memory usage worst case for a super deep tree. This could be quite serious, which is why I say this method is likely mostly for fun only. But maybe there is some ultra high update case where someone would want to use it? Who knows *recursive queries, so reads are going to be less efficient than nested sets Create and populate table: CREATE TABLE "ParentIndexTree" ( "id" INTEGER PRIMARY KEY, "parentId" INTEGER, "childIndex" INTEGER NOT NULL, "value" INTEGER NOT NULL, "name" TEXT NOT NULL, FOREIGN KEY ("parentId") REFERENCES "ParentIndexTree"(id) ) ; INSERT INTO "ParentIndexTree" VALUES (0, NULL, 0, 1, 'one' ), (1, 0, 0, 2, 'two' ), (2, 0, 1, 3, 'three'), (3, 1, 0, 4, 'four' ), (4, 1, 1, 5, 'five' ) ; Represented tree: 1 / \ 2 3 / \ 4 5 Then for a DBMS with arrays like PostgreSQL](https://www.postgresql.org/docs/14/arrays.html): WITH RECURSIVE "TreeSearch" ( "id", "parentId", "childIndex", "value", "name", "prefix" ) AS ( SELECT "id", "parentId", "childIndex", "value", "name", array[0] FROM "ParentIndexTree" WHERE "parentId" IS NULL UNION ALL SELECT "child"."id", "child"."parentId", "child"."childIndex", "child"."value", "child"."name", array_append("parent"."prefix", "child"."childIndex") FROM "ParentIndexTree" AS "child" JOIN "TreeSearch" AS "parent" ON "child"."parentId" = "parent"."id" ) SELECT * FROM "TreeSearch" ORDER BY "prefix" ; This creates on the fly prefixes of form: 1 -> 0 2 -> 0, 0 3 -> 0, 1 4 -> 0, 0, 0 5 -> 0, 0, 1 and then PostgreSQL then sorts by the arrays alphabetically as: 1 -> 0 2 -> 0, 0 4 -> 0, 0, 0 5 -> 0, 0, 1 3 -> 0, 1 which is the pre-order result that we want. For a DBMS without arrays like SQLite, you can hack by encoding the prefix with a string of fixed width integers. Binary would be ideal, but I couldn't find out how, so hex would work. This of course means you will have to select a maximum depth that will fit in the number of bytes selected, e.g. below I choose 6 allowing for a maximum of 16^6 children per node. WITH RECURSIVE "TreeSearch" ( "id", "parentId", "childIndex", "value", "name", "prefix" ) AS ( SELECT "id", "parentId", "childIndex", "value", "name", '000000' FROM "ParentIndexTree" WHERE "parentId" IS NULL UNION ALL SELECT "child"."id", "child"."parentId", "child"."childIndex", "child"."value", "child"."name", "parent"."prefix" || printf('%06x', "child"."childIndex") FROM "ParentIndexTree" AS "child" JOIN "TreeSearch" AS "parent" ON "child"."parentId" = "parent"."id" ) SELECT * FROM "TreeSearch" ORDER BY "prefix" ; Some nested set notes Here are a few points which confused me a bit after looking at the other nested set answers. Jonny Buchanan shows his nested set setup as: __________________________________________________________________________ | Root 1 | | ________________________________ ________________________________ | | | Child 1.1 | | Child 1.2 | | | | ___________ ___________ | | ___________ ___________ | | | | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | | 1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14 | |________________________________| |________________________________| | |__________________________________________________________________________| which made me wonder why not just use the simpler looking: __________________________________________________________________________ | Root 1 | | ________________________________ _______________________________ | | | Child 1.1 | | Child 1.2 | | | | ___________ ___________ | | ___________ ___________ | | | | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | | 1 2 3___________| 4___________| | 5 6___________| 7___________| | | | |________________________________| |_______________________________| | |_________________________________________________________________________| which does not have an extra number for each endpoint. But then when I actually tried to implement it, I noticed that it was hard/impossible to implement the update queries like that, unless I had parent information as used by Konchog. The problem is that it was hard/impossible to distinguish between a sibling and a parent in one case while the tree was being moved around, and I needed that to decide if I was going to reduce the right hand side or not while closing a gap. Left/size vs left/right: you could store it either way in the database, but I think left/right can be more efficient as you can index the DB with a multicolumn index (left, right) which can then be used to speed up ancestor queries, which are of type: left < curLeft AND right > curLeft Tested on Ubuntu 22.04, PostgreSQL 14.5, SQLite 3.34.0. A: If elements are in tree order, as shown in your example, you can use something like the following Python example: delimiter = '.' stack = [] for item in items: while stack and not item.startswith(stack[-1]+delimiter): print "</div>" stack.pop() print "<div>" print item stack.append(item) What this does is maintain a stack representing the current position in the tree. For each element in the table, it pops stack elements (closing the matching divs) until it finds the parent of the current item. Then it outputs the start of that node and pushes it to the stack. If you want to output the tree using indenting rather than nested elements, you can simply skip the print statements to print the divs, and print a number of spaces equal to some multiple of the size of the stack before each item. For example, in Python: print " " * len(stack) You could also easily use this method to construct a set of nested lists or dictionaries. Edit: I see from your clarification that the names were not intended to be node paths. That suggests an alternate approach: idx = {} idx[0] = [] for node in results: child_list = [] idx[node.Id] = child_list idx[node.ParentId].append((node, child_list)) This constructs a tree of arrays of tuples(!). idx[0] represents the root(s) of the tree. Each element in an array is a 2-tuple consisting of the node itself and a list of all its children. Once constructed, you can hold on to idx[0] and discard idx, unless you want to access nodes by their ID. A: Think about using nosql tools like neo4j for hierarchial structures. e.g a networked application like linkedin uses couchbase (another nosql solution) But use nosql only for data-mart level queries and not to store / maintain transactions
{ "language": "en", "url": "https://stackoverflow.com/questions/192220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "567" }
Q: Can we use dagger only in some parts of an android app? Until now we have not used dagger in our android app. We want to use dagger for whatever new code that we write in our app from now on. Is this possible ? I just started exploring dagger and i have a doubt if this is possible. A: Yes , It is possible. You can add dagger for ongoing project and use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/64121126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GridGain Error : java.lang.NoClassDefFoundError: org/apache/hadoop/mapreduce/JobContext I have configured gridgain-hadoop-os-6.6.2.zip, and followed steps as mentioned in docs/hadoop_readme.pdf . started gridgain using bin/ggstart.sh command, now am running a simple wordcount code in gridgain with hadoop-2.2.0. using command hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/*-mapreduce-examples-*.jar wordcount /input /output Steps I tried: Step 1: Extracted hadoop-2.2.0 and gridgain-hadoop-os-6.6.2.zip file in usr/local folder and changed name for gridgain folder as "gridgain". Step 2: Set the path for export GRIDGAIN_HOME=/usr/local/gridgain.. and path for hadoop-2.2.0 with JAVA_HOME as # Set Hadoop-related environment variables export HADOOP_PREFIX=/usr/local/hadoop-2.2.0 export HADOOP_HOME=/usr/local/hadoop-2.2.0 export HADOOP_MAPRED_HOME=/usr/local/hadoop-2.2.0 export HADOOP_COMMON_HOME=/usr/local/hadoop-2.2.0 export HADOOP_HDFS_HOME=/usr/local/hadoop-2.2.0 export YARN_HOME=/usr/local/hadoop-2.2.0 export HADOOP_CONF_DIR=/usr/local/hadoop-2.2.0/etc/hadoop export GRIDGAIN_HADOOP_CLASSPATH='/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*' Step 3: now i run command as bin/setup-hadoop.sh ... answer Y to every prompt. Step 4: started gridgain using command bin/ggstart.sh Step 5: now i created dir and uploaded file using : hadoop fs -mkdir /input hadoop fs -copyFromLocal $HADOOP_HOME/README.txt /input/WORD_COUNT_ME. txt Step 6: Running this command gives me error: hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/*-mapreduce-examples-*. jar wordcount /input /output Getting following error: 15/02/22 12:49:13 INFO Configuration.deprecation: mapred.working.dir is deprecated. Instead, use mapreduce.job.working.dir 15/02/22 12:49:13 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_091ebfbd-2993-475f-a506-28280dbbf891_0002 15/02/22 12:49:13 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/hduser/.staging/job_091ebfbd-2993-475f-a506-28280dbbf891_0002 java.lang.NullPointerException at org.gridgain.client.hadoop.GridHadoopClientProtocol.processStatus(GridHadoopClientProtocol.java:329) at org.gridgain.client.hadoop.GridHadoopClientProtocol.submitJob(GridHadoopClientProtocol.java:115) at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:430) at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1268) at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1265) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:415) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491) at org.apache.hadoop.mapreduce.Job.submit(Job.java:1265) at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1286) at org.apache.hadoop.examples.WordCount.main(WordCount.java:84) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:72) at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144) at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.util.RunJar.main(RunJar.java:212) and gridgain console error as: sLdrId=a0b8610bb41-091ebfbd-2993-475f-a506-28280dbbf891, userVer=0, loc=true, sampleClsName=java.lang.String, pendingUndeploy=false, undeployed=false, usage=0]], taskClsName=o.g.g.kernal.processors.hadoop.proto.GridHadoopProtocolSubmitJobTask, sesId=e129610bb41-091ebfbd-2993-475f-a506-28280dbbf891, startTime=1424589553332, endTime=9223372036854775807, taskNodeId=091ebfbd-2993-475f-a506-28280dbbf891, clsLdr=sun.misc.Launcher$AppClassLoader@1bdcbb2, closed=false, cpSpi=null, failSpi=null, loadSpi=null, usage=1, fullSup=false, subjId=091ebfbd-2993-475f-a506-28280dbbf891], jobId=f129610bb41-091ebfbd-2993-475f-a506-28280dbbf891]] java.lang.NoClassDefFoundError: org/apache/hadoop/mapreduce/JobContext at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585) at java.lang.Class.getConstructor0(Class.java:2885) at java.lang.Class.getConstructor(Class.java:1723) at org.gridgain.grid.hadoop.GridHadoopDefaultJobInfo.createJob(GridHadoopDefaultJobInfo.java:107) at org.gridgain.grid.kernal.processors.hadoop.jobtracker.GridHadoopJobTracker.job(GridHadoopJobTracker.java:959) at org.gridgain.grid.kernal.processors.hadoop.jobtracker.GridHadoopJobTracker.submit(GridHadoopJobTracker.java:222) at org.gridgain.grid.kernal.processors.hadoop.GridHadoopProcessor.submit(GridHadoopProcessor.java:188) at org.gridgain.grid.kernal.processors.hadoop.GridHadoopImpl.submit(GridHadoopImpl.java:73) at org.gridgain.grid.kernal.processors.hadoop.proto.GridHadoopProtocolSubmitJobTask.run(GridHadoopProtocolSubmitJobTask.java:54) at org.gridgain.grid.kernal.processors.hadoop.proto.GridHadoopProtocolSubmitJobTask.run(GridHadoopProtocolSubmitJobTask.java:37) at org.gridgain.grid.kernal.processors.hadoop.proto.GridHadoopProtocolTaskAdapter$Job.execute(GridHadoopProtocolTaskAdapter.java:95) at org.gridgain.grid.kernal.processors.job.GridJobWorker$2.call(GridJobWorker.java:484) at org.gridgain.grid.util.GridUtils.wrapThreadLoader(GridUtils.java:6136) at org.gridgain.grid.kernal.processors.job.GridJobWorker.execute0(GridJobWorker.java:478) at org.gridgain.grid.kernal.processors.job.GridJobWorker.body(GridJobWorker.java:429) at org.gridgain.grid.util.worker.GridWorker.run(GridWorker.java:151) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.ClassNotFoundException: Failed to load class: org.apache.hadoop.mapreduce.JobContext at org.gridgain.grid.kernal.processors.hadoop.GridHadoopClassLoader.loadClass(GridHadoopClassLoader.java:125) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 20 more Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.mapreduce.JobContext at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at org.gridgain.grid.kernal.processors.hadoop.GridHadoopClassLoader.loadClassExplicitly(GridHadoopClassLoader.java:196) at org.gridgain.grid.kernal.processors.hadoop.GridHadoopClassLoader.loadClass(GridHadoopClassLoader.java:106) ... 21 more ^[[B Help here.... Edited Here : raj@ubuntu:~$ hadoop classpath /usr/local/hadoop-2.2.0/etc/hadoop:/usr/local/hadoop-2.2.0/share/hadoop/common/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/common/*:/usr/local/hadoop-2.2.0/share/hadoop/hdfs:/usr/local/hadoop-2.2.0/share/hadoop/hdfs/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/hdfs/*:/usr/local/hadoop-2.2.0/share/hadoop/yarn/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/yarn/*:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce/lib/*:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce/*:/usr/local/hadoop-2.2.0/contrib/capacity-scheduler/*.jar raj@ubuntu:~$ jps 3529 GridCommandLineStartup 3646 Jps raj@ubuntu:~$ echo $GRIDGAIN_HOME /usr/local/gridgain raj@ubuntu:~$ echo $HADOOP_HOME /usr/local/hadoop-2.2.0 raj@ubuntu:~$ hadoop version Hadoop 2.2.0 Subversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768 Compiled by hortonmu on 2013-10-07T06:28Z Compiled with protoc 2.5.0 From source with checksum 79e53ce7994d1628b240f09af91e1af4 This command was run using /usr/local/hadoop-2.2.0/share/hadoop/common/hadoop-common-2.2.0.jar raj@ubuntu:~$ cd /usr/local/hadoop-2.2.0/share/hadoop/mapreduce raj@ubuntu:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce$ ls hadoop-mapreduce-client-app-2.2.0.jar hadoop-mapreduce-client-hs-2.2.0.jar hadoop-mapreduce-client-jobclient-2.2.0-tests.jar lib hadoop-mapreduce-client-common-2.2.0.jar hadoop-mapreduce-client-hs-plugins-2.2.0.jar hadoop-mapreduce-client-shuffle-2.2.0.jar lib-examples hadoop-mapreduce-client-core-2.2.0.jar hadoop-mapreduce-client-jobclient-2.2.0.jar hadoop-mapreduce-examples-2.2.0.jar sources raj@ubuntu:/usr/local/hadoop-2.2.0/share/hadoop/mapreduce$ A: I configured exactly the versions you mentioned (gridgain-hadoop-os-6.6.2.zip + hadoop-2.2.0) -- the "wordcount" sample works fine. [UPD after question's author log analysis:] Raju, thanks for the detailed logs. The cause of the problem are incorrectly set env variables export HADOOP_MAPRED_HOME=${HADOOP_HOME} export HADOOP_COMMON_HOME=${HADOOP_HOME} export HADOOP_HDFS_HOME=${HADOOP_HOME} You explicitly set all these variables to ${HADOOP_HOME} value, what is wrong. This causes GG to compose incorrect hadoop classpath, as seen from the below GG Node log: +++ HADOOP_PREFIX=/usr/local/hadoop-2.2.0 +++ [[ -z /usr/local/hadoop-2.2.0 ]] +++ '[' -z /usr/local/hadoop-2.2.0 ']' +++ HADOOP_COMMON_HOME=/usr/local/hadoop-2.2.0 +++ HADOOP_HDFS_HOME=/usr/local/hadoop-2.2.0 +++ HADOOP_MAPRED_HOME=/usr/local/hadoop-2.2.0 +++ GRIDGAIN_HADOOP_CLASSPATH='/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*:/usr/local/hadoop-2.2.0/lib/*' So, to fix the issue please don't set unnecessary env variables. JAVA_HOME and HADOOP_HOME is quite enough, nothing else is needed. A: many thnaks to Ivan, thanks for your help and support, the solution you gave was good to get me out of the problem. The issue was not to set other hadoop related environment variables. this is enough to set. JAVA_HOME , HADOOP_HOME and GRIDGAIN_HOME
{ "language": "en", "url": "https://stackoverflow.com/questions/28655536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change a predeterminate underline color in an Input with Materialize w/Ruby on Rails I really try so hard to change the underline color but I can't, I don't know where do that, please help me! <div class="row"> <div class="col-md-6 col-md-offset-3"> <%= form_for(:session, url: login_path) do |f| %> <%= f.label :email %> <%= f.email_field :email, class: 'form-control white-text' %> <br> <%= f.label :password %> <%= f.password_field :password, class: 'form-control white-text' %> <br> <%= f.submit "Log in", class: "btn" ,style:"color:white;background-color: #EEB756;" %> <% end %> </div> </div> A: You can change the class .input-field, and add more specific selector, for example: .input-field input or to email type of input .input-field input[type=email] or to focused field: .input-field input[type=text]:focus And set the border style: .input-field input[type=text]:focus{ border-bottom: 1px solid #aaa; } You can read more in Materialize documentation: http://materializecss.com/forms.html EDIT: edited as suggested by @Toby1Kenobi A: According to the docs you can change the underline colour in CSS by modifying the colour of border-bottom and box-shadow of the element containing the input element (that is the one with the class input-field) so maybe it would be something like this: .input-field input[type=email] { border-bottom: 1px solid red; box-shadow: 0 1px 0 0 red; }
{ "language": "en", "url": "https://stackoverflow.com/questions/50048432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete a pointer belonging to an object stored in a vector? I have a Containing class, a Contained class, and a Data class. That Containing class holds a vector of Contained objects. The Contained class holds a pointer to a data object, allocated on the heap in Contained's constructor. However, I can't deallocate it in the destructor, since the vector will create copies of Contained and then destroy them, thus destroying the data pointer even in the copy we're using. TL;DR Here's some code to explain: class Data { public: Data(); }; class Contained { private: Data* data; public: Contained(); // what should I add ? a copy constructor ? an assignement operator ? and how }; class Container { private: vector<Contained> rooms; public: //some member functions }; Contained::Contained() { data = new Data(); } Where do I delete data ? A: Using RAII(Resource Acquisition is Initialization) Add a destructor to the Contained class: Contained::~Contained() { delete data; } This will ensure whenever your contained object goes out of scope, it will automatically delete the data pointer it has. So if you do //delete first element rooms.erase(rooms.begin()); data ptr of that object will automatically be deleted. Using smart pointers Use std::unique_ptr<T>. class Contained { private: std::unique_ptr<Data> data; public: Contained(); // what should I add ? a copy constructor ? an assignement operator ? and how }; and in the constructor: Contained::Contained() { data = std::make_unique<Data>(); } Using smart pointers i.e., (unique_ptr, shared_ptr) ensures your pointer will automatically delete when no one is owning it. Since you can not copy unique_ptr but only move it, you should define a move constructor and move assignment operator on the Contained class. Contained::Contained(Contained&& other) : data(std::move(other.data)) {} Contained& operator=(Contained&& rhs) { if (this != &other) { data = std::move(rhs.data); } return *this; }
{ "language": "en", "url": "https://stackoverflow.com/questions/60915586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finding if file exists ANYWHERE c# For starters, I'm quite new to C#. How would I go about checking if a (.exe) file exists anywhere on a pc's memory? I tried to google an answer, but only ones I came across required you to specify a directory where to look from. I'm building an application that launches certain apps which the user selects, hence why I can't know the directory where the file is in. Is there a way of checking it without a directory, aka check if the file exists anywhere on the pc? Alternatively, is there a way to handle an error where the selected file is not found?
{ "language": "en", "url": "https://stackoverflow.com/questions/49710227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: apt-get fails on i386/debian docker image I have a 32-bit Ubuntu server, running 17.10 Artful & with docker.io installed (my understanding is this is the only version available for 32-bit) jonny@grizzly ~ $ lsb_release -cs artful jonny@grizzly ~ $ apt list | grep docker.io WARNING: apt does not have a stable CLI interface. Use with caution in scripts. 4384:docker.io/artful,now 1.13.1-0ubuntu6 i386 [installed] I am attempting to use i386/debian image (I have also tried 32bit/Ubuntu with similar results), and having issues with apt-get. Sources appear to be configured sensibly, but apt-get update gets 404 errors. Hitting the same URLs (with .gz appended) from browser works fine. ping works within Docker image, wget & curl aren't available so haven't been able to further diagnose possible network issues. jonny@grizzly ~ $ docker run -it i386/debian /bin/bash root@1023ad95222c:/# more /etc/apt/sources.list deb http://deb.debian.org/debian stretch main deb http://security.debian.org/debian-security stretch/updates main deb http://deb.debian.org/debian stretch-updates main root@1023ad95222c:/# apt-get update Ign:1 http://security.debian.org/debian-security stretch/updates InRelease Ign:2 http://security.debian.org/debian-security stretch/updates Release Ign:3 http://deb.debian.org/debian stretch InRelease Ign:4 http://deb.debian.org/debian stretch-updates InRelease Ign:5 http://deb.debian.org/debian stretch Release Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages Ign:8 http://deb.debian.org/debian stretch-updates Release Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages Ign:9 http://deb.debian.org/debian stretch/main all Packages Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages Ign:10 http://deb.debian.org/debian stretch/main i386 Packages Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages Ign:9 http://deb.debian.org/debian stretch/main all Packages Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages Ign:10 http://deb.debian.org/debian stretch/main i386 Packages Ign:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages Ign:6 http://security.debian.org/debian-security stretch/updates/main all Packages Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages Err:7 http://security.debian.org/debian-security stretch/updates/main i386 Packages 404 [IP: 212.211.132.250 80] Ign:9 http://deb.debian.org/debian stretch/main all Packages Ign:10 http://deb.debian.org/debian stretch/main i386 Packages Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages Ign:9 http://deb.debian.org/debian stretch/main all Packages Ign:10 http://deb.debian.org/debian stretch/main i386 Packages Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages Ign:9 http://deb.debian.org/debian stretch/main all Packages Ign:10 http://deb.debian.org/debian stretch/main i386 Packages Ign:11 http://deb.debian.org/debian stretch-updates/main i386 Packages Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages Ign:9 http://deb.debian.org/debian stretch/main all Packages Err:10 http://deb.debian.org/debian stretch/main i386 Packages 404 [IP: 130.89.148.14 80] Err:11 http://deb.debian.org/debian stretch-updates/main i386 Packages 404 [IP: 130.89.148.14 80] Ign:12 http://deb.debian.org/debian stretch-updates/main all Packages Reading package lists... Done W: The repository 'http://security.debian.org/debian-security stretch/updates Release' does not have a Release file. N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use. N: See apt-secure(8) manpage for repository creation and user configuration details. W: The repository 'http://deb.debian.org/debian stretch Release' does not have a Release file. N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use. N: See apt-secure(8) manpage for repository creation and user configuration details. W: The repository 'http://deb.debian.org/debian stretch-updates Release' does not have a Release file. N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use. N: See apt-secure(8) manpage for repository creation and user configuration details. E: Failed to fetch http://security.debian.org/debian-security/dists/stretch/updates/main/binary-i386/Packages 404 [IP: 212.211.132.250 80] E: Failed to fetch http://deb.debian.org/debian/dists/stretch/main/binary-i386/Packages 404 [IP: 130.89.148.14 80] E: Failed to fetch http://deb.debian.org/debian/dists/stretch-updates/main/binary-i386/Packages 404 [IP: 130.89.148.14 80] E: Some index files failed to download. They have been ignored, or old ones used instead. I've tried various different mirrors I've found online with no difference. I've also tried a few different versions/tags of the i386/debian docker image. No proxy used to access internet on this server. Are there any other steps I may be missing here?
{ "language": "en", "url": "https://stackoverflow.com/questions/51176070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is my User Group Information Do as not passing my keytab token to my HDFS access method When I attempt to list the files in a HDFS directory I am receiving the following error: main] ERROR com.pr.hdfs.common.hadooputils.HdfsUtil - Failed to connect to hdfs directory /HDFS/Datastore/DB org.apache.hadoop.security.AccessControlException: SIMPLE authentication is not enabled. Available:[TOKEN, KERBEROS] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106) at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:73) The code I am using although being accessed as scala is the following Java: public static List<Path> listHdfsFilePaths(final FileSystem hdfs, final String directory) throws IOException { final List<Path> result = new ArrayList<>(); final FileStatus[] fileStatuses; try { fileStatuses = hdfs.listStatus(new Path(directory)); for (final FileStatus fileStatus : fileStatuses) { result.add(fileStatus.getPath()); } } catch (final IOException e) { LOGGER.error("Failed to connect to hdfs directory " + directory, e); throw e; } return result; } The scala code wraps a User Group Information doas to access the folder: val auctions = ugiDoAs(ugi){ val hdfs = FileSystem.get(hadoopConf) HdfsUtils.listHdfsFilePaths(hdfs, "/HDFS/Datastore/DB/") } The ugiDoAs method is specified as: def ugiDoAs[T](ugi: Option[UserGroupInformation])(code: => T) = ugi match { case None => code case Some(u) => u.doAs(new PrivilegedExceptionAction[T] { override def run(): T = code }) } The ugiDoAs wrapper works for reading from Zookeeper, reading from Hbase but just not accessing HDFS in this case. Also, my ugi variable contains the keytab and the principal needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/36128295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to resolve dependency tree after upgrading node, failing on node-sass After upgrading Node to the latest version, I start getting these error messages when I tried npm audit fix --force. It seems like I'm unable to fix my dependency tree issues. I've tried to search for solutions to this error extensively and tried many different solutions but none worked. Should the only solution be downgrading back to an older Node version? npm ERR! path /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass npm ERR! command failed npm ERR! command sh -c node scripts/build.js npm ERR! Building: /usr/local/bin/node /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= npm ERR! gyp info it worked if it ends with ok npm ERR! gyp verb cli [ npm ERR! gyp verb cli '/usr/local/bin/node', npm ERR! gyp verb cli '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js', npm ERR! gyp verb cli 'rebuild', npm ERR! gyp verb cli '--verbose', npm ERR! gyp verb cli '--libsass_ext=', npm ERR! gyp verb cli '--libsass_cflags=', npm ERR! gyp verb cli '--libsass_ldflags=', npm ERR! gyp verb cli '--libsass_library=' npm ERR! gyp verb cli ] npm ERR! gyp info using [email protected] npm ERR! gyp info using [email protected] | darwin | x64 npm ERR! gyp verb command rebuild [] npm ERR! gyp verb command clean [] npm ERR! gyp verb clean removing "build" directory npm ERR! gyp verb command configure [] npm ERR! gyp verb check python checking for Python executable "python2" in the PATH npm ERR! gyp verb `which` succeeded python2 /usr/bin/python2 npm ERR! gyp verb check python version `/usr/bin/python2 -c "import platform; print(platform.python_version());"` returned: "2.7.16\n" npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 16.13.0 npm ERR! gyp verb command install [ '16.13.0' ] npm ERR! gyp verb install input version string "16.13.0" npm ERR! gyp verb install installing version: 16.13.0 npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed npm ERR! gyp verb install version is already installed, need to check "installVersion" npm ERR! gyp verb got "installVersion" 9 npm ERR! gyp verb needs "installVersion" 9 npm ERR! gyp verb install version is good npm ERR! gyp verb get node dir target node version installed: 16.13.0 npm ERR! gyp verb build dir attempting to create "build" dir: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build npm ERR! gyp verb build dir "build" dir needed to be created? /Users/Mac/Desktop/Projects/folder/Website/filder/node_modules/node-sass/build npm ERR! gyp verb build/config.gypi creating config file npm ERR! gyp verb build/config.gypi writing out config file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build/config.gypi npm ERR! (node:19391) [DEP0150] DeprecationWarning: Setting process.config is deprecated. In the future the property will be read-only. npm ERR! (Use `node --trace-deprecation ...` to show where the warning was created) npm ERR! gyp verb config.gypi checking for gypi file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/config.gypi npm ERR! gyp verb common.gypi checking for gypi file: /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/common.gypi npm ERR! gyp verb gyp gyp format was not specified; forcing "make" npm ERR! gyp info spawn /usr/bin/python2 npm ERR! gyp info spawn args [ npm ERR! gyp info spawn args '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/gyp/gyp_main.py', npm ERR! gyp info spawn args 'binding.gyp', npm ERR! gyp info spawn args '-f', npm ERR! gyp info spawn args 'make', npm ERR! gyp info spawn args '-I', npm ERR! gyp info spawn args '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass/build/config.gypi', npm ERR! gyp info spawn args '-I', npm ERR! gyp info spawn args '/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/addon.gypi', npm ERR! gyp info spawn args '-I', npm ERR! gyp info spawn args '/Users/Mac/.node-gyp/16.13.0/include/node/common.gypi', npm ERR! gyp info spawn args '-Dlibrary=shared_library', npm ERR! gyp info spawn args '-Dvisibility=default', npm ERR! gyp info spawn args '-Dnode_root_dir=/Users/Mac/.node-gyp/16.13.0', npm ERR! gyp info spawn args '-Dnode_gyp_dir=/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp', npm ERR! gyp info spawn args '-Dnode_lib_file=/Users/Mac/.node-gyp/16.13.0/<(target_arch)/node.lib', npm ERR! gyp info spawn args '-Dmodule_root_dir=/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass', npm ERR! gyp info spawn args '-Dnode_engine=v8', npm ERR! gyp info spawn args '--depth=.', npm ERR! gyp info spawn args '--no-parallel', npm ERR! gyp info spawn args '--generator-output', npm ERR! gyp info spawn args 'build', npm ERR! gyp info spawn args '-Goutput_dir=.' npm ERR! gyp info spawn args ] npm ERR! No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'. npm ERR! npm ERR! No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'. npm ERR! npm ERR! No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'. npm ERR! npm ERR! gyp: No Xcode or CLT version detected! npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1 npm ERR! gyp ERR! stack at ChildProcess.onCpExit (/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/lib/configure.js:345:16) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:390:28) npm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (node:internal/child_process:290:12) npm ERR! gyp ERR! System Darwin 19.6.0 npm ERR! gyp ERR! command "/usr/local/bin/node" "/Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library=" npm ERR! gyp ERR! cwd /Users/Mac/Desktop/Projects/folder/Website/folder/node_modules/node-sass npm ERR! gyp ERR! node -v v16.13.0 npm ERR! gyp ERR! node-gyp -v v3.7.0 npm ERR! gyp ERR! not ok npm ERR! Build failed with error code: 1 npm ERR! A complete log of this run can be found in: npm ERR! /Users/Mac/.npm/_logs/2021-11-24T18_21_54_491Z-debug.log A: First solution Make sure your nodejs version is not superior than the latest stable one. For that you can use n package from npm: npm install -g n n stable # if one of the commands does not pass, you may need to use sudo sudo npm install -g n sudo n stable Then you would wanna use sass package instead of node-sass, as it's deprecated. And for that run those commands: npm uninstall node-sass --save npm install sass --save Second solution If you need or want node-sass for some reasons, you should downgrade your nodejs version to like v14. For that you can use n package from npm: npm install -g n n 14 # if one of the commands does not pass, you may need to use sudo sudo npm install -g n sudo n 14 A: I got rid of everything and re-installed Xcode, Node and node-sass again, and the issue is resolved.
{ "language": "en", "url": "https://stackoverflow.com/questions/70101470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Uninstall a Component in vue.js I installed this component in my application. I would like to uninstall it now. How can I do that ?
{ "language": "en", "url": "https://stackoverflow.com/questions/47845457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular Material unit tests - Failed to find MatHarness element I am writing unit tests for my app which uses Angular Material. I wanna make sure that there's a material card in the page. For this, I use the following code: let loader: HarnessLoader; let component: LoginComponent; let fixture: ComponentFixture<LoginComponent>; let authService: jasmine.SpyObj<AuthService>; beforeEach(async () => { authService = jasmine.createSpyObj<AuthService>(['authenticate', 'logout']); await TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [LoginComponent], providers: [{ provide: AuthService, useValue: authService }] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(LoginComponent); loader = TestbedHarnessEnvironment.loader(fixture); fixture.detectChanges(); }); it('should display a material card', async () => { const card = await loader.getHarness(MatCardHarness); expect(card).toBeTruthy(); }); But, this returns the error: Error: Failed to find element matching one of the following queries: (MatCardHarness with host element matching selector: ".mat-card") Here's my HTML: <mat-card class="custom-class"> <h2>Sign In</h2> </mat-card> I'll be able to solve this by adding mat-card class to the <mat-card> element. But isn't it supposed to work without manually adding the class? Is there anything wrong with the way I set up my tests? A: Try importing MatCardModule into you TestBed configuration. import { MatCardModule } from '@angular/material/card'; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule, MatCardModule, ], declarations: [LoginComponent], providers: [{ provide: AuthService, useValue: authService }] }).compileComponents(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/67225431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the technology most commonly used for iPhone - iPad communications? What is the most commonly used technology for communicating between an application running on an iPad and one on an iPhone? For example, the famous Scrabble application uses device-to-device communication to host the game board on the iPad and the letters on the iPhone. A: Bluetooth P2P connection. Check that
{ "language": "en", "url": "https://stackoverflow.com/questions/3342990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open/run YML compose file? How can I open/run a YML compose file on my computer? I've installed Docker for Windows and Docker tools but couldn't figure out how. A: If you are asking how to open YAML files, then you can use some common editors like NotePad++ in windows or vim in linux. If your question is about running the compose yaml file, then run this command from the directory where compose file is residing: docker-compose -f {compose file name} up You can avoid -f if your filename is docker-compose.yml A: To manage .yml files you have to install and use Docker Compose. Installation instructions can be found here: https://docs.docker.com/compose/install/ After the installation, go to your docker-compose.yml directory and then execute docker-compose up to create and start services in your docker-compose.yml file. If you need more information, take a look to Docker Compose docs: https://docs.docker.com/compose
{ "language": "en", "url": "https://stackoverflow.com/questions/44364916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: How can my Spring integration tests create their own schema based on the model in a HSQL database? Writting some integration tests in Spring (Like in this question) I will like to avoid the work of a big script to create all tables in HSQL: <jdbc:script location="classpath:createSchema.sql" /> As Spring is creating and updating my development tables from the model automagically. How could I tell Spring to do the same things for my integration tests? My datasource file is <?xml version="1.0" encoding="UTF-8"?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "http://www.springframework.org/schema/context" xmlns:jee= "http://www.springframework.org/schema/jee" xmlns:p= "http://www.springframework.org/schema/p" xmlns:jdbc= "http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"> <!-- Usamos HSQLDB para hacer las pruebas con in-memory db --> <jdbc:embedded-database id="dataSource" type="HSQL"> <jdbc:script location="classpath:create_schema.sql"/> <jdbc:script location="classpath:import.sql"/> </jdbc:embedded-database> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.myProject.model" /> <property name="hibernateProperties"> <props> <prop key="hibernate.default_schema">TESTING</prop> <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">create-drop</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> Update: After NimChimpsky answer I had included the schema name in hibernate properties and created a script with just: CREATE SCHEMA TESTING After trying the first insert int the import.sql script I see: org.hsqldb.hsqlexception user lacks privilege or object not found [MyTable] A: You still need to create schema manually - but literally only the create schema my-schema-name statement, let hibernate create the tables <jdbc:embedded-database id="dataSource" type="HSQL"> <jdbc:script location="classpath:create_schema.sql"/> </jdbc:embedded-database> If populating the database with values is a problem, yeah it is. No shortcuts really. And the import script will have to run after the tables are created, in a postconstruct method probably. A: I solved the issue with the help of geoand comment. (Thanks, you should have posted it as an answer). But let me share more information to make future reader's life easier. First. It seems that telling that you have an script to initializa database makes hibernate to avoid the creation proccess. I changed the code embedded elemento to: <jdbc:embedded-database id="dataSource" type="HSQL"/> Hibernate will automatically execute import.sql from the classpath (at least in Create or Create-Drop mode) so there was no need to indicate further scripts. As Spring test framework does rollback the transaction you do no need to restore the database after each test. Second, I had some problems with my context configuration that needed to be solved if I wanted Spring to create my schema. The best way to do it was to set the ignore failures attribute to "ALL" and look and the logs. Third. Using HSQL for a few things MySQL for others has its own issues. Syntax is sometimes different and I had to fix my import.sql to become compatible with both databases. Appart from that, it works: @ContextConfiguration(locations={"file:src/test/resources/beans-datasource.xml", "file:src/main/webapp/WEB-INF/applicationContext.xml", "file:src/main/webapp/WEB-INF/my-servlet.xml"}) @Configuration @RunWith(SpringJUnit4ClassRunner.class) public static class fooTest{ @Inject BeanInterface myBean; @Test @Transactional public void fooGetListTest(){ assertTrue("Expected a non-empty list", myBean.getList().size() > 0 ); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/23539545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax call include not works in Wordpress I have a PHP file that I call with Cron Job and I need it separately from the rest of code. So, I have a button that call AJAX request from my dashboard. The Ajax function in my Wordpress plugin includes the file (process.php), this in turn, includes another file (snippets.php). If I call process.php directly, it works perfectly, but not from Ajax call. Folder structure plugin.php plugin.js snippets.php processes/process.php plugin.js jQuery.ajax({ type: 'GET', url: ajaxurl, data : { action : 'process', } }) plugin.php function process(){ include_once( 'processes/process.php' ); } add_action( 'wp_ajax_process', 'process' ); process.php include_once('../snippets.php') //here not includes 'snippets.php' A: You should use relative includes from their own file, otherwise, it will run from the current path. To force this you can use __DIR__ and start with a slash plugin.php function process(){ include_once(__DIR__.'/processes/process.php' ); } add_action('wp_ajax_process', 'process' ); process.php include_once(__DIR__.'/../snippets.php'); //here not includes 'snippets.php' Also, you forgot the semicolumn ; in process.php
{ "language": "en", "url": "https://stackoverflow.com/questions/50914257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unit tests for a custom Date Serializer I have recently started writing tests in Java and I am having some problem with the tests for the following class. How to write correctly tests for TestDateTimeSerializer class in such a form. public class TestDateTimeSerializer extends JsonSerializer<LocalDateTime> { public static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); @Override public void serialize(LocalDateTime dt, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException { if (dt == null) { gen.writeNull(); } else { gen.writeString(dt.format(FORMATTER)); } } } this class is used here @Data @JsonIgnoreProperties(ignoreUnknown = true) @JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES) public class TestRequest implements ITestResponse { @JsonProperty("TestID") private Long testID; @JsonSerialize(using = TestDateTimeSerializer.class) private LocalDateTime lastUpdateDate; } A: Make JsonGenerator as mock object, then verify its method call. @ExtendWith(MockitoExtension.class) class TestDateTimeSerializerTest { @Mock JsonGenerator generator; // JsonGenerator is mock @Mock SerializerProvider provider; @Test void test() throws IOException { TestDateTimeSerializer serializer = new TestDateTimeSerializer(); LocalDateTime now = LocalDateTime.now(); // run your method serializer.serialize(now, generator, provider); // assert mocked generator's method call verify(generator).writeString(ArgumentMatchers.anyString()); } } Mockito API doc : https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#1 you can find more example and usage. A: Please try this: import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import org.junit.Before; import org.junit.Test; import java.time.LocalDateTime; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME; import static org.junit.Assert.*; public class TestDateTimeSerializerSerializerTest { private ObjectMapper mapper; protected TestDateTimeSerializer serializer; @Before public void setup() { mapper = new ObjectMapper(); serializer = new TestDateTimeSerializer(); SimpleModule module = new SimpleModule(); module.addSerializer(LocalDateTime.class, serializer); mapper.registerModule(module); } @Test public void testSerializeNonNull() throws JsonProcessingException { LocalDateTime ldt = LocalDateTime.parse("2016-10-06T10:40:21.124", ISO_LOCAL_DATE_TIME); String serialized = mapper.writeValueAsString(ldt); assertEquals("equal strings", "\"2016-10-06T10:40:21.124Z\"", serialized); } @Test public void testSerializeNull() throws JsonProcessingException { LocalDateTime ldt = null; String serialized = mapper.writeValueAsString(ldt); assertEquals("equal strings", "null", serialized); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/72378101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access nested model attributes I have following setup: class EmpsController < ApplicationController def new @emp = Emp.new @unit_options = Unit.all.collect{|unit| [unit.name, unit.id] } end def create @emp = Emp.new(emp_params) @emp.save! redirect_to :action => :list end def destroy @emp = Emp.find([:id]) @emp.destroy redirect_to :action => :list end def list @emps = Emp.all end def emp_params params.require(:emp).permit(:name, :unit_id) end end Model: class Emp < ApplicationRecord has_one :units accepts_nested_attributes_for :units end Form: <p> List of Employees: </p> <table> <% @emps.each do |u| %> <tr> <td><%= u.id %></td> <td><%= u.name %></td> <td><%= u.unit_id %></td> <td><%= link_to "Delete", u, :method => :delete %></td> </tr> <% end %> </table> All I want to do is to print (in table above) unit attribute called :name related with Emp printed Emp object. Found various related solution but they do not apply to my case. A: First, don't use :units as the association name, it "has one unit" no "units", Rails convention over configuration expects the association to be singular. Then you should be able to do some_emp.unit.name. Or you can use method delegation: class Emp < ApplicationRecord has_one :unit delegate :name, to: :unit end And now you can do some_emp.name.
{ "language": "en", "url": "https://stackoverflow.com/questions/59436105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the Java equivalent of Objective-C's NSDictionary? What is the closest implementation of Objective-C's NSDictionary in Java? To me, it looks like HashMap<String, Object>, but I'm very new to Objective-C. Thanks A: NSDictionary is a class cluster (see the "Class Cluster" section in The Cocoa Fundamentals Guide), meaning that the actual implementation is hidden from you, the API user. In fact, the Foundation framework will choose the appropriate implementation at run time based on amount of data etc. In addition, NSDictionary can take any id as a key, not just NSString (of course, the -hash of the key object must be constant). Thus, closest analog is probably Map<Object,Object>. A: For practical usage: HashMap<String, Object> would be the way to go for a simple, non-parallel dictionary. However, if you need something that is thread-safe (atomic), you'd have to use HashTable<String, Object> which is thread safe, but - notably - does not accept null as a valid value or key. A: I'm admittedly an Android newbie, but to me ContentValues seems to be the closest thing to NSDictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/8128408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Indexing lists of list/vectors Data lst <- list(1, 1:3, 2:4) ind <- c(1, 2, 2) Problem I can guarantee that length(ind) == length(lst) and now I want to get the 1st element of the the first element of lst, then the second element of the second element and finally the second element of the third element. With a loop I could do something like sapply(seq_along(ind), function(i) lst[[i]][[ind[i]]]) So my question is whether I need the loop or is there any smart indexing technique which I am not aware of? Background of the question is that I have the impression that I do not make best use of R's capability to do incredible stuff with smart indexing (like indexing a matrix with another matrix). A: We can use mapply to get the corresponding element of 'lst' based on the index in 'ind'. mapply(`[`, lst, ind) #[1] 1 2 3
{ "language": "en", "url": "https://stackoverflow.com/questions/39119294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: $elemMatch projection in node.js dbo.collection("users") .findOne({email: emailGiven, "friends.email": element.email}, { friends: { $elemMatch: { email: element.email } } }, function(errT, resultT) {}) I have the query above in node.js but for some reason the query's elemMatch part doesn't work on node.js but when I execute the same query in mongo terminal it works, so I'm thinking maybe node.js doesn't support $elemMatch? If this is the case, could anyone tell me what would be the equivalent of this query in node.js? Sample data from my DB: /* 4 */ { "_id" : ObjectId("5ad20cef8248544860ce3dc1"), "username" : "test", "email": "", "fullName" : "", "friends" : [{email: "", status :""}], "alarms": [ {"id":111, "title": "TITLE", "location": "", "startTime": "10-10-1996 10:18:00", "endTime": "10-10-1996 10:18:00" }, {},{} ], "pnumber" : "" } A: The node.js driver findOne has a different call signature than the findOne in the MongoDB shell. You pass the field selection object as the projection element of the options parameter: dbo.collection("users") .findOne({"friends.email": email}, {projection: { friends: { $elemMatch: { email: email } } } }, function(errT, resultT) {...}); A: If you want to find for any values which is stored in some variable, you use regex for that. Your query should look like dbo.collection("users").findOne({ email: new RegExp(emailGiven, 'i'), "friends.email": new RegExp(element.email, 'i') }, { friends: { $elemMatch: { email: new RegExp(element.email, 'i') } } }, function(errT, resultT) {}) i is for case insensitive comparison here
{ "language": "en", "url": "https://stackoverflow.com/questions/50068893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Nested list with TAL I'm using Chameleon in the Pyramids Framework and want to repeat nested list while rendering the template. My minimized HTML-Code is: 1. <ul> 2. <li tal:repeat="item items"> 3. <input tal:attributes="id item.id; onclick item.url"> 4. <label tal:repeat="premise item.values" tal:attributes="for item.id; id premise.id"> 5. <label tal:replace="premise.title"/> 6. </label> 7. <label tal:attributes="for item.id" tal:content="item.title"/> 8. </li> 9. </ul> Whereby I got the following json-Data [{ 'url': 'location.href="http://..."', 'values': [{ 'id': '70', 'title': 'some title 1' }], 'attitude': 'justify', 'id': '68', 'title': 'some title 2' }, { 'url': 'null', 'values': [{ 'id': '0', 'title': 'some title 3! }], 'attitude': 'justify', 'id': '0', 'title': 'some title 4' }] If I kill HTML-lines 4.-6., everything is fine, otherwise Pyramid/Chameleon throws: File "/usr/local/lib/python3.4/dist-packages/chameleon/tal.py", line 471, in __call__ iterable = list(iterable) if iterable is not None else () TypeError: 'builtin_function_or_method' object is not iterable Anyone some idea? A: Thanks to #pyramid in the IRC i got the first hint, which is mentioned in the comment. But..never ever name a key 'value' or 'values'!
{ "language": "en", "url": "https://stackoverflow.com/questions/34946872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Angular JS - Date changes when submitting to $http - Timezone issue I am having a strange problem where a Date changes when it is passed to API through $http.put, I suspect a timezone issue: Datepicker triggers ng-change event - console.log: Tue Jun 10 2014 00:00:00 GMT+0100 (GMT Summer Time) Passed to API using Angular $http.put... When it hits Fiddler: StartDate=2014-06-09T23:00:00.000Z As you can see the date changes from 10th June to 9th June. How can I stop this change of date? Is it the timezone causing the change? Both the API and client side are running on Localhost. Further to this: When the field is clicked a second time and the datepicker launched / date selected, this second time the problem does not appear: Console.log: Wed Aug 06 2014 22:00:00 GMT+0100 (GMT Summer Time) Fiddler data received: StartDate=2014-08-06T21:00:00.000Z A: I think it is a TZ issue, b/c the difference between your GMT+0100 and your StartDate=2014-06-09T23:00:00.000Z is 5 hours. . The issue: Your local time is currently BST (British Summer Time) equivalent to GMT +1 This is going to be the default time when you make your API call. However, the API was written by Google in California, and they are rather egocentric. Therefore, they're automatically converting the time since you're not providing any date formatting "instructions". In other words, Chrome does the conversion for you nicely when you print to the console.log(), but when you make your $http.put, Angular, without explicit formatting for you, makes the call using it's default TZ (which is PST) . Resolution You need to force the date formatting to your locale. * *Angular template {{ date_expression | date : 'yyyy-MM-dd HH:mm:ss'}} *In JavaScript $filter('date')(date, 'yyyy-MM-dd HH:mm:ss') *using localization <html> <head> <title>My Angular page</title> <script src="angular-locale_en-uk.js"></script> ... </head> <body> ... </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/24356475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Lotus Notes - Column view as Totals: Total showing not 0.00 even if there aren't no docs saved I have a view which contains a column ( as Total ) . Even, there aren't any docs created, the column shows: 165.65 ( as total ) and not 0.00 ( as it should be ) Any suggestions? A: Does the view show documents in a response hierarchy? Probably there is an "orphaned" response (Replication conflict or other reason) that is not shown in the view as the parent document is missing, but still is counted in the total- column. Try disable response- hierarchy in the View- Properties and check if there is such a document. An additional reason for the total not being 0 could also be a document that is protected by a readers- field. Server will add this document to the totals (as View- Index is created by the server) whereas the Designer / User does not see the document. If you know, what is in the Readers- Field (Role, GroupName, etc.) then make yourself member of that field (by assigning the Role to yourself or add yourself to the group). If you don't know, what's in there (or something went wrong filling the readers field, e.g. forgot to tick the "multi value"- property), then you need somebody with "Full Access Administration"- right to the server. This Admin- function ovverrides all Reader- fields and makes the document visible to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/17043245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding another variable information or adding weight into stat_density_2d Below is a simple code to produce stat_density_2d plot of X~Y. plot_data <- data.frame(X = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)), Y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)), Z = c(rnorm(300, 60, 5), rnorm(150, 40, 5)), Label = c(rep('A', 300), rep('B', 150))) ggplot(plot_data, aes(x=X, y=Y)) + stat_density_2d(geom = "polygon", aes(alpha = stat(level), fill = Label)) As I understand, the density is based on the count of X~Y. My question is can I use Z as the density? Or perhaps, add Z as weight to the density? I'm not sure I'm making sense here. As it is the density of X~Y is useful for me. But I'm just wondering if I can add the information in Z into the density of X~Y. Perhaps you have alternative idea? Both the density of X~Y and Z are information that I want to convey. Currently I'm separating them into separate density X~Y, X~Z, Y~Z, and they're all useful to me (using my data of course). Edit2, Manual Calculation Plan: I'm still working on this as I go. This is a general idea of what I'm planning to do. * *Instead of using stat_density_2d, I plan to calculate the density itself using the method used in stat_density_2d, which is MASS::kde2d(). *I would then use interpolation such as akima::interp, to interpolate the Z into X~Y grid. *I would then multiply Z unto the density of X~Y (from 1) as a form of weightage. *Plot them again using ggplot. Edit 3: Update with code of applying Z as weightage towards density of X~Y. library(ggplot2) library(data.table) library(ggnewscale) library(akima) library(MASS) plot_data <- data.frame(X = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)), Y = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)), Z = c(rnorm(300, 60, 5), rnorm(150, 60, 5)), Label = c(rep('A', 300), rep('B', 150))) setDT(plot_data) #Interpolation of Z into X~Y grid for Label A int_plot_data_A=with(plot_data[Label=="A"],interp(x=X,y=Y,z=Z,nx=100,ny=100)) rownames(int_plot_data_A$z)=int_plot_data_A$x colnames(int_plot_data_A$z)=int_plot_data_A$y plot_data_Z_A <- melt(int_plot_data_A$z) names(plot_data_Z_A) <- c("X", "Y", "Z") #Calculation of kde2d for Label A plot_data_A=plot_data[Label=="A"] kde2d_A=kde2d(plot_data_A$X,plot_data_A$Y,n=100) rownames(kde2d_A$z)=kde2d_A$x colnames(kde2d_A$z)=kde2d_A$y plot_kde_A <- melt(kde2d_A$z, na.rm = TRUE) names(plot_kde_A) <- c("X", "Y", "Z") #Interpolation of Z into X~Y grid for Label B int_plot_data_B=with(plot_data[Label=="B"],interp(x=X,y=Y,z=Z,nx=100,ny=100)) rownames(int_plot_data_B$z)=int_plot_data_B$x colnames(int_plot_data_B$z)=int_plot_data_B$y plot_data_Z_B <- melt(int_plot_data_B$z) names(plot_data_Z_B) <- c("X", "Y", "Z") #Calculation of kde2d for Label B plot_data_B=plot_data[Label=="B"] kde2d_B=kde2d(plot_data_B$X,plot_data_B$Y,n=100) rownames(kde2d_B$z)=kde2d_B$x colnames(kde2d_B$z)=kde2d_B$y plot_kde_B <- melt(kde2d_B$z, na.rm = TRUE) names(plot_kde_B) <- c("X", "Y", "Z") #Filtering out values under 0.01. It makes the plot better. This is subjective setDT(plot_kde_A) plot_kde_A[Z<0.01]=NA setDT(plot_kde_B) plot_kde_B[Z<0.01]=NA #Calculate for A weighted with Z plot_kde_A_Weight_Z=plot_kde_A plot_kde_A_Weight_Z$Z=plot_kde_A_Weight_Z$Z*plot_data_Z_A$Z #Calculate for B weighted with Z plot_kde_B_Weight_Z=plot_kde_B plot_kde_B_Weight_Z$Z=plot_kde_B_Weight_Z$Z*plot_data_Z_B$Z ggplot() + geom_contour_fill(data=plot_kde_A,aes(x=X,y=Y,z=Z),alpha=0.8,bins=10) + scale_fill_continuous(low = "white", high = "blue") + geom_contour(data=plot_kde_A_Weight_Z,aes(x=X,y=Y,z=Z),bins=10) + new_scale_fill() + geom_contour_fill(data=plot_kde_B,aes(x=X,y=Y,z=Z),alpha=0.8,bins=10) + scale_fill_continuous(low = "white", high = "red") + geom_contour(data=plot_kde_B_Weight_Z,aes(x=X,y=Y,z=Z),color="red",bins=10) Edit 1: After searching around while dropping keyword ggplot, I found something called kernel density estimation And this post, Plot contours of distribution on all three axes in 3D plot, feels like this is what I'm looking for to visualise my data. Unfortunately, I found out that ggplot does not have 3D functionality. There's a 4 years package called gg3D? plotly seems to be the best candidate for this? The final figure in the post looks like what I'm trying to achieve.
{ "language": "en", "url": "https://stackoverflow.com/questions/71585680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to target specific Cucumber runner classes or feature files within Jenkins? Is it possible to target specific runner classes or feature files within Jenkins? Let's say for example I have the following files. Runner classes: RunnerClass1.java RunnerClass1.java Feature Files: Login.feature SignUp.feature Is there a way to trigger specific runner classes or feature files within the Jenkins UI, I know you can use specific plugins such as: 'Parameterised / String Parameters', has anyone else found a solution to target specific tests from Jenkins? thanks for your help A: You can tag your test cases and maven will be able to run them by these tags. For example, When I have Login cases with @Login tags and I want to run them with Maven, I am using the following terminal script : mvn clean test -Dcucumber.options="--tags @Login"
{ "language": "en", "url": "https://stackoverflow.com/questions/55302032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to revoke Users Access On Schema in Azure SQL? I have a requirement where I need to revoke users access on a particular schema as we will be purging that schema and its table in future. Currently, the process followed to create Schema and grant access is like below, * *Create Schema *Create DB Role *Create Azure AD Group on azure portal *Create DB User with the same name as AD group *Then, we run EXEC sp_addrolemember command to add DB user to DB role in database. *Finally, we run the Grant command to give permission (Select, Insert etc) on Schema to DB Role. Now, whenever any new user need access to that schema we simply add him in the Azure AD group and he is able to see and access that schema. However, when I Revoke the access of user by removing him from Azure AD group he is still able to see that Schema. As I am not an expert in SQL so I am not sure what am I missing in order to revoke his access. I also tried Revoke command like below but still the user is able to see the schema. REVOKE SELECT ON SCHEMA :: Schema_Name TO [DB Role] Am I missing anything, can anyone please let me know the right steps to revoke user access so that they should not be able to see that schema anymore or should not be able to run any command on that schema not even select command? A: Then, in addition to remove it from the AD group, try to deny permissions on the schema: DENY SELECT,VIEW DEFINITION On SCHEMA::Schema_Name To [user_name]
{ "language": "en", "url": "https://stackoverflow.com/questions/75029646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PopBackStack previous last fragment and check which fragment it is I got a few fragments in MainActivity which can be selected from Navigation Drawer. Now, whenever users press a profile button, it will jumps to UserProfile Fragment. If home button is pressed, it will pop back the last fragment. Since I've assigned each of the fragments a specific backstack name i.e .addToBackStack("abc"), how can I check what is the last fragment by using popBackStack() method ? A: To get the last fragment: FragmentManager fm = getSupportFragmentManager(); int lastFragEntry = fm.getBackStackEntryCount()-1; String lastFragTag = fm.getBackStackEntryAt(lastFragEntry).getName(); Log.i("Last Fragment Tag->", lastFragTag); NB: If you want to get the name/tag of last fragment, you also have to use the same Tag during fragment transaction: ft.replace(android.R.id.container, fragment, "abc"); ft.addToBackStack("abc"); Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/43032948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert mathematical expressions into C statement? How to convert each of the following mathematical expressions to its equivalent statement in C? * *1 / (x^2 + y^2) *square root of (b^2 - 4ac) A: * *1.0 / (pow(x,2) + pow(y,2)) *sqrt(pow(b,2) - 4*a*c) See pow() and sqrt() functions manual. You can also write x*x instead of pow(x, 2). Both will have the exact same result and performance (the compiler knows what the pow function does and how to optimize it). (For commenters) GCC outputs the exact same assembler code for both of these functions: double pow2_a(double x) { return pow(x, 2); } double pow2_b(double x) { return x * X; } Assembler: fldl 4(%esp) fmul %st(0), %st ret
{ "language": "en", "url": "https://stackoverflow.com/questions/7333101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Best way to join 3 lists and count how many times an ID is in the list using linq Looking for some help with this problem i'm trying to work through to learn how linq works. My thinking was to join the person and customer list on personID to get the name for the customers and then join the customer and sale lists on customerID and then count the customerID in sale to get the amount of sales by the customer that were from the online store. Task: Determine which people have placed the most orders from our online store public class Person { public int PersonID { get; set; } public string PersonType { get; set; } public bool NameStyle { get; set; } public string Title { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string Suffix { get; set; } } public class Sale { public int SalesOrderId { get; set; } public int RevisionNumber { get; set; } public DateTime OrderDate { get; set; } public DateTime DueDate { get; set; } public DateTime? ShipDate { get; set; } public bool IsOnlineOrder { get; set; } public int CustomerId { get; set; } public int? SalesPersonId { get; set; } public int? TerritoryID { get; set; } public decimal SubTotal { get; set; } public decimal TaxAmt { get; set; } public decimal Freight { get; set; } public decimal TotalDue { get; set; } } public class Customer { //CustomerID can belong to a store or a person public int CustomerID { get; set; } public int? StoreID { get; set; } public int? PersonID { get; set; } public int? TerritoryID { get; set; } public string AccountNumber { get; set; } } public void MostOrders() { List<Person> per = Data.GetAllPersons(); List<Sale> sale = Data.GetAllSales(); List<Customer> cus = Data.GetAllCustomers(); var join = (from x in per join y in cus on x.PersonID equals y.PersonID join t in sale on y.CustomerID equals t.CustomerId select new { ...... }); } A: I would create a class that will hold gather all "store entities" and their sales, i think that using a collection of this class (StoreEntity in my example) it will be much easier to perform a variety of data manipulation (for this task and in future tasks). here is my suggestion: public class StoreEntity { Person PersonEntity { get; set; } Customer CustomerEntity { get; set; } List<Sale> SalesList { get; set; } public StoreEntity(Person p, Customer c,List<Sale> sales) { this.PersonEntity = p; this.CustomerEntity = c; this.SalesList = sales; } public int SalesCount { get { if (SalesList == null) { return 0; } else { return SalesList.Count; } } } } public List<StoreEntity> Entities { get; set; } public void MostOrders() { List<Person> per = Data.GetAllPersons(); List<Sale> sale = Data.GetAllSales(); List<Customer> cus = Data.GetAllCustomers(); Entities = new List<StoreEntity>(); foreach (Person p in per) { var cust = cus.Where(x => x.PersonID == p.PersonID).Select(x => x).SingleOrDefault(); if (cust != null) { var sales = sale.Where(x => x.CustomerId == cust.CustomerID).ToList(); StoreEntity entity = new StoreEntity(p, cust, sales); Entities.Add(entity); } } // now you have list of all entities with their sales // it will be musch easy to manipulate with linq // you can do this: Entities = Entities.OrderBy(x => x.SalesCount).ToList(); // or this... var bestEntity = Entities.Max(x => x.SalesCount); }
{ "language": "en", "url": "https://stackoverflow.com/questions/51777803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL SELECT 3 consecutive records with the same value I want to select 3 consecutive (by year) records with same value from 'participation' table (name, year) : Name Year ------------- Carol 1999 Carol 2000 Carol 2001 Carol 2002 Faith 1996 John 2001 John 2002 John 2003 John 2009 Lyla 1994 Lyla 1996 Lyla 1997 Here is my initial code : SELECT DISTINCT p1.name, p1.year FROM participatition p1, participatition p2 WHERE (p1.year = p2.year + 1 OR p1.year = p2.year - 1) AND p1.name = p2.name ORDER BY p1.name, p1.year which returns ALL consecutive records but I only want records which meet 3 consecutive criteria, ie not Lyla: Name Year ------------- Carol 1999 Carol 2000 Carol 2001 Carol 2002 John 2001 John 2002 John 2003 Lyla 1996 Lyla 1997 Is it possible to build on my code, eg add an extra criterion, to refine the selection without implementing the row_number() method? I would like the following output: Name Carol John ie all records if there are at least 3 consecutive A: Consider it as a gaps-and-islands problem and use the following trick to group consecutive rows together: WITH cte1 AS ( SELECT *, Year - ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Year) AS grp FROM t ), cte2 AS ( SELECT *, COUNT(*) OVER (PARTITION BY Name, grp) AS grp_count FROM cte1 ) SELECT * FROM cte2 WHERE grp_count >= 3 ORDER BY Name, Year If you look at the values in grp column you will find the pattern. db<>fiddle A: If there are no duplicate years for each Name, you need LEAD() window function to check for the 2nd next row. If the year in that row is equal to the current year + 2 then this means that for this Name there are 3 consecutive years: WITH cte AS ( SELECT *, LEAD(Year, 2) OVER (PARTITION BY Name ORDER BY Year) next_next FROM participatition ) SELECT DISTINCT p.* FROM participatition p INNER JOIN cte c ON p.Name = c.Name AND p.Year BETWEEN c.Year AND c.next_next WHERE c.next_next = c.Year + 2; See the demo. A: I would simply use lead(): select distinct name from (select p.*, lead(year, 2) over (partition by name order by year) as year_2 from participation p ) p where year_2 = year + 2; For each row, this looks at the row two ahead for the same name ordered by year. If that row is the current year plus 2, then you have three years in a row. A: There may be a more elegant way. But, well, this is what I've come up with: select name, year from ( select name, year, case when lag(year, 2) over (partition by name order by year) = year - 2 then 1 else 0 end + case when lag(year, 1) over (partition by name order by year) = year - 1 then 1 else 0 end + case when lead(year, 1) over (partition by name order by year) = year + 1 then 1 else 0 end + case when lead(year, 2) over (partition by name order by year) = year + 2 then 1 else 0 end + 1 as consecutive_rows from participatition ) analyzed where consecutive_rows >= 3 order by name, year; If the table participatition can contain multiple rows for one name and year, add DISTINCT to the subquery (aka derived table). A: WITH CTE AS ( SELECT name , year-lag(year,2) OVER(PARTITION BY name ORDER BY year ASC) as two_years_ago FROM t ) SELECT name, two_years_ago FROM cte WHERE two_years_ago=2 A: You can solve this using row pattern matching if you're using Oracle Database: with rws as ( select 'Carol' nm, 1999 yr from dual union all select 'Carol' nm, 2000 yr from dual union all select 'Carol' nm, 2001 yr from dual union all select 'Carol' nm, 2002 yr from dual union all select 'Faith' nm, 1996 yr from dual union all select 'John' nm, 2001 yr from dual union all select 'John' nm, 2002 yr from dual union all select 'John' nm, 2003 yr from dual union all select 'John' nm, 2009 yr from dual union all select 'Lyla' nm, 1994 yr from dual union all select 'Lyla' nm, 1996 yr from dual union all select 'Lyla' nm, 1997 yr from dual ) select * from rws match_recognize ( partition by nm order by yr all rows per match pattern ( init cons{2} ) define cons as yr = prev ( yr ) + 1 ); NM YR Carol 1999 Carol 2000 Carol 2001 John 2001 John 2002 John 2003 A: Adding to my initial code Group By and Having clause as below builds on the existing code (which filtered all consecutive name, year) : SELECT DISTINCT p1.name FROM participatition p1, participatition p2 WHERE (p1.year = p2.year+1 OR p1.year = p2.year-1) AND p1.name = p2.name GROUP BY p1.name HAVING COUNT(p1.name) > 2 ORDER BY p1.name, p1.year Thanks for all the answers - I never realised there was so many alternative solutions which has opened my eyes. A: I have updated my code based on feedback (distinct, inner join, etc) from @ThorstenKettner using PSQL this time SELECT p1.name FROM participation p1 JOIN participation p2 ON p1.name = p2.name WHERE (p1.year = p2.year+1 OR p1.year = p2.year-1) GROUP BY p1.name HAVING COUNT(p1.name) > 2 ORDER BY p1.name This seems to work fine, is easy to understand and less complex. However I would like to test all solutions so I may apply such instead to suit new requirements. So thank you all for your generous help. Esp. Danke TK!
{ "language": "en", "url": "https://stackoverflow.com/questions/68998986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cython: Compiling and Cannot Find Library Mac OSX 10.12 I am just getting started with Cython and am trying to compile a "Hello World" script. I am trying to use gcc -Os /User/Documents/Python/Test\ Python/helloCopy.c -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -l, but I don't know what to add after the -l. Other forum pages say to "include -lpython2.7 (or whatever version of Python you're using) on the linker command-line" but that produces ld: library not found for -lpython3.5 clang: error: linker command failed with exit code 1 (use -v to see invocation) Should I be directing the -l to a particular folder? A: I do not know what resource you're using, but this does not say anything about a -l flag. It suggests cython -a helloCopy.pyx This creates a yourmod.c file, and the -a switch produces an annotated html file of the source code. Pass the -h flag for a complete list of supported flags. gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o helloCopy.so helloCopy.c (Linux) On macOS I would try to compile with gcc -I/usr/bin/python -o helloCopy.so helloCopy.c to use the standard version of Python.
{ "language": "en", "url": "https://stackoverflow.com/questions/43055967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: plotly layout - Y Axis range not working i am trying to create a graph that will show a Scatter of the times i opened my computer. - i am using plotly offline. Y = time, X = date. this works fine, but i can't make the Y axis to show all the hours of the day, but only the range of times that was in the data. (for example, if i opened my computer only between 13:00-15:00 every day, the range of the Y axis will be from 13:00 to 15:00 only) i am trying to show all the hours of the day on the Y axis by using the 'range' attribute in the layout, but it still doesn't work for me. an example of my code: from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot from plotly.graph_objs import * from datetime import datetime, time init_notebook_mode(connected=True) # in the example i am using fabricated data. declaring the data: time_data = [datetime(2017, 07, 28, 21, 37, 19), datetime(2017, 07, 29, 17, 11, 56), datetime(2017, 08, 01, 11, 15, 45), datetime(2017, 08, 02, 13, 54, 03)] x_data = [] y_data = [] # creating the x-row data with dates only, and the y-row data with the time only for row in time_data: x_data.append(row.date()) y_data.append(datetime.combine(datetime(2017, 1, 1).date(), row.time)) #declaring the data for the graph data = [Scatter(x=x_data, y=y_data, name='Times On', mode='markers')] # creating the hour range hours = [] for i in range (0, 24): hours.append(datetime(2017, 1, 1, i, 0, 0)) # declaring the Layout with the 'range' attribute, and Figure layout = dict(title='Times On', xaxis=dict(type='date'), yaxis={'type': 'date', 'tickformat': '%H:%M', 'range': hours}) fig = Figure(data=data, layout=layout) # plotting plot(figure_or_data=fig, filename='C:\Users\tototo\Desktop\Time-On') does someone know what's the problem? any help would be blessed! Thanks! A: plotly seems to limit the axis based on the max and min values present in the corresponding axis. I tried each of the properties and came up with a solution. Approach: The first one is generating what you need, but cant seem to get it to start at 12 in the midnight and end at 12 the next day. from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot from plotly.graph_objs import * from datetime import datetime, time init_notebook_mode(connected=True) # in the example i am using fabricated data. declaring the data: time_data = [datetime(2017, 7, 28, 21, 37, 19), datetime(2017, 7, 29, 17, 11, 56), datetime(2017,8, 1, 11, 15, 45), datetime(2017, 8, 2, 13, 54, 3)] x_data = [] y_data = [] # creating the x-row data with dates only, and the y-row data with the time only for row in time_data: x_data.append(row.date()) y_data.append(str(datetime.combine(datetime(2017, 1, 1).date(), row.time()))) #declaring the data for the graph data = [Scatter(x=x_data, y=y_data, name='Times On', mode='markers')] # creating the hour range hours = [] for i in range (0, 24): hours.append(datetime(2017, 1, 1, i, 0, 0)) # declaring the Layout with the 'range' attribute, and Figure layout = dict(title='Times On', xaxis=dict(type='date'), yaxis={'type': 'date', 'tickformat': '%H:%M', 'nticks': 30, 'tick0': hours[0], 'range': [hours[0], hours[len(hours)-1]], 'autorange': False}) fig = Figure(data=data, layout=layout) # plotting iplot(figure_or_data=fig) The above code is giving me the output:
{ "language": "en", "url": "https://stackoverflow.com/questions/45577341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to replace the first column of a tab delimited file 690070 690070 A 690451 690451 B 690571 690571 C 690578 690578 D 690637 690637 F How can I replace the first column values with a sequential number, starting from 1...n. So it becomes: 1 690070 A 2 690451 B 3 690571 C 4 690578 D 5 690637 F Can this be done in Vim or some linux command? A: You can use awk or vim macro. awk is really great for such text manipulation awk '{count++; print count " " $2 " "$3;}' data.stat > /tmp/data.stat && mv /tmp/data.stat data.stat A: in Vim: :let i=1 | g/^[^/\t]*\t/s//\= i. "\t"/ | let i=i+1 Reference Update For splitting the first two columns and saving into another file, I recommend using awk as in Tomáš Šíma's answer, specifically: awk '{print $1 "\t" $2;}' data.stat > newfilename.txt If you want to to do everything in Vim: * *Copy the current file to a new one :w newfilename.txt * *Open the newly copied file: :o newfilename.txt * *Split the first two columns of the rest of the line: :%s/^\([^\t]*\)\t\([^\t]*\).*$/\1\t\2/g * *Save your edits of course :w newfilename.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/36268060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTTP 302 "Moved Temporarily" Error While we are getting latest project from TFS2013, we are facing below error. PS: We are using proxy in our network. Thank you in advance A: I faced with the same problem before and when I add my ip adress to proxy then try again to do Get latest in TFS. Its worked!!!. Have a nice coding :)
{ "language": "en", "url": "https://stackoverflow.com/questions/40233546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Account and Physical Thermostat I signed up for a developer account using the same account that I have my home thermostat on. I'm getting an error in the Home Simulator saying that a mix of physical and virtual devices is dangerous. Do I have to create a separate account to be my developer account or can I just remove my physical thermostat from the Home Simulator? I don't want to remove my thermostat from my account though since I use that to manage my thermostat. A: Yes, it is a good idea to create a separate account. Quote from https://developer.nest.com/documentation/cloud/home-simulator "This Home Simulator is intended to be used with virtual devices for testing purposes. We strongly suggest that you create a separate account for testing and add virtual devices to it via the Home Simulator."
{ "language": "en", "url": "https://stackoverflow.com/questions/32783150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to use the letter keys to access programs on Windows 8.1 Metro, like in XP? For those who remember (or still use) Windows XP, you might remember that you could launch the start bar with your Windows key on your keyboard and then hit the letter of the program/folder/file you wanted and as long as there wasn't another program/folder/file on the start bar starting with the same letter, it'd launch right away. e.g. If you wanted to open excel, you'd hit the windows key and press the letter "e" and excel would launch. So, for those who do remember that feature, I'm wondering, is there any way to get that functionality back in Windows 8.1? Right now, what happens is that when you hit the windows key, Metro pops up (which is fine) but if you type "e", for example, windows will automatically start searching instead of just launching Excel (or whatever letter you've typed). I'd rather keep the interface as it is and, if possible, prefer not to install any 3rd party software (unless there's no other go). My preference is to be able to utilize the OS to get that option (if available), even if that includes going through regedit. Just a note, I am already aware that 8.1 and XP are completely different architectures and I also realize that automatic searching does have its benefits but I prefer that specific XP functionality so it'd be great if I could get it back in 8.1. Thanks in advance for your help. A: This isn't the exact thing that I'm looking for but I've found somewhat of a workaround. You can create global keyboard shortcuts and thereby circumvent the metro/start screen altogether. To do so, create a shortcut of the program/folder/file you want to easily access (the shortcut can be placed anywhere). Then, go to the properties of the shortcut and go to the shortcut tab where you can enter a global shortcut key (about half way down the box). Of course, there are limitations to this because there are only a few keys (key combinations) free that you can use globally whereas with the XP method I was looking for, you could essentially have up to 36 different items you can access with just two keystrokes (26 letters, 10 numbers - not sure if other characters worked). If anyone has figured out the XP method, though, that would be great.
{ "language": "en", "url": "https://stackoverflow.com/questions/32576332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get all records that do not have an empty field Posts have many Comments. Each Comment optionally belongs to a User. How can I get all comments for Post 1 that HAVE a user? Comments content post_id user_id ------- ------- ------- There is no user for this post. 1 This is an example with a user. 1 123 Another example with a user. 1 8321 Things I've tried: This returns no records @comments = Post.find(1).comments.where(:user_id != nil) These return every record: @comments = Post.find(1).comments.where("user_id IS NOT NULL") @comments = Post.find(1).comments.where("user_id <> 0") When I print out the user_ids on the page, it looks like the nil ones are being read as "0", but are still null in the db. A: It looks you have blank user_id column when comments doesn't have user. So the correct query should be @post = Post.find(1) @comments = @post.comments.where("user_id != ''") A: I'd do this: #app/models/post.rb class Post < ActiveRecord::Base has_many :comments do def no_user where.not(user_id: "") #-> http://robots.thoughtbot.com/activerecords-wherenot end end end #app/models/comment.rb class Comment < ActiveRecord::Base belongs_to :post end This will allow me to call: #app/controllers/comments_controller.rb class CommentsController < ApplicationController def show @post = Post.find params[:post_id] @comments = @post.comments.no_user end end -- Notes on Null Having null is a specific data-type in your database We use it when wanting to "default" populate a table's columns - allowing you to submit no data, having the database be as efficient as possible in providing the right allocations of data. I would certainly look up about the NULL data type with the likes of MYSQL & PGSQL. This will give you the ability to define any unpopulated data columns as NULL - allowing you to call the NOT NULL command. Currently, your "non defined" data is just blank - not null A: My code might not represent a standard way but it would work in both cases(Null and blank). @post = Post.find(1) @comments = @post.comments.where("user_id > 0")
{ "language": "en", "url": "https://stackoverflow.com/questions/25580035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to use a PCF spring cloud config server from a client outside the PCF? We have a few spring-boot micro-services running on PCF for which we have the PCF cloud config server for serving the configurations for various profile/environments. These micro-services are bound to the config server and all are managed by the PCF infrastructure. We have a few services running on Virtual Machines which are not managed by PCF. Is it possible to serve the resources from the same PCF config server to the services running on the VM which is not managed by PCF? A: Atlast, this is what I had to do to connect an external service from VM to connect to the PCF managed Config Server. When the profile property was not set to 'dev' in the bootstrap.yml, the profile was set to 'default' which triggered a login prompt even though I had a relaxed security config in place. I still don't know if this is a best practice. But, once I set the profile property as 'dev', I was able to consume the resouces seamlessly.
{ "language": "en", "url": "https://stackoverflow.com/questions/54923497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android's InputMethodService keyEventCode won't work I'm trying to create my keyboard, and now am at the place when the pressed button should send the letter to the application. In the examples I found InputMethodService.sendDownUpKeyEvents(keyEventCode); But couldn't really figure out, what should go into keyEventCode? For example, how do I send a letter "A" ? edit: Just one more thing, here ( http://developer.android.com/reference/android/view/KeyEvent.html ) I can find only codes for english character. How do I get other unicode characters? Thanks! A: That function takes the constants from the KeyEvent class. To send a, use sendDownUpKeyEvents(KeyEvent.KEYCODE_A);
{ "language": "en", "url": "https://stackoverflow.com/questions/7255924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The instance member "..."' can't be accessed in an initializer I am trying to create a simple flutter project for learning. I need to delete the selected student -Photo- but at the beginning I assigned the StudentList private so setState() function is not working when I try to delete. How can I assign StudentList as global. This is the code I wrote at the beginning: class _MyAppState extends State<MyApp> { StudentManager ChoosedStudent = new StudentManager.WithId(0, "", "", 0, ""); StudentManager student1 = new StudentManager.WithId(1, "Name1", "LastName1", 22, "https://uifaces.co/our-content/donated/hvaUVob5.jpg"); StudentManager student2 = new StudentManager.WithId(2, "Name2", "LastName2", 70, "https://uifaces.co/our-content/donated/eqUZLcBO.jpg"); StudentManager student3 = new StudentManager.WithId(3, "Name3", "LastName3", 55, "https://uifaces.co/our-content/donated/-oe25tWA.png"); StudentManager student4 = new StudentManager.WithId( 4, "Name4", "LastName4", 99, "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg"); StudentManager student5 = new StudentManager.WithId( 5, "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image"); @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("Student Exam Result System"), ), body: bodyBuilder(context), ); } bodyBuilder(BuildContext context) { List<StudentManager> StudentList = [ student1, student2, student3, student4, student5 ]; return Column( children: [ Expanded( child: ListView.builder( itemCount: StudentList.length, itemBuilder: (BuildContext context, int index) { if (StudentList[index].Grade >= 50) { StudentList[index].IsPassed = true; } else if (StudentList[index].Grade < 50) { StudentList[index].IsPassed = false; } return ListTile( leading: CircleAvatar( backgroundImage: NetworkImage(StudentList[index].PhotoURL), ), title: Text(StudentList[index].Name + " " + StudentList[index].Surname), subtitle: Text( "${StudentList[index].Name} named students grade is " "${StudentList[index].Grade}, ${StudentList[index].AlphebaticalGrade}"), isThreeLine: true, trailing: buildStatusIcon(StudentList[index].IsPassed), onTap: () { setState(() { ChoosedStudent = StudentList[index]; }); }, ); })), I want to assign StudentList like this: class _MyAppState extends State<MyApp> { StudentManager ChoosedStudent = new StudentManager.WithId(0, "", "", 0, ""); StudentManager student1 = new StudentManager.WithId(1, "Name1", "LastName1", 22, "https://uifaces.co/our-content/donated/hvaUVob5.jpg"); StudentManager student2 = new StudentManager.WithId(2, "Name2", "LastName2", 70, "https://uifaces.co/our-content/donated/eqUZLcBO.jpg"); StudentManager student3 = new StudentManager.WithId(3, "Name3", "LastName3", 55, "https://uifaces.co/our-content/donated/-oe25tWA.png"); StudentManager student4 = new StudentManager.WithId( 4, "Name4", "LastName4", 99, "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg"); StudentManager student5 = new StudentManager.WithId( 5, "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image"); List<StudentManager> StudentList = [ student1, student2, student3, student4, student5 ]; but this is throwing "The instance member "..."' can't be accessed in an initializer." Error. is there any other way to assign StudentList globally and what is the reason of the error? Full version of the code if it's neccesary: import 'dart:ffi'; import 'package:by_myself/models/students.dart'; import 'package:flutter/material.dart'; void main() { runApp(MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { StudentManager ChoosedStudent = new StudentManager.WithId(0, "", "", 0, ""); StudentManager student1 = new StudentManager.WithId(1, "Name1", "LastName1", 22, "https://uifaces.co/our-content/donated/hvaUVob5.jpg"); StudentManager student2 = new StudentManager.WithId(2, "Name2", "LastName2", 70, "https://uifaces.co/our-content/donated/eqUZLcBO.jpg"); StudentManager student3 = new StudentManager.WithId(3, "Name3", "LastName3", 55, "https://uifaces.co/our-content/donated/-oe25tWA.png"); StudentManager student4 = new StudentManager.WithId( 4, "Name4", "LastName4", 99, "https://images.generated.photos/ukvWCGJJF8xoZ_rvVSFDLnQ-WDkGw2WsZ53uPPm63M8/rs:fit:512:512/Z3M6Ly9nZW5lcmF0/ZWQtcGhvdG9zLzA3/OTI0MTAuanBn.jpg"); StudentManager student5 = new StudentManager.WithId( 5, "Name5", "LastName5", 45, "https://thispersondoesnotexist.com/image"); @override Widget build(BuildContext context) { // TODO: implement build return Scaffold( appBar: AppBar( title: Text("Student Exam Result System"), ), body: bodyBuilder(context), ); } bodyBuilder(BuildContext context) { List<StudentManager> StudentList = [ student1, student2, student3, student4, student5 ]; return Column( children: [ Expanded( child: ListView.builder( itemCount: StudentList.length, itemBuilder: (BuildContext context, int index) { if (StudentList[index].Grade >= 50) { StudentList[index].IsPassed = true; } else if (StudentList[index].Grade < 50) { StudentList[index].IsPassed = false; } return ListTile( leading: CircleAvatar( backgroundImage: NetworkImage(StudentList[index].PhotoURL), ), title: Text(StudentList[index].Name + " " + StudentList[index].Surname), subtitle: Text( "${StudentList[index].Name} named students grade is " "${StudentList[index].Grade}, ${StudentList[index].AlphebaticalGrade}"), isThreeLine: true, trailing: buildStatusIcon(StudentList[index].IsPassed), onTap: () { setState(() { ChoosedStudent = StudentList[index]; }); }, ); })), Text("Student: " + ChoosedStudent.Name), Center( child: Row( children: [ Flexible( fit: FlexFit.tight, flex: 1, child: RaisedButton( onPressed: () {}, color: Colors.blueAccent, textColor: Colors.white, child: Row( children: [ SizedBox( width: 16.0, ), Icon(Icons.add), Text("Add"), ], ), ), ), Flexible( fit: FlexFit.tight, flex: 1, child: RaisedButton( onPressed: () {}, color: Colors.blueAccent, textColor: Colors.white, child: Row( children: [ SizedBox( width: 16.0, ), Icon(Icons.update), Text("Update"), ], ), ), ), //KAY Flexible( fit: FlexFit.tight, flex: 1, child: RaisedButton( onPressed: () { setState(() { StudentList.remove(ChoosedStudent); print(StudentList); }); }, color: Colors.blueAccent, textColor: Colors.white, child: Row( children: [ SizedBox( width: 16.0, ), Icon(Icons.delete), Text("Delete"), ], ), ), ), ], ), ), ], ); } } Widget buildStatusIcon(bool IsPassed) { if (IsPassed == true) { return Icon(Icons.done); } else if (IsPassed == false) { return Icon(Icons.warning); } else { return Icon(Icons.error); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65817790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android activity without graphic From the BroadcastReceiver I want to call a activity without graphic. Without graphic because it will speak some words. Intent iSpeechIntent = new Intent(context, TTS.class); iSpeechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(iSpeechIntent); but activity cycle is not finished correctly. onDestroy() method is never executed. Why? @Override public void onDestroy() { // Don't forget to shutdown! if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } And is OK if i am using activity without graphic XML just for speak some text with TTSEngine? A: You misunderstood Activity lifecycle. onDestroy() is NOT called when your activity is dismissed. And dismissing it (i.e. by starting another activity) does NOT equal destroying activity (however you may enforce destroy of activity, by calling finish() - and then your onDestroy() method will be invoked). You may want to move your code to onPause() and onResume() respectively or maybe you shall use IntentService instead, if you dot require any UI for the task. A: I propose to use Android Service for such kind of tasks http://developer.android.com/reference/android/app/Service.html .
{ "language": "en", "url": "https://stackoverflow.com/questions/12307647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Screen going behind bottom material tab bar Hi am working on screens which involves bottom tab bar. For that I have implemented material bottom tab bar from react-navigation-material-bottom-tabs. Problem is my screen is going behind the bottom tab like below The yellow border was given to see how UI would look like. The bottomline of screen is expected to be just above the bottom bar not behind it. <SafeAreaView style={{backgroundColor: '#f3f3f5'}}> <View style={{ borderWidth: 3, borderColor: 'yellow', width: width, height: height, flexDirection: 'column-reverse', }}> <Header data={headerData} /> <LabelledView rectanglebarfunc={() => this.rectanglebarfunc()} height={height * 0.07} rectanglebarbuttontext={'List Item 01'} width={width} color="white" icolor="#ff007C" textColr="#120F3F" fontSize={16} rectanglebarfunc={() => {}} /> <View style={{ width: '100%', height: 0.5, backgroundColor: 'transparent', }} /> <LabelledView rectanglebarfunc={() => this.rectanglebarfunc()} height={height * 0.07} rectanglebarbuttontext={'List Item 00'} width={width} color="white" icolor="#ff007C" textColr="#120F3F" fontSize={16} rectanglebarfunc={() => {}} /> {/* <View style={{ width: '90%', height: '70%', backgroundColor: 'red', alignSelf: 'center', marginVertical: 5, }}></View> */} </View> </SafeAreaView> A: Try adding marginBottom to safeAreaView and View : <SafeAreaView style={{backgroundColor: '#f3f3f5' ,marginBottom:100}}> <View style={{ borderWidth: 3, borderColor: 'yellow', width: width, height: height, flexDirection: 'column-reverse', marginBottom:100 }}> try adjusting your marginBottom to check Hope it helps. feel free for doubts
{ "language": "en", "url": "https://stackoverflow.com/questions/59948572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using IntentFilter I am trying to use IntentFilter with Brodcastreciver, but text not updates. I want to update text every time when time changes. Better if when day changes, but I dont know how to do this. Can you help me please to do it right? @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FadingActionBarHelper helper = new FadingActionBarHelper() .actionBarBackground(R.drawable.ab_background) .headerLayout(R.layout.header) .contentLayout(R.layout.activity_main); setContentView(helper.createView(this)); initCard(); initHeader(); helper.initActionBar(this); IntentFilter s_intentFilter = new IntentFilter(); s_intentFilter.addAction(Intent.ACTION_TIME_TICK); s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED); s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED); registerReceiver(m_timeChangedReceiver, s_intentFilter); initHeader(); } private void initHeader() { TextView title = (TextView)(findViewById(R.id.title)); final TextView subtitle = (TextView)(findViewById(R.id.subtitle)); SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy.HHmmss"); final String currentDateandTime = sdf.format(new Date()); subtitle.setText(currentDateandTime); } private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(Intent.ACTION_TIME_CHANGED) || action.equals(Intent.ACTION_TIMEZONE_CHANGED)|| action.equals(Intent.ACTION_TIME_TICK)) { initHeader(); } } }; Update: Time changes. Sorry) Actually it is chnges every minute
{ "language": "en", "url": "https://stackoverflow.com/questions/24430077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix 'Unexpected identifier' in JavaScript I am writing code for a calculator and I got an error 'Unexpected Identifier' and I don't know what's wrong. The line of code is alert("Welcome to the multiplication website!"). I have no idea what's wrong. <head> <title>Multiplication Table</title> <script type="text/javascript"> alert("Welcome to the multiplication website!") var rows = prompt("What is your first number?") var cols = prompt("What is your second number?") output = rows * cols if rows isNaN() then output = Error: Not a Number document.write(output); </script> </head> <body> </body> </html> I expected it to not have errors, then there were errors. A: You have a little code that looks like pseudoxode - try this: if (isNaN(rows)) alert("Error: Not a Number");
{ "language": "en", "url": "https://stackoverflow.com/questions/55989989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Ionic native using ionic/angular 1 I'm currently working on a project in ionic/angular 1. I'm using ionic native to wrap the cordova plugins. I installed ionic native with bower, and added dependency to 'ionic.native' in my app's angular module. Now I can inject stuff like $cordovaFile into my controllers and use them. This works great. My problem is using the MediaPlugin. I inject $cordovaMediaPlugin in my controller. Now the documentation ( https://ionicframework.com/docs/v2/native/mediaplugin/ ) says do this: new MediaPlugin('path/to/file.mp3', onStatusUpdate); Obviously i cant do this in angular1. I tried stuff like this: var media = this.$cordovaMediaPlugin('PATH'); var media = new this.$cordovaMediaPlugin('patch'); nothing seems to work, getting undefined all the time. How would I make this calls in angular/ionic 1? I really think the 'new' keyword is the issue here... A: Try to install ngCordova Media plugin. Install ngCordova, and inject in your app module 'ngCordova'. * *See de following steps *Install plugin *If you want create a service to provide a media resources see (Not required)
{ "language": "en", "url": "https://stackoverflow.com/questions/42270930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Pattern matching from mochiweb xpath I am trying to pattern match these values which are returned by running mochixpath. The pattern is clearly [elemName, htmlAttrs, children], but what I really need from the following values is UserNameA and "This is a message" [{"tr", [{"bgcolor", "White"}], [{"td", [{"class", "Topic"}], [{"div", [], [{"a", [{"class", "lnkUserName"}, {"href", "/users/prof.aspx?u=27149"}], ["UserNameA"] }] }]}, {"img", [{"alt", ""}, {"src", "/Images/Icons/userIcon.gif"}], []}, {"td", [{"class", "bHeader"}], [{"div", [{"style", "float:left;width:77%;"}],[ {"a", [{"class", "PostDisplay"}], ["This is a message"]}] }] }] Essentially I'm using the parsed xml from the output of the xpath to get the username and the message they sent. I am very new to elixir and the concept of pattern matching so any help is greatly appreciated. A: Something is wrong with the output, because it spits syntax error, when I copy it to console, so I'll assume that you have tr, with td, img and other td inside. Pattern matching can be used for unwrapping this way. Lets say, you have your whole data in variable Data, you can extract the contents with: [TR] = Data, {_Name, _Attrs, Contents} = TR. Now Contents is again a list of nodes: [Td1, Img, Td2], so you can do: [Td1, Img, Td2] = Contents. And so on, until you actually reach your contents. But writing that is pretty tedious and you can use recursion instead. Lets define contents function, that recursively scans the elements. contents({_Name, _Attrs, Contents}) -> case Contents of [] -> []; % no contents like in img tag [H | T] -> case is_tuple(H) of % tupe means list of children true -> lists:map(fun contents/1, [H | T]); % otherwise this must be a string _ -> [H | T] end end. This will return nested list, but you can at the end run lists:flatten like this: Values = lists:flatten(contents(Data)). A: The curly and square brackets are not balanced in your example. I guess it is missing a }] at the end. It seems that the deepness of the expression may vary, so you have to explore it recursively. The code belows does it, assuming that you will find the information in type "a" elements: -module (ext). -compile([export_all]). extL(L) -> extL(L,[]). extL([],R) -> R; extL([H|Q],R) -> extL(Q, extT(H) ++ R). extT({"a",PropL,L}) -> case proplists:get_value("class",PropL) of "lnkUserName" -> [{user_name, hd(L)}]; "PostDisplay" -> [{post_display,hd(L)}]; _ -> extL(L,[]) end; extT({_,_,L}) -> extL(L,[]). with your example it returns the proplist [{post_display,"This is a message"},{user_name,"UserNameA"}]
{ "language": "en", "url": "https://stackoverflow.com/questions/26396198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vue.js routes does not work using router-link i make a project using vue js. in the nav bar i put menu home and about which is will go direct to each page when it's clicked. there is no error when i run the project but the router doesn't work when i clicked the menu. main.js import { createApp } from 'vue' import App from './App.vue' import router from './routes' import './assets/main.css' createApp(App).use(router).mount('#app') routes.js import { createWebHistory, createRouter } from "vue-router"; import Home from '@/components/Home.vue'; import AboutMe from '@/components/AboutMe.vue'; const routes = [ { name: 'Home', path: '/', component: Home }, { name: 'AboutMe', path: '/aboutme', component: AboutMe } ] const router = createRouter({ history: createWebHistory(), routes }) export default router; app.vue <div class="container header-item" id="app"> <img src="./assets/Logo.svg" alt="Logo"> <div class="nav"> <router-link to="/" class="nav-item">HOME</router-link> <router-link to="/aboutme" class="nav-item">ABOUT ME</router-link> </div> </div> A: You missed to add <router-view/> add it on your app.vue file after the nav section. Example: <div class="nav"> <router-link to="/" class="nav-item">HOME</router-link> <router-link to="/aboutme" class="nav-item">ABOUT ME</router-link> </div> <router-view/>
{ "language": "en", "url": "https://stackoverflow.com/questions/74768064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to return range or location of cursor in TinyMCE when clicked or cursor location changed? how can I get the location of the cursor when the TinyMCE editor is focused on or when cursor location changes? Thanks. A: Use the tinymce onActivate event in case of focus. A cursor location change is possible, but it is expensive to detect, because you will have to check on each key-action if the cursor is still on the previous spot or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/13397678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replacing "foreach" with "for" in PHP I need to replace my "foreach" with "for", but actually I don't know how. Here is the part of my php code: $r = ""; $j = 0; foreach ($orgs as $k => $v) { echo "\n\r" . $v->id . "\n\r"; if (1) { $a_view_modl = ArticleView :: model($v->id, $v->id); $connection = $a_view_modl->getDbConnection(); Thanks! A: $r = ""; $j = 0; foreach ($orgs as $k => $v) { echo "\n\r" . $v->id . "\n\r"; if (1) { //you don't really need this, because it's allways true $a_view_modl = ArticleView :: model($v->id, $v->id); $connection = $a_view_modl->getDbConnection(); if $orgs is an associative array, it becomes: $r = ""; $j = 0; for($i = 0; $i < count($orgs); $i++) { echo "\n\r" . $orgs[$i]->id . "\n\r"; $a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id); $connection = $a_view_modl->getDbConnection(); } better you do some checks first if you go for this solution. if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal: $i++; //if you want the increment afterwards ++$i; //if you want the increment before you read your variable the same for decrements: $i--; //decrement after reading the variable --$i; //decrement before you read the variable A: A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v. Then $v has the value you are using in the snippet of code. A for loop does only accept indexed arrays, and no associative arrays. We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0. $r = ""; $j = 0; for ($i = 0; $i < count($orgs); $i++) { echo "\n\r" . $orgs[$i]->id . "\n\r"; if (1) { $a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id); $connection = $a_view_modl->getDbConnection(); A: $r = ""; $j = 0; for($i = 0 ; $i < count($orgs); $i++) { $v = $orgs[$i]; echo "\n\r" . $v->id . "\n\r"; if (1) { $a_view_modl = ArticleView :: model($v->id, $v->id); $connection = $a_view_modl->getDbConnection(); } A: foreach ($orgs as $k => $v) { // Your stuff } for loop for ($i = 0; $i < count($orgs); $i++) { // Your stuff ... use $orgs[$i]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/27127097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Decrease top menu so it does not stick out on carousel I have made this website here: http://dijon-egg.com/Possum/ If you click on green big dot button, it takes you to page2. My problem is I can't figure and fix the menu being too big on page 2 or change view of carousel on page 2 so full carousel can show to us. A: As I looked at your source code, I guess you should somehow add the .cbp-af-header-shrink class back to the header, when you click the green button.
{ "language": "en", "url": "https://stackoverflow.com/questions/41201820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a template dashbord in tableu? I have a Dashboard in tableau that I want to replicate it with another database that has the same columns/pills! is it possible to do that? A: The best way would be to open the "template dashboard", add the new data source, then go to menu DATA => Replace data source and change the old data source to the new data source. At this point close the old data source. The fastest way, but this might not work, is to open the .twb file of the dashboard with Notepad and replace the old database name with the new one...of course something could be broke. If you have a .twbx file you can open it with WinZip, WinRar, ... and find the .twb file inside. A: Possibly you could try 2 Options: * *Take a copy of your template. In the Data Source tab, go to Connections -> Edit Connection to point it to the new data source. *In the template, create a new data source. Replace the Old data source with the new one by Data -> Replace Data Source. For the formulas and filters to reflect on the new data source, make sure the field names and data types are the same as the old data source. Kindly note: Editing the XML is unsupported by Tableau! Create a copy of your original workbook before attempting any XML editing, as this could potentially corrupt your workbook.
{ "language": "en", "url": "https://stackoverflow.com/questions/68767244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: translationY doesn't change bounds I'm trying to create a flexible toolbar using the ObservableScroll library following the code that he wrote, only that I want to use a RecyclerView instead of a ScrollView. here's the layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:elevation="4dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize"/> <View android:id="@+id/vFlexible" android:layout_width="match_parent" android:layout_height="0dp" android:background="?attr/colorPrimary" /> </LinearLayout> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="16dp" android:paddingLeft="72dp" android:ellipsize="end" android:maxLines="1" android:layout_gravity="start" android:minHeight="?attr/actionBarSize" android:textColor="@android:color/white" android:textSize="20sp" android:text="test"/> </FrameLayout> <com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/rv" /> and here's the code: package test.itayrabin.toolbartest; import android.content.res.TypedArray; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView; import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks; import com.github.ksoichiro.android.observablescrollview.ScrollState; public class MainActivity extends ActionBarActivity implements ObservableScrollViewCallbacks { private View vFlexibleSize; private Toolbar mToolbar; private TextView tvTitle; private int flexibleSize; public static final String TAG = "FlexibleTest"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); tvTitle = (TextView) findViewById(R.id.title); tvTitle.setText(getTitle()); setTitle(null); final ObservableRecyclerView recyclerView = (ObservableRecyclerView) findViewById(R.id.rv); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new Adapter(this)); recyclerView.setScrollViewCallbacks(this); flexibleSize = getResources().getDimensionPixelSize(R.dimen.flexible_space_height); int flexibleAndToolbar = flexibleSize + getActionBarSize(); vFlexibleSize = findViewById(R.id.vFlexible); vFlexibleSize.getLayoutParams().height = flexibleAndToolbar; //recyclerView.setPadding(0,flexibleAndToolbar,0,0); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) { update(scrollY); } @Override public void onDownMotionEvent() {} @Override public void onUpOrCancelMotionEvent(ScrollState scrollState) {} protected int getActionBarSize() { TypedValue typedValue = new TypedValue(); int[] textSizeAttr = new int[]{R.attr.actionBarSize}; int indexOfAttrTextSize = 0; TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr); int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1); a.recycle(); return actionBarSize; } private void update(final int scrollY){ vFlexibleSize.setTranslationY(-scrollY); int adjustedY = scrollY; if (scrollY<0){ adjustedY = 0; Log.i(TAG,"Scroll Y <0 - " + scrollY); } else if (flexibleSize < scrollY){ adjustedY = flexibleSize; Log.i(TAG,"scrollY is bigger than flexibleSize - " +scrollY); } float maxScale = (float) (flexibleSize - mToolbar.getHeight()) / mToolbar.getHeight(); Log.i(TAG,"maxScale is " + maxScale); float scale = maxScale * ((float) flexibleSize - adjustedY) / flexibleSize; Log.i(TAG,"scale is " + scale); tvTitle.setPivotX(0); tvTitle.setPivotY(0); tvTitle.setScaleX(scale + 1); tvTitle.setScaleY(scale + 1); } What's basically happening here is there is a Frame layout at the top of the screen, consisting of a LinearLayout that has the Toolbar on top and a view underneath it that expands and collapses when we scroll. below that I have the recyclerView. I collapse the flexibleView when there is a scroll in the update method by setting it's TranslationY. The problem is that when I scroll and the FlexibleView collapses the recyclervies's padding stays, or the LinearLayout doesn't change it's bounds, or something is making the recylcerview stay in it's location and not go up sticking to the edge of the toolbar FrameLayout. Does anyone have any ideas how do I fix this?
{ "language": "en", "url": "https://stackoverflow.com/questions/28889432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby on Rails: Create Database Entry without JavaScript i´m kinda new in web development and try to get started a project with Ruby on Rails (3.2.9). So, i´m a little bit confused about what RoR can do without JavaScript or not... For Example with using a Rails Scaffold, it´s no problem to create new records in the database via accessing the Controller´s new method (which then calls the create method and saves the record to the database) I would now like to create new records without using a view for it. Just something like "User hits a button -> record is saved" I will give you an example (i need this for my studies, it´s not a real life project...) I have a view which shows all my articles (rails generate scaffold article) and now added a link to a "buy-method" which shows the articles name and available amount. below there is a field in which a customer could select the amount of the article he wants to buy. <p> <b>Name:</b> <%= @article.name %> </p> <p> <b>Available:</b> <%= @article.stocks %> </p> <%= form_for(@article) do |f| %> <div class="field"> <b>How many?</b> <br /> <%= f.number_field :amount %> </div> <% end %> Now i want to add a link (or better a button i think) which causes an event which turns the article´s name and the selected amount into something like an order item i.e. create a record in an order_item table. <td><%=link_to "Ja", :controller => "oderItem", :method => "create" %></td><br> Now i´m confused about how i can do it. I thought about using just the create - Method (or any method) of the Controller which does something like: def match @apo = OrderItem.new(:amount :2, ...) @apo.save end But this just seems to render me to the new-method of the controller or sth like that. So, with this explanations (which maybe as well reveal the level of my knowledge...) can anybody tell me if i am doing something really wrong with rails or if i just have to use javascript for this??? Some Sample Code (for Rails and / or JS) would be appreciated the most! (Please keep it simple, i know that Ajax etc. are state of the Art but i just want to get this running :-) ) ...also links to Code-Samples which just show projects like this on Rails (simply :-) ) would be very nice! A: Ruby on Rails does not depend on Javascript and therefore you don't need to know Javascript to learn Ruby and Rails. To answer one of your questions the link_to method doesn't refer to which action you are trying to call but to the HTTP method such as "POST", "GET", "PUT", "DELETE". You should use :action to tell which action in the controller (methods) to go to. There are a few places that can get you started with Ruby and Rails. * *Code School - Code school has a few free courses and one of them happens to be a very good one on Ruby on Rails *Code Academy - Code academy is more structured than code school and still provides many courses on different web development technologies *Railscasts - Railscasts is a great site with some free videos of rails tutorials Maybe some people can elaborate on more sources. Also, Github has many open source projects that you can take a look at and have a feel on how people use Ruby and Rails. A: In order to change the the page layout to show a "mini" form in response to a user clicking a particular element, you're going to either need to render a new view, or modify the current document via JavaScript. Here's a simplified version of what this view code might look like if you opted to reveal a form via JavaScript: ERB: # rendering each available article... <% @articles.each do |article| %> <p> <b>Name:</b> <%= article.name %> </p> <p> <b>Available:</b> <%= article.stocks %> </p> <% button_tag(:type => 'button', :class => 'buy-btn', data-article-id="article.id") do %> <strong>Buy Me!</strong> <% end %> # for each article, create a mini form with which # the user can buy n of said article... <div class="field hidden-item" id="form-#{article.id}" > <%= form_for(OrderItem.new do |f| %> <b>How many?</b> <br /> <%= f.number_field_tag :amount%> <%= f.submit %> <% end %> </div> <% end %> CSS: .field { display: none; //hides the div from all browsers by default } JavaScript to help tie everything together: $(document).ready(function() { //... other js code // bind all elements with the css class 'buy-btn' to // a click event... $(".buy-btn").bind('click', function() { var id = $(this).data('article-id'); $("#form-" + id).slideDown(); // shows the selected element with a nice slide down effect }); //... other js code }); So in the ERB we supply each article with a mini-form waiting to be populated and submitted. The form is hidden by default in our CSS, to be made visible when the user clicks the "Buy Me!" button for the article in question. This approach can also be adjusted a bit to allow the user to order however many different articles they desire by moving the the form declarations around a bit, and with appropriate handling in the OrderItemsController.create action. Another thing to keep in mind is that clicking the submit button on a form will cause the page to redirect by default. That's probably how you'll want to leave it while just getting started, but when you start to become comfortable, check out how to use :remote => true on submit tags to allow submitting forms in the background via AJAX. If you REALLY want to do it without any JavaScript at all, you're going to either have to do some very advanced work with CSS or will have to rig a link that passes a parameter to your view that instructs it to show a particular form. Here's what that might look like: # rendering each available article, as before... <% @articles.each do |article| %> <p> <b>Name:</b> <%= article.name %> </p> <p> <b>Available:</b> <%= article.stocks %> </p> # ... but now set up a link that passes a param to the controller... <%= link_to( 'Buy Me!', "/articles?article=#{article.id}" ) %> # which we then use to render a form on the page if the id in the # 'article' param matches the id of the article we are currently # rendering... <% if params[:article] && params[:article] == article.id %> <%= form_for(OrderItem.new do |f| %> <b>How many?</b> <br /> <%= f.number_field_tag :amount%> <%= f.submit %> <% end %> </div> <% end %> This may not be exact, but I hope it points you in the right direction!
{ "language": "en", "url": "https://stackoverflow.com/questions/13712059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OrderBy and ThenBy with anonymous class I have this: List<string> lstRanksOrder = new List<string>() { "Captain", "Lieutenant", "Sergeant", "Corporal Master", "Corporal Senior", "Corporal 1", "Corporal", "Civilian Pilot" }; var emp = test .ToList() .Select(x => new { EID = x.IBM, Description = string.Format("{0} {1}", x.FirstName, x.LastName), Group = x.RPosition }) .AsEnumerable() .OrderBy(x => lstRanksOrder.IndexOf(x.Group)) .ThenBy(x => x.Description) .Distinct() .ToList(); The ThenBy Clause works fine, but is there a way to alter it to order by LastName before FirstName without changing the Description to Description = string.Format("{0} {1}", x.LastName, x.FirstName)? A: Order the collection before calling the Select extension method: var emp = test.ToList() .OrderBy(x => lstRanksOrder.IndexOf(x.RPosition)) .ThenBy(x => x.LastName) .ThenBy(x => x.FirstName) .Select(x => new { EID = x.IBM, Description = string.Format("{0} {1}", x.FirstName, x.LastName), Group = x.RPosition }) .Distinct() .ToList(); A: Distinct then Order the collection before calling the Select extension method: var emp = test.ToList() .Distinct() .OrderBy(x => lstRanksOrder.IndexOf(x.RPosition)) .ThenBy(x => x.LastName) .ThenBy(x => x.FirstName) .Select(x => new { EID = x.IBM, Description = string.Format("{0} {1}", x.FirstName, x.LastName), Group = x.RPosition }) .ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/37032947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Unable to connect XMPPFramework to Openfire server in iOS I am working on an iOS chat app where user login to app. I've downloaded XMPPFramework from GitHub XMPPFramework. I am trying to connect XMPP framework with Openfire server by following this tutorial. Here is my code to connect XMPP to openfire. - (BOOL)connect { [self setupStream]; [xmppStream setHostName:@"192.168.1.5"]; [xmppStream setHostPort:5222]; NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:@"userID"]; NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:@"userPassword"]; if (![xmppStream isDisconnected]) return YES; if (jabberID == nil || myPassword == nil) return NO; [xmppStream setMyJID:[XMPPJID jidWithString:jabberID]]; password = myPassword; NSError *error = nil; if (![xmppStream isConnected]) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Can't connect to server %@", [error localizedDescription]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alertView show]; return NO; } return YES; } The problem is when I run the app, it shows the alert can't connect to server. I have checked many questions on StackOverflow and tried googling but couldn't find any relevant solution. How to connect it to the Openfire serve? If I am doing anything wrong in my code please suggest me with a snippet of code or a tutorial to make this happen. A: A host of possibilities. Try adding break points at xmppStreamDidConnect and xmppStreamDidAuthenticate. If xmppStreamDidConnect isn't reached, the connection is not established; you've to rectify your hostName. If xmppStreamDidAuthenticate isn't reached, the user is not authenticated; you've to rectify your credentials i.e. username and/or password. One common mistake is omitting of @domainname at the back of username i.e. username@domainname e.g. keithoys@openfireserver where domain name is openfireserver. A: Hope this still relevant, if not, hopefully it will help others. There are some issues with your code: * *I don't see the call to connect, you should add something like this: NSError *error = nil; if (![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error]) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting" message:@"Msg" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alertView show]; } *Most of the XMPP API is asynchronous. You have to set the stream delegate in order to receive events. Check out XMPPStreamDelegate and XMPPStream#addDelegate If you don't want to go through the code yourself XMPPStream.h , you can implement all methods of XMPPStreamDelegate and log the events. This will help you understand how the framework works. Hope this helps, Yaron
{ "language": "en", "url": "https://stackoverflow.com/questions/26750301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: no graph output for d3.js http://jsfiddle.net/amanminhas16/KUf7f/ var root = { "name" : "Total Number Of Users", "size" : 50000, "children": [{ "name":"user A" }, { "name":"user B" }, { "name":"user C" }, { "name":"user D" }, ] }; this was inspired by http://jsfiddle.net/augburto/YMa2y/ But even if i get the exact code, i do not get a graph output. If i copy my code into his jsfiddle, it gives me my desired result. can you tell me what could be the issue ? i am using WAMP + Zend. Thank you in adv. A: The documentation page explains quite well how to setup d3 in your localhost. You have to: * *include d3.js in your page using: <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> *start a python server if you want to access local files using: python -m SimpleHTTPServer 8888 & A: Thanks a lot for your suggestion. But actually, The problem was that i did not put my javascript code in $(document).ready(function(){//here}) It works great now :) .. Thank you Christopher and FernOfTheAndes for all the help
{ "language": "en", "url": "https://stackoverflow.com/questions/21995927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB - Replace Function and escaping a quote I appreciate there are a lot of similar posts on here which I have read with interest, but I just can't find the solution for my particular issue, hope someone can help. strFieldValue is a string (a title) which may contain quotes e.g. someone may put text like 9" (9 inch) - this causes issues for the code following this. So I wanted to search the string for the quote(s) and replace with escaped quotes. So far I have only managed to remove the quote altogether. What I have tried - newFieldValue = Replace(strFieldValue,Chr(34), "") - this removed the quote newFieldValue = Replace(strFieldValue,Chr(34), """"") - I thought this would work as the double quotes would escape the one in the middle, but all it did was print all 5 quotes in my debug Is there a way to make any quotes in the string 'safe' but still exist? Many thanks Lisa The data passed to the JSON scripts, which contains the offending string: {"request":{},"results":[{"columns":[{"dbname":"REFERENCE","text":"Reference"},{"dbname":"VERSION","text":"Version"},{"dbname":"TITLE","text":"Title"},{"dbname":"AUTHOR","text":"Author"},{"dbname":"STATE","text":"State"}],"rows":[{"id":"6422","REFERENCE":"TPJ/TECH/DES/406","VERSION":"v1A","TITLE":"Doc Baselines Test lisa % && /","AUTHOR":"LISA CARVER","STATE":"Filed"}]}]} {"request":{},"results":[{"columns":[{"dbname":"REFERENCE","text":"Reference"},{"dbname":"VERSION","text":"Version"},{"dbname":"TITLE","text":"Title"},{"dbname":"AUTHOR","text":"Author"},{"dbname":"STATE","text":"State"}],"rows":[{"id":"6422","REFERENCE":"TPJ/TECH/DES/406","VERSION":"v1A","TITLE":"Doc Baselines Test lisa" % && /","AUTHOR":"LISA CARVER","STATE":"Filed"}]}]} The latter one is cutting the string short with the quote. A: This is likely too late to be any help to this poster, but JSON is JavaScript Object Notation, which means the language for which the quote needs to be escaped is JavaScript, rather than VB.Net. To escape a single or a double quote in JavaScript, you can replace it with a backslash followed by the single or double quote. That is a little tricky to write in a Regex -- and this becomes a much nastier problem in C#.Net because C# also uses backslash for escaping -- but this example should get you started: Dim s AS String s = "This is a ""quote"" test." s = Regex.Replace(s,"[""]","\\""") ' After VB.Net quote-escaping and replacing the string-delimiting quote marks with the slashes more familiar to JavaScript users, that reduces to /["]/ (with an implicit global replace directive) for the pattern, and a string consisting of a backslash followed by a double-quote, for the replacement value.
{ "language": "en", "url": "https://stackoverflow.com/questions/36719523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL Query slow I have an app that analyzes peoples facebook likes and matches them up with things they may have liked in past decades. As part of refining the matches we have, I store each users likes (with a hash of their facebook ID, to keep it anonymous). People can enter multiple times, so it stores their likes multiple times, thus skewing the results a bit. So my user_likes table is like this: id | page_id | user_id_hash ---------------------------------- | | I have around 820,000 records currently. Currently if I do a query: SELECT page_id, COUNT(*) from user_likes GROUP BY page_id LIMIT 0,30 This takes around 8 seconds and gives me an incorrect count, since it can count people who entered multiple times more than once. My questions are: 1) How can I speed this query up? 2) How can I get a more accurate count? A: You can get a more accurate count by phrasing the query like this: SELECT page_id, COUNT(distinct user_id_hash) from user_likes ul GROUP BY page_id LIMIT 0,30; Speeding it up in MySQL is tricky, because of the group by. You might try the following. Create an index on user_likes(page_id, user_id_hash). Then try this: select p.page_id, (select count(distinct user_id_hash) from user_likes ul where ul.page_id = p.page_id ) from (select distinct page_id from user_likes ul ) p The idea behind this query is to avoid group by -- a poorly implemented operator in MySQL. The inner query should use the index to get the list of unique page_ids. The subquery in the select should use the same index for the count. With the index-based operations, the count should go faster.
{ "language": "en", "url": "https://stackoverflow.com/questions/18709887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to play Invisible Music in a Batch file I was making a batch Music Player, but I can't play Invisible Music. I have tried this: @echo off :1 echo Hello pause goto 2 :2 start /min wmplayer "C:\Users\*user\Desktop\Games\Music.wav" goto 1 But it doesn't show up minimized. How can I start wmplayer minimized? A: @echo off set file=track12.mp3 ( echo Set Sound = CreateObject("WMPlayer.OCX.7"^) echo Sound.URL = "%file%" echo Sound.Controls.play echo do while Sound.currentmedia.duration = 0 echo wscript.sleep 100 echo loop echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000) >sound.vbs start /min sound.vbs just change track12.mp3 with the name of your audio file A: And here is a complete batch source for a batch Music Player ! So enjoy it ;) Batch Music Player.bat @echo off setlocal enabledelayedexpansion Set vbsfile=%temp%\Intro.vbs Set URL=http://hackoo.alwaysdata.net/Intro_DJ.mp3 Call:Play %URL% %vbsfile% Start %vbsfile% Set MyFile=%~f0 Set ShorcutName=DJ Batch Music Player ( echo Call Shortcut("%MyFile%","%ShorcutName%"^) echo ^'**********************************************************************************************^) echo Sub Shortcut(CheminApplication,Nom^) echo Dim objShell,DesktopPath,objShortCut,MyTab echo Set objShell = CreateObject("WScript.Shell"^) echo MyTab = Split(CheminApplication,"\"^) echo If Nom = "" Then echo Nom = MyTab(UBound(MyTab^)^) echo End if echo DesktopPath = objShell.SpecialFolders("Desktop"^) echo Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^) echo objShortCut.TargetPath = Dblquote(CheminApplication^) echo ObjShortCut.IconLocation = "Winver.exe,0" echo objShortCut.Save echo End Sub echo ^'********************************************************************************************** echo ^'Fonction pour ajouter les doubles quotes dans une variable echo Function DblQuote(Str^) echo DblQuote = Chr(34^) ^& Str ^& Chr(34^) echo End Function echo ^'********************************************************************************************** ) > %temp%\Shortcutme.vbs Start /Wait %temp%\Shortcutme.vbs Del %temp%\Shortcutme.vbs ::**************************************************************************************************** Title DJ Batch Music Player by Hackoo 2015 :menuLOOP Color 0A & Mode con cols=78 lines=25 echo( echo =============================================================== echo "/ | / | / | "; echo "$$ | $$ | ______ _______ $$ | __ ______ ______ "; echo "$$ |__$$ | / \ / |$$ | / | / \ / \ "; echo "$$ $$ | $$$$$$ |/$$$$$$$/ $$ |_/$$/ /$$$$$$ |/$$$$$$ |"; echo "$$$$$$$$ | / $$ |$$ | $$ $$< $$ | $$ |$$ | $$ |"; echo "$$ | $$ |/$$$$$$$ |$$ \_____ $$$$$$ \ $$ \__$$ |$$ \__$$ |"; echo "$$ | $$ |$$ $$ |$$ |$$ | $$ |$$ $$/ $$ $$/ "; echo "$$/ $$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$/ $$$$$$/ "; echo " "; echo " "; echo( =============================Menu============================== echo( for /f "tokens=2* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo %%A %%B echo( echo( =============================================================== set choice= echo( & set /p choice=Make a choice or hit ENTER to quit: || GOTO :EOF echo( & call :menu_[%choice%] GOTO:menuLOOP ::******************************************************************************************** :menu_[1] Play DJ Buzz Radio cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching DJ Buzz Radio ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\DJBuzzRadio.vbs Set URL=http://www.chocradios.ch/djbuzzradio_windows.mp3.asx Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[2] Play David Guetta Mix cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching David Guetta Mix ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\David_Guetta_Miami.vbs Set URL=http://hackoo.alwaysdata.net/David_Guetta_Miami_2014.mp3 Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[3] Play Ibiza Mix cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching Ibiza Mix ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\IbizaMix.vbs Set URL=http://hackoo.alwaysdata.net/IbizaMix.mp3 Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[4] Play Avicii Mega Mix cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching Avicii Megamix ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\IbizaMix.vbs Set URL="http://hackoo.alwaysdata.net/Best of Avicii Megamix 2014.mp3" Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[5] Play Mega Mix 90 cls & color 0A Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Launching Mega Mix 90 ... Taskkill /IM "wscript.exe" /F >nul 2>&1 Set vbsfile=%temp%\IbizaMix.vbs Set URL="http://hackoo.alwaysdata.net/Megamix 90.mp3" Call:Play %URL% %vbsfile% Start %vbsfile% TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :menu_[6] Stop the music cls & color 0C Call:SkipLine 10 Call:Tab 3 echo %x% Please Wait for a while .. Stopping the music ... Taskkill /IM "wscript.exe" /F >nul 2>&1 TimeOut /T 1 /NoBreak>nul GOTO:menuLOOP ::******************************************************************************************** :Play ( echo Play "%~1" echo Sub Play(URL^) echo Dim Sound echo Set Sound = CreateObject("WMPlayer.OCX"^) echo Sound.URL = URL echo Sound.settings.volume = 100 echo Sound.Controls.play echo do while Sound.currentmedia.duration = 0 echo wscript.sleep 100 echo loop echo wscript.sleep (int(Sound.currentmedia.duration^)+1^)*1000 echo End Sub )>%~2 ::********************************************************************************************* :Tab set "x=" For /L %%I In (1,1,%1) Do Set "x=!x! " REM ^-- this is a TAB goto :eof ::********************************************************************************************* :SkipLine For /L %%I In (1,1,%1) Do Echo( Goto:Eof :EOF EXIT ::*********************************************************************************************
{ "language": "en", "url": "https://stackoverflow.com/questions/31685055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ Libraries ecosystem using CMake and Ryppl I am interested in building a cross-platform C++ Library and distributing it in source form. I want the consumers of this library to be able to acquire it, build it and consume it inside their software very easily on whatever platform they are working on and for whatever platform they are targeting. At the same time while building my library, I also want to be able to consume other popular OSS libraries through a similar mechanism. I see that CMake and Ryppl were created with these intentions in mind and to some extent they do solve some of these problems, especially the build problem. But I don't quite know how exactly to go about achieving the above mentioned goals. Is it OK to settle on CMake as the build solution? How do I solve the library acquisition and distribution problem? Simply host the sources somewhere and let people discover, download and build them? Or is there a better way? A: At the time of writing there is no accepted solution that handles everything you want. CMake gives you cross-platform builds and git (with submodules) gives you a way to manage source-level dependencies if all other projects are using CMake. But, in practice, many common dependencies you project wil need don't use CMake, or even Git. Ryppl is meant to solve this, but progress is slow because the challenge is such a hard one. Arguably, the most successful solution so far is to write header-only libraries. This is common practice and means your users just include your files, and their build system of choice takes care of everthing. There are no binary dependencies to manage. A: TheHouse's answer is still essentially true. Also there don't seem to have been any updates to ryppl itself for a while (3 years) and the ryppl.org domain has expired. There are some new projects aiming to solve the packaging issue. Both build2 and wrap from mesonbuild have that goal in mind. A proposal was made recently to add packages to the c++ standard which may open up the debate (reddit discussion here). Wrap looks promising as meson's author has learned from cmake. There is a good video when its author discussing this here. build2 seems more oblivious (and therefore condemned to reinvent). However both suffer from trying to solve the external project dependencies issue simultaneously with providing a complete build system. conan.io is another recent attempt which doesn't try to provide the build system as well. Time will tell if any of these gain any traction. The accepted standard for packaging C and C++ projects on Unix was always a source tarball + a configure script (autotools) + make. cmake is now beginning to replace autotools as your first choice. It is able create RPMs and tarballs for distribution purposes. Its also worth considering the package managers built into the various flavours of Linux. The easiest to build and install projects are those where most of the dependencies can be pulled in via yum or apt. This won't help you on windows of course. While there is a high barrier to entry getting your own projects added to the main Linux repositories (e.g. RedHat, Debian) there is nothing to stop you adding your maintaining your own satellite repo. The difference between that and just hosting your project on github or similar is you can provide pre-built binaries for a number of popular systems. You might also consider that configure times checks (e.g. from cmake findLibrary()) and your own documentation will tell people what needs to be installed as a prerequisite and providing you don't make it too onerous that might be enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/18861289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there need any other file or code in RFID to unlock windows Here I upload this code in my Arduino Leonardo circuit but when I scanned my card on RFID sensor windows locked successfully but when I scanned card on lock screen there is error occur that incorrect password enter. So I want suggestion about update or addition in code. #include <deprecated.h> #include <MFRC522.h> #include <MFRC522Extended.h> #include <require_cpp11.h> #include <Keyboard.h> #include <SPI.h> #include <MFRC522.h> #define SS_PIN 10 #define RST_PIN 2 #define KEY_RETURN 0xB0 //The hex value for the return key is 0xB0. MFRC522 mfrc522 ( SS_PIN, RST_PIN ) ; char Enter = KEY_RETURN; //Return key is declared as Enter. String readid; String card1="e9226c15"; //Change this value to the UID of your card. void setup( ) { Serial.begin(9600); Keyboard.begin(); SPI.begin(); mfrc522.PCD_Init(); } void temp(byte *buffer, byte bufferSize)//function to store card uid as a string datatype. { readid=""; for(byte i = 0;i<bufferSize; i++) { readid=readid+String(buffer[i], HEX); } } void loop( ) { if(!mfrc522.PICC_IsNewCardPresent()) { return; } if(!mfrc522.PICC_ReadCardSerial()) { return; } mfrc522.PICC_DumpToSerial(&(mfrc522.uid)); // Display card details in serial Monitor. temp(mfrc522.uid.uidByte, mfrc522.uid.size); if(readid==card1) { Keyboard.press(KEY_LEFT_GUI); //Press the left windows key. Keyboard.press('l'); //Press the "l" key. Keyboard.releaseAll(); //Release all keys. delay (100); Keyboard.press(Enter); //Press the Enter key. Keyboard.release(Enter); //Release the Enter key. delay(100); Keyboard.print("12345"); // Change this value to your Windows PIN/Password. Keyboard.releaseAll(); delay(100); Keyboard.press(Enter); Keyboard.releaseAll(); } else { return; } } ``
{ "language": "en", "url": "https://stackoverflow.com/questions/66451644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In the CSS .style.transform function im trying to add the degrees to be 90 + MenuRotate which is a variable The code function OpenMenu(){ var MenuRotate = getCurrentRotation(document.getElementById("Menu-Icon")); document.getElementById("menu").style.margin = "450px"; document.getElementById("Menu-Icon").style.transform ="rotate(90deg)"; var Menu1 = 1; //alert(MenuRotate); function getCurrentRotation(el){ var st = window.getComputedStyle(el, null); var tm = st.getPropertyValue("-webkit-transform") || st.getPropertyValue("-moz-transform") || st.getPropertyValue("-ms-transform") || st.getPropertyValue("-o-transform") || st.getPropertyValue("transform") || "none"; if (tm != "none") { var values = tm.split('(')[1].split(')')[0].split(','); /* a = values[0]; b = values[1]; angle = Math.round(Math.atan2(b,a) * (180/Math.PI)); */ //return Math.round(Math.atan2(values[1],values[0]) * (180/Math.PI)); //this would return negative values the OP doesn't wants so it got commented and the next lines of code added var angle = Math.round(Math.atan2(values[1],values[0]) * (180/Math.PI)); return (angle < 0 ? angle + 360 : angle); //adding 360 degrees here when angle < 0 is equivalent to adding (2 * Math.PI) radians before } return 0; } I would like to be able to add MenuRotate to the 90 degrees, not sure how i could do this so im looking for some answers A: I read the article that the OP code is originally from and I believe it's overkill. What should be done to avoid so much work is to setup the elements angles initially so you know what to start from or reset the elements to 0. Example A features a <form> that allows the user to rotate an element by adding positive and/or negative numbers (min -360, max 360). Example B features a function that operates the same as the event handler (spin(e)) in Example A. Details are commented in both examples Example A <form> as User Interface // Bind <form> to the submit event document.forms.spin.onsubmit = spin; function spin(e) { // Stop normal behavior when submit is triggered e.preventDefault(); // Reference all form controls const IO = this.elements; // Reference <output> const comp = IO.compass; // Reference <input> const turn = IO.turn; // Get <input> value and convert it into a number let deg = +turn.value; // Add comp value with turn value and assign to comp value comp.value = +comp.value +(deg); // If comp value is ever over 360, reset it if (+comp.value > 360) { comp.value = +comp.value - 360; } // .cssText is like .textContent for the style property comp.style.cssText = `transform: rotate(${comp.value}deg)`; } fieldset { display: flex; justify-content: center; align-items: center; } #turn { width: 3rem; text-align: center; } #compass { position: relative; display: flex; justify-content: center; align-items: center; width: 100px; height: 100px; border-radius: 50%; background: rgba(0, 0, 255, 0.3); } #compass::before { content: '➤'; position: absolute; z-index: 1; transform: rotate(-90deg) translate(55%, -5%); transform-origin: center center; font-size: 3rem; } <form id='spin'> <fieldset> <input id='turn' type='number' min='-360' max='360' step='any'><input id='add' type='submit' value='Add'> </fieldset> <fieldset> <output id='compass' value='0'></output> </fieldset> </form> Example B No <form>, Only a Function // Declare variable to track angle let degree; /** * @desc - Rotates a given element by a given number of * degrees. * @param {object<DOM>} node - The element to rotate * @param {number} deg - The number of degrees to rotate * @param {boolean} init - If true the element's rotate value * will be 0 and degree = 0 @default is false */ function turn(node, deg, init = false) { // If true reset node rotate and degree to 0 if (init) { node.style.cssText = `transform: rotate(0deg)`; degree = 0; } /* Simple arithmatic Reset degrees when more than 360 */ degree = degree + deg; if (degree > 360) { degree = degree - 360; } // .cssText is like .textContent for the style property node.style.cssText = `transform: rotate(${degree}deg)`; console.log(node.id + ': ' + degree); } const c = document.getElementById('compass'); turn(c, 320, true); fieldset { display: flex; justify-content: center; align-items: center; } #compass { position: relative; display: flex; justify-content: center; align-items: center; width: 100px; height: 100px; border-radius: 50%; background: rgba(0, 0, 255, 0.3); } #compass::before { content: '➤'; position: absolute; z-index: 1; transform: rotate(-90deg) translate(55%, -5%); transform-origin: center center; font-size: 3rem; } <fieldset> <output id='compass' value='0'></output> </fieldset>
{ "language": "en", "url": "https://stackoverflow.com/questions/72739147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Xamarin : UISearchController is not becoming first responder and editing is not getting started while adding it to Navigation Bar I am facing a strange issue with UISearchController. I have added the search controller in Navigation Bar in UIViewController1 on click of a button. It is working fine in UIViewController1. Now I am navigating to UIViewController2 and there also I am adding the UISearchController on click of a button. Below is the sample code. The problem is that in UIViewController2 UISearchController is not becoming first responder and OnEditingStarted is not getting fired. It is happening when I have used (added search controller) in UIViewController1 and now trying to use in UIViewController2. This is how I am adding search controller: DefinesPresentationContext = true; _searchController = new UISearchController(searchResultsController: null) { WeakDelegate = this, DimsBackgroundDuringPresentation = false, WeakSearchResultsUpdater = this, }; _searchController.SearchBar.SizeToFit(); _searchController.SearchBar.TintColor = UIColor.Black; _searchController.SearchBar.WeakDelegate = this; _searchController.SearchBar.OnEditingStarted += OnEditingStarted; _searchController.SearchBar.OnEditingStopped += OnEditingStopped; _searchController.SearchBar.SearchButtonClicked += OnSearchButtonClicked; _searchController.SearchBar.CancelButtonClicked += OnSearchCancelledClicked; _searchController.HidesNavigationBarDuringPresentation = false; NavigationController.NavigationBar.TopItem.TitleView = this._searchController.SearchBar; _searchController.SearchBar.BecomeFirstResponder(); OnSearchCancelledClicked I am trying to remove the UISearchController NavigationController.NavigationBar.TopItem.TitleView = null; _searchController.SearchBar.ResignFirstResponder(); _searchController.SearchBar.RemoveFromSuperview(); What could be issue. Is the Search controller from the previous screen is still active and blocking calls to search controller in the new screen. If I directly navigate to UIViewController2 then search controller isworking fine. A: I finally resolved this issue by setting the property in a new thread like below: Task.Factory.StartNew(() => { InvokeOnMainThread(() => { _searchController.SearchBar.BecomeFirstResponder(); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/41198849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I remove the duplicate pages from EJS template pagination? I have found this article for implementing a pagination feature in my MEN stack app. The article shows everything from frontend to backend. Everything works fine but I'm trying to tweak it a little. The demo app from the article looks like this: But I replaced the First and Last from the start and the end and used 1 and 10, but now I have a duplicate of 1 and 10. Like this: Here's the code: <% if (pages > 1) { %> <ul class="pagination-list"> <% if (currentPage == 1) { %> <li class="disabled"><a>1</a></li> <% } else { %> <li><a href="/1">1</a></li> <% } %> <% var i = (Number(currentPage) > 5 ? Number(currentPage) - 4 : 1) %> <% if (i !== 1) { %> <li class="disabled"><a>...</a></li> <% } %> <% for (; i <= (Number(currentPage) + 4) && i <= pages; i++) { %> <% if (i == currentPage) { %> <li class="active"><a><%= i %></a></li> <% } else { %> <li><a href="/<%= i %>"><%= i %></a></li> <% } %> <% if (i == Number(currentPage) + 4 && i < pages) { %> <li class="disabled"><a>...</a></li> <% } %> <% } %> <% if (currentPage == pages) { %> <li class="disabled"><a><%= pages %></a></li> <% } else { %> <li><a href="/<%= pages %>"><%= pages %></a></li> <% } %> </ul> <% } %> How can I remove the duplicate ones? *** Thanks to Mikhail Evdokimov for the tutorial. *** A: Try changing the for loop to: for (; i <= (Number(currentPage) + 4) && i < pages; i++) { That should do the trick for the 10 you want to remove. Hope it works, not sure it will, can't test it right now. If you won't get it working in like 2 hours, I can help you then, when I could test it on my example. Edit: The 10 got removed. We simply changed "less than or equal" to "less than", meaning the last for cycle didn't get executed because we were at the last cycle of the last page already. Now for the 1: var i = (Number(currentPage) > 5 ? Number(currentPage) - 4 : 1) You should change this i declaration. What this code tells us is: If the number of the current page is higher than 5 do: Number(currentPage) - 4 else 1 And because we are using the i variable as a starting point in our for loop, we should change the 1 to 2. So the correct declaration should be: var i = (Number(currentPage) > 5 ? Number(currentPage) - 4 : 2) Second edit: Now for the ... problem: You can probably change i !== 1 to i !== 2 That should fix it, it's the same principle, we are starting for loop from 2, so we have to change it to 2. We are telling it: don't show ... when we are on pages: 1, 2, 3, 4, 5 now.
{ "language": "en", "url": "https://stackoverflow.com/questions/66489692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extract value from an ID tag in a extracted Html data I hope my topic finds you well. I want to extract a specific number from an ID value, here is the line: TAG POS=1 TYPE=INPUT ATTR=CLASS:markAll<SP>check EXTRACT=HTM and here is the result I get after I run the previous line: <input style="outline: 1px solid blue;" id="raidListMarkAll1518" class="markAll check" onclick="Game.RaidList.markAllSlotsOfAListForRaid(1518, this.checked); "type="checkbox"> For example, I want only to extract this number (1518) from this (id="raidListMarkAll1518"). I don't know how to make the EVAL command to achieve the result I want. I hope to get help from you guys, I really appreciate it Thank you so much.
{ "language": "en", "url": "https://stackoverflow.com/questions/58475967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XAML Designer show error in VIsual Studio 2019 Introduction I wanted to develop the UWP application further and for some reason I am not able to use the XAML designer functionally. Every feature is up to date. Have opened Visual Studio 2019 and switched to XAML-Designer. Problem The XAML designer does not recognise objects of the classes that are responsible for the UI surface. Screenshot A: Change Run Configuration to x86 to Debug or Release
{ "language": "en", "url": "https://stackoverflow.com/questions/68107458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I use class instance(serialized) or Singleton for storing userInfo once the user login I want to know what would be a better approach for Storing user info once he logs in. Should I parse the data into Serizaled object class? Or should I create A singleton. Mostly I get around 12-13 obejects from the server once I login, however 2-3 of them are used all over the app, the others are not very common. A: You have several options. Read here: https://developer.android.com/guide/topics/data/data-storage.html In your case perhaps you can simply use SharedPreferences, here: https://developer.android.com/guide/topics/data/data-storage.html#pref SharedPreferences sharedPreferences = context.getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE); To put the value: (.commit() instead of .apply() if you care whether or not putString was successful) SharedPreferences sharedPreferences = context.getSharedPreferences(COOKIE_SP_FILE_NAME, Context.MODE_PRIVATE); if (sharedPreferences != null) { sharedPreferences.edit().putString("KEY", "VALUE").apply(); } To retrieve the value: SharedPreferences sharedPreferences = context.getSharedPreferences("FILE_NAME", Context.MODE_PRIVATE); if (sharedPreferences != null) { String theString = sharedPreferences.getString("KEY", "DEFAULT_VALUE"); } Where "DEFAULT_VALUE" is what you would get if no value with "KEY" as key was found.
{ "language": "en", "url": "https://stackoverflow.com/questions/45210161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change a div tag from fixed to absolute and back? In the Facebook News Feed, the side bar (containing ads, etc.) isn't fixed all the time. How do you do this? You could do <div style="position:fixed"></div> But how could you tell it to change back and forth according to your wish? A: If you are happy to do it with jQuery: $("#sideBar").css("position", "fixed"); and then to change it back: $("#sideBar").css("position", "");
{ "language": "en", "url": "https://stackoverflow.com/questions/16059399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }