text
stringlengths
64
89.7k
meta
dict
Q: Good way to simulate a disk failure in vSphere I need to be able to demonstrate SQL Server recovery procedures and since our DBs are all virtualized and using a SAN for backend storage, I need to know what the best way is to simulate a disk failure and recovery using a tail-log backup. I've tried removing the data volume from the VM in vSphere but SQL doesn't seem to be aware that the MDF file is no longer accessible and doesn't trigger a fault, and none of the other options I think of can be done "live". I'm just not enough of a vSphere guy to know my options here. A: I can really only see a couple of options here. They both assume that the only thing on this datastore is the VMDK that's housing the SQL Server's MDFs. No VMX files, no log files, no datastore heartbeating. The first would be to unmount the volume on the host in question. You can do it via the vSphere clients, esxcli or it's PowerCLI equivalent. I don't actually know if vSphere will let you do this while it's got a running VM attached, but it might. The second is to just un-present the volume from the SAN or mask it on the host in question. It's a really drastic thing to do and might cause more pain than it's worth since it's likely to cause the host to throw a PDL or APD error, but it will give you what you want if the first option isn't possible cause VMware blocks it (which is actually a good thing). If you're attempting the second option, you should read up on this article about PDL/APD and the articles listed in the 'See Also' section. Oh, and don't do it to a production box. And have backups before trying any of this.
{ "pile_set_name": "StackExchange" }
Q: iOS emoji for android app. Is it legal? Before this question gets marked as a repeat, let me say I have gone throughout the existing questions on StackOverflow, and I have not found a proper answer. I am aware that there are many apps that enable the iOS design emojis on android phones, and I'm also aware that I could potentially add them to my android app, but my question is: Is it legal to use Apple's emoji icons in my android app? Do I need some sort of special permission from them? Whatsapp is a good example. They use Apple's emoji icon designs in their keyboard for both iPhone and Android. Could i too do the same for my app's keyboard? Would it be legal to do so, or will I have any issues in the future? Thanks. A: Emoji are Unicode characters, so should work if you have written your application in a Unicode aware manner all the way through (for ex, by using NVARCHAR types on your database layer)
{ "pile_set_name": "StackExchange" }
Q: Menu disappears after changing template It's been awhile since I've used Joomla and I'm trying to get back into it. I just uploaded a new template that supports Joomla 3.5 and the minute I change to the template, the menu at the top goes away and the one that the demo shows for the template doesn't appear. Is there anything that I need to change in Joomla after changing the template as well? I apologize for this question that may be answered somewhere already, but I'm really just having a hard time trying to find this information. A: Just figured this one out on my own. Had to go to the module and reassign positions to the new template.
{ "pile_set_name": "StackExchange" }
Q: How could I remove the last character from a string if it is a punctuation, in ruby? Gah, regex is slightly confusing. I'm trying to remove all possible punctuation characters at the end of a string: if str[str.length-1] == '?' || str[str.length-1] == '.' || str[str.length-1] == '!' or str[str.length-1] == ',' || str[str.length-1] == ';' str.chomp! end I'm sure there's a better way to do this. Any pointers? A: str.sub!(/[?.!,;]?$/, '') [?.!,;] - Character class. Matches any of those 5 characters (note, . is not special in a character class) ? - Previous character or group is optional $ - End of string. This basically replaces an optional punctuation character at the end of the string with the empty string. If the character there isn't punctuation, it's a no-op.
{ "pile_set_name": "StackExchange" }
Q: Creating threads from generic lambdas with references as generic parameters How can I create a thread using a generic lambda with auto parameters defined as reference? For instance, what would be the right way to achieve something conceptually equivalent to this: int vi = 0; auto lambda = [](auto &v) {}; auto t = std::thread(lambda, std::ref(vi)); gcc-5.3 complains because of the missing type: /opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/functional: In instantiation of ‘struct std::_Bind_simple<main()::<lambda(auto:2&)>(std::reference_wrapper<int>)>’: /opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = main()::<lambda(auto:2&)>&; _Args = {std::reference_wrapper<int>}]’ testLambdaCapture.cpp:52:41: required from here /opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<main()::<lambda(auto:2&)>(std::reference_wrapper<int>)>’ typedef typename result_of<_Callable(_Args...)>::type result_type; ^ /opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<main()::<lambda(auto:2&)>(std::reference_wrapper<int>)>’ _M_invoke(_Index_tuple<_Indices...>) ^ As a side question, why does it work when the generic parameter is passed by value like this: auto lambda = [](auto v) {}; auto t = std::thread(lambda, vi); A: fixed: #include <thread> int vi = 0; auto lambda = [](auto &&v) {}; auto t = std::thread(lambda, std::ref(vi)); // this works too auto rv = std::ref(vi); auto t2 = std::thread(lambda, rv); In this case, auto&& is being deduced as if it were a template argument. Hence the actual type during instantiation is either const T& or T&& as required.
{ "pile_set_name": "StackExchange" }
Q: Engine programming, is it supposed to be enjoyable? Now this might sound like a silly question and I apologize if this sort of question is not suited for stackexchange. But I am genuinely wondering this, and I feel like I get alot more proffesional awnsers on here. I'm getting into game development and have only worked solo since my study is not primairly about games. I'm only interested at 2D games atm, so am not really in need of any external engines for physics and rendering and such. So usually write the engines myself. I absolutely hate writing things as quadtree's and pathfinding algorithims, most of the time I wish I could just skip those parts and move on to programming the actual gameplay elements. Things that happen in the background don't really interest me at all. But at the same time, I can't stand it I don't know whats/how everything is happening in the background. My dislike might be explained by my weak mathematical skills. My motivation gets me through, but it can take alot of time before I grasp the technical solution behind a problem. Now is it normal to have such a dislike towards engine programming? Or do you (people who also work solo) enjoy programming the engine? A: It's not supposed to be enjoyable if you don't like it... I mean it's not the most rewarding part of the job. You don't see the results immediately, there are more "interesting things" that you could be creating right now... If you feel that way then yes it's normal, you are simply not an engine guy. You are attracted to the creative part of video games dev, not the engineering ;) I don't mean that engine work leaves no room for creativity... to the contrary! I enjoy it from time to time. But wen you like visuals and interactions, it's not the most rewarding part that's it. A: Different programmers are interested in different kinds of programming. I'm just the opposite to you - I love doing the low-level "systems" stuff, but I'm bored by coding gameplay mechanics, player controls, AI etc. It takes both engine coders and gameplay coders as well as others to make a well-rounded team. If you're working on your own I'd recommend learning to use an off-the-shelf engine. You'll save a lot of time and jump right to the things that interest you. If you're curious about how some feature works, you can always poke around in their code to get an idea what's going on, but you don't need to understand every last detail the way you would to write it yourself.
{ "pile_set_name": "StackExchange" }
Q: RavenDB: Convert a document property to another type I'm currently developing an application where I change the document a lot as I go forward (a small project to learn stuff like RavenDB). Some changes are not backwards compatible, which leads to JSON deserialization failures when I try to fetch documents. Are there some way that I convert a property from the old type to a new one during deserialization? I'm using Raven.Client.Lightweight as client library. Example: I had a property named AllProperties in a class which was a Dictionary<string,string>. I changed the type from dictionary to a class called MetadataItemCollection. A: As in any other database-solution I suggest you roll your favourite migrations-framework for such kind of things. You will probably want to do set-based operations on documents. Interesting is, Ayende is going to publish two articles about ravendb migrations in the next few days, however, google has already indexed them and you can access these articles here: RavenDB Migrations: When to execute? RavenDB Migrations: Rolling Updates Ayende, please forgive me... ;) A: If you are doing this during development, you are probably better off just deleting old docs and recreating them If you are doing this in production, take a look at the posts that dlang has posted, they discuss those specific issues.
{ "pile_set_name": "StackExchange" }
Q: How do you use Stack Overflow to find good questions to answer? Possible Duplicate: How to find the right questions that I can answer? I have favourited some tags. I see on homepage related questions getting updated regularly. But out of those questions I can find few questions that I can answer and add value. What is bad is most of those questions have already been answered or have vague answer such that I can't really figure out if that answer is what user wanted or not. Sometimes that is what user wants and I avoid adding another answer. On other questions I feel why should I spend some effort when someone else might be already composing an answer to the question. How do you solve this kind of bystander effect. How do I find questions to answer matching my expertise? BTW I have fair amount of ROR, Javascript and relevant experience so I am not really a newbie. A: Check out the Unanswered tab in some of your favorite tags. Some of the more popular tags have thousands of questions that don't have any answer at all, and even more that have a few answers that didn't receive any upvotes. Also, the Unanswered tab is sorted by votes, so the questions at the top should be high enough quality that they'd be worth a look.
{ "pile_set_name": "StackExchange" }
Q: Discrete Random Variables - Probability of X occurring Misc Hardware Software Within Warranty 15.00% 14.00% 29.00% After Warranty 10.00% 26.00% 6.00% I've come across a seemingly simplistic question in a textbook (regarding discrete random variables) and I'm wondering if there is more to it than simply reading the appropriate value from the table. The above table concerns type of complaints made at a computer shop. The question reads: i) If a complaint has been made, what is the probability the complaint was about Hardware, given that the complaint was filed within the warranty period? Is the answer really as simple as 14.00%? If not, can anybody explain or point me in the right direction to solve this? A: Hint: You might start by finding the probability that a complaint is filed within the warranty period Then you can find the conditional probability the complaint was about Hardware, given that the complaint was filed within the warranty period which is the probability that the complaint was about Hardware and was filed within the warranty period (the $14\%$ in the table), divided by the probability that the complaint was filed within the warranty period
{ "pile_set_name": "StackExchange" }
Q: java.io.FileNotFoundException while running java app from jar file Hi i am running java app from jar file. like following java -cp test.jar com.test.TestMain . in the java app i am reading csv file. which is throwing below exception. java.io.FileNotFoundException: file:\C:\Users\harinath.BBI0\Desktop\test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is incorrect) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:146) at java.util.Scanner.<init>(Scanner.java:656) at com.test.TestMain.run(TestMain.java:63) at com.test.TestMain.main(TestMain.java:43) *csv file is located in src/main/resources folder. code causes to exception is public static void main(String[] args) throws Exception { TestMain trainerScraper = new TestMain(); trainerScraper.run(); } private void run() throws JsonParseException, JsonMappingException, IOException{ String line = ""; String cvsSplitBy = ","; //Get file from resources folder ClassLoader classLoader = getClass().getClassLoader(); System.out.println(csvFile); URL url = classLoader.getResource("us_postal_codes.csv"); String fileName = url.getFile(); File file = new File(fileName); try (Scanner scanner = new Scanner(file)) { line = scanner.nextLine(); //header while ((scanner.hasNextLine())) { thanks. A: test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is incorrect) Would suggest using System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder and getResourceAsStream("/us_postal_codes.csv") // if its inside a jar
{ "pile_set_name": "StackExchange" }
Q: How to close a file handle which came from a parent process C# I'm creating an application updater module at the moment and have encountered a problem with an open file handle. The updater module is a separate program but is launched via the application which is being updated via Process.Start() when the user clicks the 'upgrade' option. One of the first things the updater does is close down the application which is being updated so that it can be reinstalled without any file access issues etc. Everything is fine up until the point where I try to remove the install directory of the application which is being updated. I get an exception which says:- The process cannot access the file because it is being used by another process. I've followed things through using the SysInternals Process Explorer utility. The updater program is initially a child process of the application which is being updated, but once the application to be updated is killed off the updater program is then its own parent. The issue appears to be that the updater program has an open file handle for the install directory of the application which is being updated. I can resolve the issue manually by closing the file handle in Process Explorer before the updater gets to the point of attempting to remove the install folder and then the exception does not get thrown. However I need some way to close this file handle in code or avoid the file handle being held by the updater program process in the first place. I've tried using the WIN32 CreateProcess method to create the process without inheriting handles, but the file handle for the install folder is still held by the updater program. Any advice would be much appreciated. A: This is probably the current directory of the process. If you start notepad with your install directory as it's current directory the same handle will appear. When you then use a file open dialog in notepad to navigate to some other directory the handle disappears. Use Environment.CurrentDirectory to change the directory or create the child with a better current directory.
{ "pile_set_name": "StackExchange" }
Q: How to get getting base_url in django template Given a website, how would you get the HOST of that in a django template, without passing that var from the view? http://google.com/hello --> {{ BASE_URL }} ==> 'http://google.com' A: This has been answered extensively in the following post There are several ways of doing it: As david542 described ** Using {{ request.get_host }} in your template ** Using the contrib.sites framework ** Please note these can be spoofed A: None of these other answers take scheme into account. This is what worked for me: {{ request.scheme }}://{{ request.get_host }}
{ "pile_set_name": "StackExchange" }
Q: shutil is not moving all files I have a folder that has photos in it, and I would like to move the photos from that folder to another. The files: IMAG_01.JPG IMAG_02.JPG IMAG_03.JPG IMAG_04.JPG IMAG_05.JPG IMAG_06.JPG IMAG_07.JPG IMAG_08.JPG IMAG_09.JPG My code: import os.path import shutil src = '/var/www/html/uploads/' dst = '/media/pi/external/Photos/' num_files = len([f for f in os.listdir(src)]) print(num_files) for x in range(num_files): print(x) picture = (os.listdir(src)[x]) print(picture) shutil.move(src+picture,dst+picture) When I run the code, it will take half of the files, and then gives me an index out of range error on picture = (os.listdir(src)[x]). The output follows: 12 0 IMAG_04.jpg 1 IMAG_07.jpg 2 IMAG_01.jpg 3 IMAG_02.jpg 4 IMAG_09.jpg 5 IMAG_08.jpg 6 Traceback (most recent call last): File "upload.py", line 11, in <module> picture = (os.listdir(src)[x]) IndexError: list index out of range I understand that it is telling me that x is not in the list, but I do not understand why that is throwing, since it should just start at 0 and go to 8. A: You are making things way too complicated. You are calling os.listdir() repeatedly, while moving files out. So your result list gets shorter and shorter each time. You start out with 12 names, but once you moved one you now get only 11 names in the directory, then 10, and by the time your x value hits 6, there are only 6 names left with indexes 0 through to 5, so os.listdir()[x] fails with an IndexError exception. You don't need a length, and you don't need to use range(). Call os.listdir() once, and loop over the results: import os.path import shutil src = '/var/www/html/uploads/' dst = '/media/pi/external/Photos/' for picture in os.listdir(src): print(picture) shutil.move(os.path.join(src, picture), os.path.join(dst, picture)) Now you have one complete list of all the names at the start, and the for loop assigns those names one by one to the picture variable. That those names are moved out no longer matters, as we don't call os.listdir() again.
{ "pile_set_name": "StackExchange" }
Q: when training simple code of pytorch, cpu ratio increased. GPU is 0% approximately I'm doing tutorial of Pytorch. Code is clearly completed. but i have one problem. It is about my CPU use ratio. If I enter into training, CPU usage ratio is increasıng up to 100%. but GPU is roughly 0%. I installed CUDA 9.2 and cudnn. and I already checked massage about torch.cuda.is_available()==True. is it OK, or my setup is wrong? A: 1.. Did you upload your model and input tensors onto GPU explicitly, showing as follow https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu For example, # Configure your device device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Upload your model onto GPU net.to(device) # Upload your tensor onto GPU inputs, labels = inputs.to(device), labels.to(device) 2.. You also can use "gpustat" to check GPU usage. https://github.com/wookayin/gpustat After installing, you can type "gpustat" on terminal If your code runs on GPU, GPU usage will increase. 3.. And check whether you've added following CUDA path into your bashrc file. Following CUDA path is general path on Ubuntu Linux, but that path can be different per OS or your setting. You can open bashrc file by typing vim ./.bashrc when your current directory is home in case where you use Ubuntu Linux. export PATH=/usr/local/cuda/bin:$PATH export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH 4.. Also check your graphic driver has been installed by typing nvidia-smi on terminal if you use Ubuntu Linux.
{ "pile_set_name": "StackExchange" }
Q: Residue of $z^4e^\frac{1}{z-1}$ at $z=1$ I'm interested in the residue of $z^4e^\frac{1}{z-1}$ at $z=1$ Following the Laurent expansion, I believe I get: $$ z^4\sum_{n=0}^\infty \frac{1}{n!} \left(\frac{1}{z-1}\right)^n = z^4\left(1+\frac{1}{z-1} +\frac{1}{2!(z-1)^2}+\frac{1}{3!(z-1)^3}...\right) $$ I have been told through lectures to find the $z^{-1}$ term, however, in this case, I'm not too sure how to proceed A: Hint: $z^4=(1+z-1)^4=1+4(z-1)+6(z-1)^2+4(z-1)^3+(z-1)^4$. Multiplying, we get $1/5!+1/3!+1+2+1=501/120=167/40$ as the residue.
{ "pile_set_name": "StackExchange" }
Q: Move the absolute value in limits Is it true that I can pull out the absolute value in a limit such that: $|\lim_{x\to a} f(x)|=\lim_{x\to a} |f(x)|$. Both quantities are non-negative and I can't see how moving the operator would change the value of the limit, but maybe there is a counterexample? A: A counterexample can be made if the left limit does not exist. For example, take $$f(x)=\begin{cases}1 & x\in\mathbb Q\\ -1 & x\in\mathbb R\setminus\mathbb Q\end{cases}$$ Then, clearly, $$\lim_{x\to 0} f(x)$$ does not exist (and so neither does $$\left|\lim_{x\to 0} f(x)\right|$$ but on the right, $$\lim_{x\to 0} |f(x)| = \lim_{x\to 0} 1 = 1$$ However, if the limit exists, then yes, the equality holds (because $x\mapsto |x|$ is a continuous function).
{ "pile_set_name": "StackExchange" }
Q: appending regex matches to a dictionary I have a file in which there is the following info: dogs_3351.txt:34.13559322033898 cats_1875.txt:23.25581395348837 cats_2231.txt:22.087912087912088 elephants_3535.txt:37.092592592592595 fish_1407.txt:24.132530120481928 fish_2078.txt:23.470588235294116 fish_2041.txt:23.564705882352943 fish_666.txt:23.17241379310345 fish_840.txt:21.77173913043478 I'm looking for a way to match the colon and append whatever appears afterwards (the numbers) to a dictionary the keys of which are the name of the animals in the beginning of each line. A: Actually, regular expressions are unnecessary, provided that your data is well formatted and contains no surprises. Assuming that data is a variable containing the string that you listed above: dict(item.split(":") for item in data.split())
{ "pile_set_name": "StackExchange" }
Q: How to set the messages.xlf output location when running Angular i18n? I'm using angular's i18n tools and have moved the messages.xlf output to a different folder than the default location (a new directory: \app\locale), as suggested. When I rerun >npm run i18n even in the newly added app/locale directory, the messages.xlf file is output to the default location. How can I specify where the output messages.xlf file is output to prevent having to move it around each time I regenerate it? A: You can add a new option to your tsconfig.json to tell the angular compiler where to output the file. { "compilerOptions": { //your normal options... }, "angularCompilerOptions": { "genDir": "./app/locale" } } When you execute the i18n program make sure to include the tsconfig.json location. node_modules\.bin>ng-xi18n -p ../../src/tsconfig.json
{ "pile_set_name": "StackExchange" }
Q: What is Replacement of Trigger in SQL Server 2012 Recently I had attended an interview for SQL Server. In SQL Server 2008 we have triggers to trigger the action while event occurs on table. What is replacement for triggers in SQL Server 2012? Anyone knows please share.... A: By luck, I spoke with one Dba. He told that t answer is CDC(Change Data Capture).. I am sorry this option is available @2008 itself.... This url refers http://www.codeproject.com/Articles/166250/Microsoft-SQL-Server-Change-Data-Capture-CDC
{ "pile_set_name": "StackExchange" }
Q: how to add string into JsonArray I am trying to add string values in JsonArray and after that create Json String to send it on server. I was searching on google but I couldn't find anything helpful. Could anyone tell me how to this? Thanks JSONArray list = new JSONArray(); list.put("Hello"); list.put("Hey"); After that I want create JSONString A: Simple: JSONArray list = new JSONArray(); list.put("Hello"); list.put("Hey"); String jsonString = list.toString() according to docs it should result in "["Hello", "Hey"]"
{ "pile_set_name": "StackExchange" }
Q: Is it possible to keep same md5 checksum of a file after content modification? Many websites put md5 checksums for downloadable files so users can verify the string against their downloaded file's md5. Can someone modify the content of the original file but still keeping the original md5 checksum? A: Yes, it is possible to modify a file without changing the MD5 checksum. That is why it is important to move to more secure hashing algorithms like SHA-256. For security purposes, MD5 and SHA-1 are pretty much considered to be deprecated. Wikipedia has a section about MD5's security issues: https://en.wikipedia.org/wiki/MD5#Security
{ "pile_set_name": "StackExchange" }
Q: Can I get back the original column order (on a button click) when a user reorders the columns? Please have a look at the following code. When I click the Revert to org order button the columns should be reordered to original datagrid order. Is there any possibility? Please help me...... //The following is my code <Window x:Class="GridTextBox.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" WindowState="Maximized" Loaded="MainWindow_Loaded" Background="Gray"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="*"/> <RowDefinition Height="30"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width=".25*"/> <ColumnDefinition Width=".25*"/> <ColumnDefinition Width=".25*"/> <ColumnDefinition Width=".25*"/> </Grid.ColumnDefinitions> <DataGrid ColumnReordered="datagrid1_ColumnReordered" GotFocus="datagrid1_GotFocus" LoadingRowDetails="datagrid1_LoadingRowDetails" Grid.ColumnSpan="3" Background="Gray" Grid.Row="1" Height="auto" Name="datagrid1" AutoGenerateColumns="False" Width="440" VerticalAlignment="Center" SelectionChanged="datagrid1_SelectionChanged"> <DataGrid.Columns> <DataGridTemplateColumn Header="Empid"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Name="txtEmpid" Text="{Binding Empid}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Empname"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding Empname}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <TextBox Text="{Binding Empname}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Empaddress"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding Empaddress}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="EmpCity"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding EmpCity}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Empstate"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding EmpState}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="EmpCountry"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Text="{Binding EmpCountry}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <Button Grid.Row="2" Grid.Column="2" Height="30" Content="Insert Employees" Click="Button_Click"></Button> <Button Grid.Row="2" Grid.Column="1" Height="30" Content="Revert to org order" Name="btn" Click="btn_Click"></Button> </Grid> </Window> A: You can keep in memory a small dictionary and on button click use the DisplayIndex Property of each column to reset the original view. EDIT: Add an example XAML <Grid> <Grid.RowDefinitions> <RowDefinition Height="281*" /> <RowDefinition Height="30*" /> </Grid.RowDefinitions> <DataGrid Name="datagrid1" ItemsSource="12345567" Loaded="datagrid1_Loaded"> <DataGrid.Columns> <DataGridTextColumn Header="Col1" Binding="{Binding}" /> <DataGridTextColumn Header="Col2" Binding="{Binding}" /> <DataGridTextColumn Header="Col3" Binding="{Binding}" /> <DataGridTextColumn Header="Col4" Binding="{Binding}" /> <DataGridTextColumn Header="Col5" Binding="{Binding}" /> </DataGrid.Columns> </DataGrid> <Button Grid.Row="1" Content="Reorder" Click="Button_Click"/> </Grid> and in your code behind: private Dictionary<int, string> originalOrder; private void datagrid1_Loaded(object sender, RoutedEventArgs e) { if (originalOrder == null) originalOrder = new Dictionary<int, string>(); //I will save the header content as a string, //but you can save anything you want to identify each column datagrid1.Columns.ToList().ForEach(c => originalOrder.Add(c.DisplayIndex, c.Header.ToString())); } private void Button_Click(object sender, RoutedEventArgs e) { originalOrder.ToList().ForEach(k => { datagrid1.Columns.FirstOrDefault(c => c.Header.ToString() == k.Value).DisplayIndex = k.Key; }); }
{ "pile_set_name": "StackExchange" }
Q: Rewriting URL with htaccess I am trying to rewrite the url to my wordpress theme folder as so: Actual URL: http://www.mydomain.com/wp-content/themes/mytheme/style.css Trying to rewrite to: http://www.mydomain.com/mytheme/style.css Here is what I have in my .htaccess file which is in my home folder, and is not working: RewriteEngine On RewriteRule ^mytheme/(.*) /wp-content/themes/mytheme/$1 [QSA,L] What am I doing wrong? A: #Begin WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteRule ^mytheme/(.*) /wp-content/themes/mytheme/$1 [QSA,L] RewriteRule ^plugins/(.*) /wp-content/plugins/$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> #End WordPress This is how your htaccess should look like. But you need to tell wordpress to use the new Urls. I recommend that you check out this github repo Roots Boilerplate->lib Especially files rewrites and relative urls.
{ "pile_set_name": "StackExchange" }
Q: How do you make CSS repeat-y repeat over a dynamic height? I have the following HTML and CSS: <div class="content"> <div class="leftbg"></div> <div class="innercontent"><p>Some content goes here</p></div> <div class="rightbg"></div> </div> .content { overflow: hidden; } .leftbg { background: url("./leftbg.png") repeat-y scroll top left transparent; margin-left: 0; float: left; width: 10px; } .innercontent { width: 600px; float: left; margin-left: 0; } .rightbg { /* similar to left bg except for the right side */ } The problem that I am having is the leftbg image is only repeating until it reaches the height of the paragraph in the innercontent div. I am accessing a database to grab the content for the innercontent div and hence the content will be of variable height. Is there any way to make it so that it repeats until it reaches the bottom of the leftbg (and rightbg) div? What I mean by that is for it to repeat until it is at the bottom of the innercontent div without setting the height as static (e.g. height: 200px;) because the height will be variable. A: This equal height column layout tutorial from smashing magazine might help you. With lot of explanation of all the whys.
{ "pile_set_name": "StackExchange" }
Q: How to limit in netty length of websocket frame received by server I am implementing a WebSocket service using netty 3.4. I need to limit the frame size to avoid DoS attacks with very very long frames. I want the connection to be dropped after 32KB of data, even if the frame was not finished yet and it was not passed to my Handler. Is there any way to do that? A: Given the code as it stands at the moment, doesn't look like it at the moment. You will have to extend WebSocket08FrameDecoder and change the code in toFrameLength(). If I get a chance, I'll put in a pull request for the next release.
{ "pile_set_name": "StackExchange" }
Q: Referencing resources.resw in AppBar-Button I need to reference a text from the resources.resw-file in a AppBar-Button, but as it is set as AutomationProperties.Name="". I can not just add it in the resources.resw as AppBarSearch.AutomationProperties.Name, so how can I reference it? A: AutomationProperties.Name is an attached property and you need to handle it differently, i.e. you need to include its namespace in the resource key: AppBarSearch.[using:Windows.UI.Xaml.Automation]AutomationProperties.Name
{ "pile_set_name": "StackExchange" }
Q: What does "do the 45" mean? As a non native speaker I'm quite stumped trying to understand what "do the 45" means in this song by Ryan Shaw that has the same title. A few searches didn't help at all, so I wonder if this is some kind of lesser known idiom or obscure reference that I don't get just because it's a cultural thing. I know that 45 could refer to a revolver, but the song doesn't sound like it has anything to do with firearms. A: Given the context, he seems to be referring to a .45 caliber hand gun. It may be important to note that there have been many songs over the years that set a serious topic to upbeat music. One of the most famous examples is Electric Avenue by Eddy Grant. The lyrics as I hear them: 45, yeah, do the 45. (x2) Well, you heard about the shotgun, how bad it's gonna be. I got news for you baby; just listen to me. You're twining and whining, like all the rest. Well, I got my 45, and I'll create a big mess. 45, yeah, do the 45. (x2) Well, here comes little sister; she's twisting up a storm. She's doin' the 38 and she's waving her arms. Well come on, young girl, and dance with me. I've got my 45, and I'm as bad I can be. Now don't just stand there lookin' so dumb. Act like Jesse James and have you some fun. Everybody's dancing and moving all around. They've got their 45s and they're the best in town. 45, yeah, do the 45. (x2) Come on girl, do the 45, twist up a storm baby, do the 45. Whining and twining, do the 45. Hey, hey hey. 45, do the 45. (repeats) Interpretation of bold lines: Well, you heard about the shotgun, how bad it's gonna be. : A shotgun is another type of gun. Shootings are considered a bad thing. Well, I got my 45, and I'll create a big mess : Again, shootings are bad. They create a "mess" in the literal sense that bodies and crime scenes will need to be cleaned-up, as well as political and social fallout (riots, protests, etc.) She's doin' the 38 : A "38" commonly refers to a .38 caliber hand gun. This is what sealed the hand gun analogy for me. A 45 can also be a record, but there are no 38 records. Act like Jesse James and have you some fun. : Jesse James was an infamous outlaw in "Old West" of the United States. He was known to be violent and to have murdered many people. Other uses of "45" outside of a firearm: "45" record: The most common form of the vinyl single is the 45 or 7-inch. The names are derived from its play speed, 45 rpm, and the standard diameter, 7 inches (18 cm). "Colt 45": Refers to cheap malt liquor, and is made even more famous in the song Crazy Rap by Afroman (caution explicit lyrics).
{ "pile_set_name": "StackExchange" }
Q: Error thrown when I click out of ListModel When I click on a button (e.g mainBtn) then select a String within the mealList and then click on another button (e.g starterBtn) an error is thrown within the console. If someone could nudge me in the right direction and show me why the code is throwing an error message that would be much appreciated. public void updateLabel(menulist model) { int selectionNumber = mealList.getSelectedIndex(); if (selectionNumber == -1){ } else { Food menulist = (Food) mealList.getSelectedValue(); Food itemFood = (Food) ((menulist) model).getElementAt(selectionNumber); Error Message Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Vector.elementData(Vector.java:734) at java.util.Vector.elementAt(Vector.java:477) at javax.swing.DefaultListModel.getElementAt(DefaultListModel.java:89) at MenuPage.updateLabel(MenuPage.java:317) A: You are calling to an invalid index, whenever you chose the item, you must not be establishing what index value you chose, therefore, the button will register as -1 because of the release of the button, you want to have the index value of the item of choice included with the ActionEvent
{ "pile_set_name": "StackExchange" }
Q: Translating American time zones to German Three parts to my question: In Germany, would our American time zones still be referred to as things like Mountain Daylight Time or do other countries have different names for regions but keep abbreviations? if so, then what are the translations fo In software, if (for example) an employee of an American business had to adjust something to an American time zone, would they be familiar with reading something like Pacific Daylight Time(PDT)? What would be the best translations for the following? Eastern Standard Time (EST) Eastern Daylight Time (EDT) Central Standard Time (CST) Central Daylight Time (CDT) Mountain Standard Time (MST) Mountain Daylight Time (MDT) Pacific Standard Time (PST) Pacific Daylight Time (PDT) I got the actual above list from a translator, they seemed incomplete as for "Central European Summer Time" he gave me Mitteleuropäische Sommerzeit (MESZ) A: Dealing with far-away time zones is almost always an international matter, and therefore, time zone names are almost always given in English (because international communications prefer it) or in the language of the nation in question. Almost never are U.S. time zone names translated to German, French etc. So what do you do? In contexts where the actual value matters, you should give the abbreviation and the offset, e.g. "PST (UTC -9)". Adding "Pacific Standard Time" adds little information, just a little local color - this is usually not necessary in business communication. If you do use time zone names in German literary contexts, it's probably still not a good idea to render "Mountain Standard Time" either into "Mountain Standard Time" (which sounds grating) or "Standardbergzeit" (which no one will understand). You should recast the expression and speak of something like "...die lokale Zeit von Denver". Note that when you speak of a "Daylight Time" variant, you can and should use the German word "Sommerzeit", since this is a well-known concept and term. A: Curiously, German speaking people seem to only want to convey the time difference relative to Washington or New York. For that the well established Ostküstenzeit can be used. The other timezones are just not needed that much to necessitate an elegant word for it. If looking at established examples in information technology use, then IBM lists their solution as well: Zeitzonen-IDs, die für die Eigenschaft "user.timezone" angegeben werden können HST -10 : 00 Hawaii-Standardzeit Pazifik/Honolulu -10 : 00 Hawaii-Standardzeit QN1000UTCS Amerika/Anchorage -9 : 00 60 Alaska-Standardzeit AST -9 : 00 60 Alaska-Standardzeit QN0900AST PST -8 : 00 60 Pazifik-Standardzeit QN0800PST Amerika/Los Angeles -8 : 00 60 Pazifik-Standardzeit Amerika/Boise -7 : 00 60 Mountain-Standardzeit PNT -7 : 00 60 Mountain-Standardzeit MST -7 : 00 60 Mountain-Standardzeit QN0700MST, Amerika/Chicago -6 : 00 60 Zentral-Standardzeit (Nordamerika) CST -6 : 00 60 Zentral-Standardzeit (Nordamerika) QN0600CST, QN600S Amerika/New York -5 : 00 60 Ostküsten-Standardzeit (Nordamerika) EST -5 : 00 60 Ostküsten-Standardzeit (Nordamerika) QN0500EST But my guess is that many people will neither know what the timezone means, nor know what the abbreviation would entail. So I think it is less important to use any variable at all. Use the abbreviation, but give the handy +/- in actual difference to UTC/GMT or the current timezone. Most should be able to do the math then quickly.
{ "pile_set_name": "StackExchange" }
Q: Pattern Matching and Delete the whole line I want to delete all the Lines of File 1, if Column1 of File1 matches exactly with Column 1 File2. File 1: r001:21:10 21 AAAAAATTTGC * = XM:21 r002:21:10 21 YAAAATTTGC * = nM:21 r001:21:10 21 TTAAAATTTGC * = XM:21 r0012:21:10 21 LLAAAATTTGC * + XM:21 r001:21:10 21 AAAAAATTTGC * = GM:21 File2: r001:21:10 r001:21:20 r002:41:36 r002:41:99 r002:41:87 r0012:21:1 Expected Output: r002:21:10 21 YAAAATTTGC * = nM:21 r0012:21:10 21 LLAAAATTTGC * + XM:21 A: You can use this awk: $ awk 'FNR==NR {a[$i]; next}; !($1 in a)' f2 f1 r002:21:10 21 YAAAATTTGC * = nM:21 r0012:21:10 21 LLAAAATTTGC * + XM:21 Explanation FNR==NR {a[$i]; next} it reads the first file and saves the contents into the a array. !($1 in a) while reading the second file, it checks if the first field is in the a array. If not, prints the line.
{ "pile_set_name": "StackExchange" }
Q: How to assign value of a string variable to a string variable of a structure in c++? I am trying to assign the value of a string variable to another string variable of a structure. But gdb gives an runtime error. The error is as follows: Program received signal SIGSEGV, Segmentation fault. 0xb7f7c8f8 in std::string::assign(std::string const&) () from /usr/lib/i386-linux-gnu/libstdc++.so.6 My C++ program is: #include<iostream> #include<stdlib.h> #include<string> typedef long unsigned int LUI; using namespace std; struct graph { string string_node; LUI node; struct graph *link; }; struct graph *abc[30]; struct graph *t; string x; int main() { t = (struct graph *) malloc(sizeof(struct graph *)); x = "abc"; t->string_node = x; t->link = NULL; abc[0] = t; cout << "Value is " << abc[0]->string_node << endl; cout << "end"; return 0; } Please help me to store the value of x into t->string_node. Thanks in advance.. A: t = (struct graph *) malloc(sizeof(struct graph *)); graph is a class. It contains C++ classes, specifically it contains a std::string. All C++ classes must be constructed in dynamic scope using the new operator. They cannot be constructed with the C library function malloc(), which knows absolutely nothing, whatsoever, about C++ classes. Doing so results in undefined behavior (not to mention that your malloc-ed size is wrong, anyway). Now that you're writing C++ code, you need to completely forget that malloc(), realloc(), and free() ever existed, and always use new and delete.
{ "pile_set_name": "StackExchange" }
Q: Multiple SVG radial gradients How to put multiple SVG radial gradient to an SVG element. A fiddle that i have created for this http://jsfiddle.net/4p9CK/. I tried the following options but with no success. - <rect x="20" y="20" width="100" height="100" style="fill: url(#center_origin),url(#center_origin2); stroke: black;"/> - <rect x="20" y="20" width="100" height="100" style="fill: url(#center_origin, #center_origin2); stroke: black;"/> A: No. SVG doesn't support multiple paint servers on one element (a "paint server" is a gradient, pattern etc). You would need to use multiple elements and simulate your desired effect by using opacity or filters - or by splitting up your shape geometrically.
{ "pile_set_name": "StackExchange" }
Q: How to fix 'Hooks can only be called inside the body of a function component' error in React custom hook? [SOLVED] I am trying to create a custom hook to use in the project. It should submit a payload and return a result, but I am getting this error: Uncaught Invariant Violation: Hooks can only be called inside the body of a function component. The error happens in the console when the page loads. I don't even need to click on the button. This is my custom hook (useSubmit): import { useState } from 'react' export const useSubmit = submitFunction => { const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const handleSubmit = async args => { try { setLoading(true) setError(null) return submitFunction(...args) } catch (error) { setError(error) } finally { setLoading(false) } } return [handleSubmit, loading, error] } This is the relevant code from my functional component: import React from 'react' import { useSubmit } from '../../../../../../../utils/custom-hooks/use-submit' import { createGameRules } from '../../../../../../services/game/rules' export const GameRules = () => { const [handleSubmit, loading, error] = useSubmit(createGameRules) // Some code here const saveGameRules = async () => { const payload = { title: 'Some title', rules: 'Some description' } const savedGameRule = await handleSubmit(payload) console.log(savedGameRule) } // More code here return ( <button onClick={() => saveGameRules()}>Save</button> ) Here is my service, to post the data to the endpoint and return the result: import axios from '../../axios' export const createGameRules = async payload => { const { title, rules } = payload const { data: { data } } = await axios({ method: 'POST', url: '/game/rules', data: { title, rules } }) return data } What am I missing? Thanks for the help!! [EDIT] The problem was that there was another package.json file in the project. Because the custom hook was in the hierarchy of this other package.json, the application was trying to use another version of React. The solution was to move the custom hook to a more internal level, next to the appropriate package.json, so everything worked. The clue was at the link https://reactjs.org/warnings/invalid-hook-call-warning.html cited by some, but I didn't know about this other package.json Thank you all for your help. A: There are 3 reasons that this error occurs: using hooks wrongly - this doesn't seem to be your case Duplicate React loaded Mismatched Dom/React libraries I would guess it would be 2 or 3 for you - check you are using the latest versions of react and react-dom. https://reactjs.org/warnings/invalid-hook-call-warning.html
{ "pile_set_name": "StackExchange" }
Q: On radio button click, show/hid divs with dynamicaly changed IDs or classes <div class=""> @foreach($result->package as $package) //listing all packages from DB using Laravel's Blade template <input id="id_radio{{$package->id}}" type="radio" value="{{$package->id}}" name="radio" >{{$package->name}} <br> <div class="" id="package{{$package->id}}"> @foreach($package->price_option as $price_option) Price Option: <input type="radio" value="{{$price_option->id}}" name="radio">{{$price_option->id}} <br> <div class=""> @foreach($price_option->values as $value) Values: {{$value->value}} <br> @endforeach </div> @endforeach </div> @endforeach </div> Page Source: <div class=""> <input id="id_radio22" type="radio" value="22" name="radio" >Package 1 <br> <div class="" id="package22"> Price Option: <input type="radio" value="75" name="radio">75 <br> <div class=""> Values: Dummy text <br> Values: Dummy text 2 <br> </div> Price Option: <input type="radio" value="78" name="radio">78 <br> <div class=""> Values: Dummy text <br> Values: Dummy text 2 <br> </div> </div> <input id="id_radio23" type="radio" value="23" name="radio" >Package 2 <br> <div class="" id="package23"> Price Option: <input type="radio" value="76" name="radio">76 <br> <div class=""> Values: a <br> Values: b <br> Values: c <br> </div> </div> </div> What I need is to show all price options as radio buttons when I click on, for example, package 1 radio button, and to show all price options as radio buttons for package2 but at the same time hide price options of Package1. Then for all Price Options that I click to show all Values that belongs to that Price Option. Currently dont have any CSS or JQuery/JavaScript code A: Working fiddle. Try to hide all the divs (that have id start with package) bellong to the other radio buttons then show just the div belong to the clicked one : $('div[id^="package"]').hide(); $('body').on('click','input[id^="id_radio"]',function(){ $('div[id^="package"]').hide(); $('#package'+$(this).val()).show(); }); $('div[id^="price_option_div"]').hide(); $('body').on('click','.price_option',function(){ $('div[id^="price_option_div_"]').hide(); $("#price_option_div_"+$(this).val()).show(); }); Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Xamarin Android - BroadcastReceiver Issue - Unable to instantiate receiver My application is using a Geofencing Service to send http requests to an API when a user enters and exits a Geofence. I need that Service to be stopped or started depending on if the user has GPS access or not. I will also need this to occur after the application has been completely closed as disabling location service will crash the background service. The problem is that whenever I enable or disable Location Services the application crashes with this stack trace: java.lang.RuntimeException: Unable to instantiate receiver com.MyCompany.MyApp.GeofenceBroadcastReceiver: java.lang.ClassNotFoundException: Didn't find class "com.MyCompany.MyApp.GeofenceBroadcastReceiver" on path: DexPathList[[zip file "/data/app/com.MyCompany.MyApp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.MyCompany.MyApp-1/lib/arm, /vendor/lib, /system/lib]] Interestingly, this only occurs when Location Services is changed, not when Airplane mode is changed. In either case OnReceive in my BroadcastReceiver is being called. I did manually edit my AndroidManifest.xml file. Not sure if that might have something to do with it. According to this it might. AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.MyCompany.MyApp" android:versionCode="1" android:versionName="1.0" android:installLocation="auto"> <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="19" /> <application android:label="MyApp" android:icon="@drawable/Icon"> <meta-data android:name="come.google.android.maps.v2.API_KEY" android:value="SomeKeyValueForGoogleAPI" /> <receiver android:name=".GeofenceBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.ACTION_AIRPLANE_MODE_CHANGED"></action> <action android:name="android.intent.action.ACTION_BOOT_COMPLETED"></action> <action android:name="android.location.PROVIDERS_CHANGED" /> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.LOCATION_HARDWARE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.ACCESS_LOCATION" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_GPS" /> </manifest> GeofenceBroadcastReceiver.cs // using blah blah blah namespace MyApp.Geofence { [BroadcastReceiver] [IntentFilter(new[] { Intent.ActionBootCompleted, Intent.ActionAirplaneModeChanged, LocationManager.ProvidersChangedAction })] public class GeofenceBroadcastReceiver : BroadcastReceiver { public GeofenceBroadcastReceiver() { } public override void OnReceive(Context context, Intent intent) { LocationManager leManager = (LocationManager)context.GetSystemService(Context.LocationService); bool gpsEnabled = leManager.IsProviderEnabled(LocationManager.GpsProvider); bool networkEnabled = leManager.IsProviderEnabled(LocationManager.NetworkProvider); if (gpsEnabled) { // bool from the application preferences if (Preferences.getBool(Preferences.GEOLOCATION)) GeofenceApp.startService(); } else GeofenceApp.stopService(); } } } MainActivity.cs // things... private GeofenceBroadcastReceiver receiver; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //... // some other stuff //... receiver = new GeofenceBroadcastReceiver(); RegisterReceiver(receiver, new IntentFilter(Intent.ActionBootCompleted)); RegisterReceiver(receiver, new IntentFilter(LocationManager.ProvidersChangedAction)); RegisterReceiver(receiver, new IntentFilter(Intent.ActionAirplaneModeChanged)); } A: Gah, I figured it out. I had to actually remove <receiver android:name=".GeofenceBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.ACTION_AIRPLANE_MODE_CHANGED"></action> <action android:name="android.intent.action.ACTION_BOOT_COMPLETED"></action> <action android:name="android.location.PROVIDERS_CHANGED" /> </intent-filter> </receiver> from my manifest.
{ "pile_set_name": "StackExchange" }
Q: Bind command with parameters In my Xamarin iOS project, I want to bind a button to a ICommand with a parameter. View: var set = this.CreateBindingSet<MyView, MyViewModel>(); set.Bind(Button1).To(vm => vm.EditCommand).WithConversion(new MvxCommandParameterValueConverter(), 1); set.Apply(); ViewModel: private readonly ICommand editCommand; public MyViewModel() { editCommand = new BaseMvxCommand<int>(DoEditPhoto); } public ICommand EditCommand { get { return editCommand; } } private void DoEditPhoto(int imageNum) { // enter code here } When I hit the button, I am not able to execute the DoEditPhoto(). Am I binding in a wrong way? Can anyone help me out? A: Yes your binding is technically not wrong. However, you don't need a converter to pass a parameter to a bound ICommand. For this you can use CommandParameter in your chain instead: set.Bind(Button1).To(vm => vm.EditCommand).CommandParameter(ViewModel.ImageNumber);
{ "pile_set_name": "StackExchange" }
Q: Comparing a variable to multiple values Quite often in my code I need to compare a variable to several values : if ( type == BillType.Bill || type == BillType.Payment || type == BillType.Receipt ) { // Do stuff } I keep on thinking I can do : if ( type in ( BillType.Bill, BillType.Payment, BillType.Receipt ) ) { // Do stuff } But of course thats SQL that allows this. Is there a tidier way in C#? A: You could do with with .Contains like this: if(new[]{BillType.Receipt,BillType.Bill,BillType.Payment}.Contains(type)){} Or, create your own extension method that does it with a more readable syntax public static class MyExtensions { public static bool IsIn<T>(this T @this, params T[] possibles) { return possibles.Contains(@this); } } Then call it by: if(type.IsIn(BillType.Receipt,BillType.Bill,BillType.Payment)){} A: There's also the switch statement switch(type) { case BillType.Bill: case BillType.Payment: case BillType.Receipt: // Do stuff break; } A: Assuming type is an enumeration, you could use the FlagsAttribute: [Flags] enum BillType { None = 0, Bill = 2, Payment = 4, Receipt = 8 } if ((type & (BillType.Bill | BillType.Payment | BillType.Receipt)) != 0) { //do stuff }
{ "pile_set_name": "StackExchange" }
Q: Are there any remedies for abusive or insulting behavior by agents executing a search warrant? Suppose I am a particular person who maintains a clean and orderly residence. I have a sign inside my front door asking visitors to put booties over their shoes before entry. Now some LEOs show up with a search warrant for the residence. Is there any obligation for them to respect my property and order? For example, it would not hinder their search to wear booties over their shoes while indoors. Or to wear gloves while rifling through my drawers. It might take some extra time, but if they were respectful they could carefully remove the contents and return them in substantially the same order as originally found. What I have heard is that the reality is agents are usually careless, and often abusive in executing searches: E.g., they don't just look through drawers, but if they're in a foul mood they dump their contents on the floor and then stomp through them. They may even use this to threaten the occupants: e.g., "Tell us where X is or we'll make this messy." The only legal requirement I am aware of is that they "reasonably" secure the premises before leaving, meaning that if they broke down an exterior door or window they have to board it up. One real-world example I recently reviewed was featured in Wired: An interagency task force with a no-knock warrant broke down an unlocked door and, before they were done, thought it amusing to leave a dildo they found propped conspicuously on a bed. In practice are there any restraints on such misbehavior in the execution of warranted searches? Are there routine remedies for damage incurred in the course of a search? And do any remedies exist for non-material damages – e.g., insult to the dignity or property searched as suggested at the beginning of this question? A: There are two separate questions here, it seems to me. First: are law enforcement officers required to respect your house rules and avoid making a mess? At least in the United States, the answer is unequivocally no. If the only "damage" suffered is that you need to sweep the floor, or put your clothes back in drawers, that's not the police's problem. You have not suffered any damages that a court is going to reimburse, and your best case scenario, even if you win a suit against the police, is an award of one dollar as nominal damages. Second: are law enforcement officers required to reimburse you for any physical damage they caused while executing the search warrant? The answer here is tricker, and depends on the search warrant. If the warrant is invalid, then the answer is yes. But remember: just because, for example, the cops are looking for the guy you bought your house from, who moved out a month ago, that doesn't mean the warrant is "invalid." Just because the cops got a bad tip, or suspected you wrongly, or were in some other way wasting their time--as long as the warrant is technically proper and they were able to convince a judge it was reasonable, the warrant is valid. Even if the warrant is invalid, you may need to sue the police to get anything reimbursed. If the warrant is valid, in practical terms, you will almost certainly need to sue the police to recover anything, and you will have to show the Court that the police's actions that damaged your property were so extreme that they were outside the reasonable scope of the warrant. For instance: the warrant is for a large item, like a stolen car: the police cannot smash holes in your walls to make sure the car isn't hidden inside. If they're looking for drugs, they may be able to. If the officers' actions are consistent with the scope of the warrant, then you are not going to recover anything. The warrant is, basically, permission from a judge to enter your home and perform those actions, and they will not be liable for them. A number of relevant cases are discussed in this article: http://www.aele.org/law/2010all01/2010-1MLJ101.pdf A: TL;DR: No. But maybe there should be. Here is a Law Review article addressing the sub-question: Does the Fifth Amendment Mandate Compensation When Property is Damaged During the Course of Police Activities? The author concludes that in practice the remedies offered seem to fall short of the Constitutional mandate: The Fifth Amendment of the United States Constitution, along with similar provisions in state constitutions, forbids the taking of private property by the government for a public use without just compensation. Despite this protection, many courts have denied takings claims made by innocent third party landowners when police officers caused damage to their property during the course of executing their official duties. These courts held that the damage was not for a "public use" in the narrow sense, and have refused to analyze the claims under takings jurisprudence. This narrow view of "public use" ignores the fact that society as a whole benefits from the police activity, including any resulting damage to property, while the innocent, individual owner alone is forced to bear the burden. This Note argues that a broader interpretation of "public use" is required to redistribute justly and fairly the costs of such burdens to the society that benefits from them in order to comport with the mandate of the Fifth Amendment.
{ "pile_set_name": "StackExchange" }
Q: JPanel on top of JLabel Good day! Is it possible to add a JPanel on top of a JLabel? I would like my JFrame to have a background image and in order to this, i used this code (based from past stackoverflow answers): setLocation(150,50); setSize(700,650); setVisible(true); JLabel contentPane = new JLabel(); contentPane.setIcon(new ImageIcon("pics/b1.jpg")); contentPane.setLayout( new BorderLayout()); setContentPane( contentPane ); Now my problem is, I cannot put a panel on my JFrame because of the JLabel background. Please help. Thanks. A: To create a background image for a JFrame, I recommend that you draw the image in the paintComponent method of a JPanel, and then add this JPanel to the contentPane BorderLayout.CENTER which has it fill the contentPane. You may even want to set the JPanel's preferredSize to be that of the Image. Then you can add any components you'd like to the image panel, and don't have to worry about trying to add comopnents to a JLabel which seems bass ackwards to me. For example here's a program that does this but slightly different. It creates an ImagePanel object, a JPanel that draws an image and sizes itself to the image and then places it in a JScrollPane which is then added to the contentPane, but you can just get rid of the JScrollPane and put your image JPanel directly in the contentPane instead: import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.*; public class BigDukeImage { public static final String IMAGE_PATH = "http://" + "duke.kenai.com/nyanya/NyaNya.jpg"; private static final Dimension SCROLLPANE_SIZE = new Dimension(900, 700); private static void createAndShowUI() { Image image = null; try { URL url = new URL(IMAGE_PATH); image = ImageIO.read(url); // JLabel label = new JLabel(new ImageIcon(image)); ImagePanelA imagePanel = new ImagePanelA(image); JScrollPane scrollpane = new JScrollPane(); // scrollpane.getViewport().add(label); scrollpane.getViewport().add(imagePanel); scrollpane.setPreferredSize(SCROLLPANE_SIZE); JFrame frame = new JFrame("Big Duke Image"); frame.getContentPane().add(scrollpane); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); JScrollBar vertSBar = scrollpane.getVerticalScrollBar(); JScrollBar horzSBar = scrollpane.getHorizontalScrollBar(); vertSBar.setValue((vertSBar.getMaximum() - vertSBar.getVisibleAmount()) / 2); horzSBar.setValue((horzSBar.getMaximum() - horzSBar.getVisibleAmount()) / 2); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } @SuppressWarnings("serial") class ImagePanelA extends JPanel { private Image image; public ImagePanelA(Image image) { this.image = image; setPreferredSize(new Dimension(image.getWidth(null), image.getHeight(null))); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (image != null) { g.drawImage(image, 0, 0, null); } } }
{ "pile_set_name": "StackExchange" }
Q: Antivirus in Macbook Do we need to install antivirus in OS X? I'm using macbook Pro 13" currently. Which antivirus is recommended (and free)? Any other better way to protect information in OS X? A: I think you mean OS X, not iOS? MacBooks run OS X. iOS is the OS on iPhones, iPads, etc. Some good, free antivirus options for OS X are Avast and AVG. You're definitely safer if you use them. There are viruses out there for OS X. That said, it's not as needed as it is on Windows. I personally don't use any antivirus on OS X, because I feel that it slows down the system a little bit. I feel the risk is rather small, so I am willing to take it. It comes down to how careful you want to be. If you don't mind your system slowing down a little bit, and want to minimize the risk of viruses as much as possible, then get antivirus. If you don't want the small slowdown, are wise enough to spot obvious traps like fraudulent websites asking you to install programs, etc, and you feel the risk is small enough, then don't install it.
{ "pile_set_name": "StackExchange" }
Q: How print landscape multible pages in IE? How print multiple pages in landscape view for IE? My content with charts and tables, I tried: transform:rotate(-90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(Rotation=3); In Chrome i use @page and this works. A: PLease use -ms-transform for IE11. This code solved my problem: -ms-transform: rotate(270deg) translate(x, 0) scale(x), transform-origin: 0 0,
{ "pile_set_name": "StackExchange" }
Q: Preventing links with query parameters from being indexed by Google I manage a mobile version of a desktop site. The mobile site has an mdot subdomain and is served from a different server. As part of recommended best practices by Google, I've included a link on the mobile site which allows the user to opt out of the mobile experience and view the desktop site instead. In order to monitor the number of users who opt out I've appended a query parameter (?MobileOptOut=1) to the corresponding desktop link. To illustrate this: If a user on the mobile site visiting http://m.example.com/products/1127 clicks the opt out link he's taken to http://www.example.com/products/1127?MobileOptOut=1 Trouble is, Google is indexing the page with the ?MobileOptOut=1. Even more incredibly, this page actually ranks higher than the correct version without this parameter (http://www.example.com/products/1127)! Is there any way I can tell Google's crawlers to ignore pages with this parameter - using Google's Webmaster Tools? A: Google Webmaster Tools does have the ability to tell Googlebot to ignore parameters. You can tell Googlebot to ignore the parameter "MobileOptOut" anywhere it appears on your site. To do so: Navigate in Webmaster Tools to Crawl -> URL Parameters. Click the Configure URL parameters » link. Click the Add Parameter button. Put in the name: "MobileOptOut". Select No: Doesn't affect page content (ex: tracks usage) from the drop down. Click the Save button. A: Stephen Ostermiller’s answer explains how to configure it in Google Webmaster Tools (which answers your question). If you care about other search engines, too, or in addition, you could use the Canonical link type. You could specify the canonical link in a HTTP header, or you could specify it in the HTML: On http://www.example.com/products/1127?MobileOptOut=1 (*), add the following link element: <link rel="canonical" href="http://www.example.com/products/1127" /> Now supporting search engines (or other consumers) know that the document containing this element has the canonical URL http://www.example.com/products/1127, and they may use this URL (instead of the current one, i.e. the one including the parameter) in their SERPs (or whatever the consumer does). (*) You may also add the link element when the current page’s URL is already the canonical one.
{ "pile_set_name": "StackExchange" }
Q: Java: how to find all references to a specific class instance I have a Java application where a specific object is the principal reason of RAM occupation, this is ok. Application logic has to drop this object instance and create a new one. I suspect old instance is kept alive by some reference. Is there a way to list all references of a specific class instance using Eclipse debug or anything else? A: Using Eclipse Memory Analyzer plugin (org.eclipse.mat.feature.feature.group): Run your application to the point where you suspect the memory leak Open the Memory Analysis perspective in Eclipse Click "Acquire Heap Dump" button in toolbar Eclipse will need enough memory to process it, usually about the same amount as the application analyzed - you might need to change eclispe.ini to add more memory (if you don't have enough RAM you may instead create the memory dump using jvisualvm then close the app and start eclipse with increased -Xmx) Once the dump loads, you can browse it to identify the leak source (I don't recall details, but roughly - browse to your class, right click, view objects with incoming references)
{ "pile_set_name": "StackExchange" }
Q: Redux - Specify which reducer from action.type when using combineReducer So I have a reducer: const buttonReducer = (state = { buttons: [] }, action) => { switch(action.type) { case "add": { state = { ...state, buttons: [...state.buttons, action.payload] } break; } case "minus": { state = { buttons : state.buttons.filter( item => item !== action.payload ) } break; } default: break; } return state; }; Now say I have another reducer (we'll call it componentReducer) that looks similar to this, just with the code in the cases changed. Now how do I specify which reducer it should go to after I've done the combineReducers? const reducers = combineReducers({ component: componentReducer, button: buttonReducer }); Will store.component.dispatch(...) work? Or should I just simply rename the cases? Connection: const Search = connect( (store) => { return { number: store.component.number}; }) (SearchComponent); A: If you want to use the same dispatch action name for those two reducers, you could use a third variable to the dispatch like dispatch({action: 'add', reducer: 'button', payload: {..your data goes here..}}). Then you would also need to add a conditional to your reducer like this: const buttonReducer = (state = { buttons: [] }, action) => { if(action.reducer == 'button'){ switch(action.type){ ... your code goes here ... } } Although you could do the above, I recommend you stay away from that solution and stick to naming your dispatch actions according to what they do exactly, like this: ADD_BUTTON and ADD_COMPONENT instead of just add.
{ "pile_set_name": "StackExchange" }
Q: Sanitising database inputs in Clojure with Korma I'm using Korma behind a RESTful API, and it occurs to me that I'm passing user-submitted values through to my (insert)calls. Is there a nice way in Clojure to protect against SQL injection attacks? Korma generates SQL in a pretty straightforward way, so if somebody told me their name was little Bobby Tables, I'm fearful that it would hurt. A: It's my understanding that Korma always generates parameterized SQL, at least for select and insert (I have not personally tested the others) so Little Baby Tables should be fine. Carefully scrutinize how these values are being returned from the database. Sanitizing DB input does nothing to protect from CSRF/XSS, etc. When working with Clojure and DB <--> web interactions I use the rule that All system components must encode the data in a way that is safe for the next server in the chain, and logical constraints (like max search size) are checked upfront in ring-middleware. Security is a cat/mouse arms race and there is no substitute for testing these things. Go ahead and put Little Baby Tables into every query and try all the combinations of encoding and multiple encoding you can think of. Demonstrating exploits can sometimes be a rather effective way to help coworkers learn to spot these things (just don't be a jerk about it)
{ "pile_set_name": "StackExchange" }
Q: Angular 4 get function return value afrer http post request I created a controller method that sends a captcha response to google server after solving a reCaptcha and the request returns a captcha response JSON. Controller method returns true if captcha response is =="success", else it returns false. The request is sent with http POST, but the problem I'm facing is: how do I get the boolean value from controller method after receiving a resposne after POST request? Controller method: { if(ModelState.IsValid) { bool success = false; var client = new System.Net.WebClient(); string PrivateKey = "6LeiumYUAAAAAMS0kU0OYXaDK0BxHO7KJqx2zO7l"; var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, Model.RecaptchaResponse)); var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaController>(GoogleReply); success = captchaResponse.Success.ToLower() == "true" ? true : false; return Ok(success); } return BadRequest(); } [JsonProperty("success")] public string Success { get { return m_Success; } set { m_Success = value; } } private string m_Success; [JsonProperty("error-codes")] public List<string> ErrorCodes { get { return m_ErrorCodes; } set { m_ErrorCodes = value; } } private List<string> m_ErrorCodes; } POST request in DataService: //Http Post request for server-side reCAPTCHA validation checkRecaptcha(url: string, data: Object): Observable<boolean> { this.timerService.resetTimer(); return this.http.post(url, JSON.stringify(data), this.sharedService.getRequestHeaders()) .map((response: Response) => { return response.json() as boolean }) .catch((response: Response) => { return Observable.throw(response); }); } app.component.ts: resolved(captchaResponse: string) { let data = { RecaptchaResponse: captchaResponse }; let result = this.dataService.checkRecaptcha('api/recaptcha/validate', data); console.log(result); } In chrome debug I get an Observable: http://prntscr.com/ke5eeo A: The line return response.json() as boolean returns for the observable, not for your checkRecaptcha function. You will need to listen to your own checkRecaptcha's returned Observable: this.dataService.checkRecaptcha('api/recaptcha/validate', data).subscribe( (result: boolean) => console.log(result) );
{ "pile_set_name": "StackExchange" }
Q: jQuery looping .each function I've got a bunch of blockquotes that I've managed to get to fade in one after another. At the moment, after the last one has faded in and out, the function ends. But I want it to loop and start from the beginning again. Here's my code so far that works: $("div.quotes blockquote").each(function (index){ $(this).delay(4500*index).fadeIn(500).delay(4000).fadeOut(500); }); How do I get it to loop? A: One possible solution: function run() { var els = $("div.quotes blockquote"); els.each(function(i) { $(this).delay(4500 * i).fadeIn(500).delay(4000).fadeOut(500, function() { if (i == els.length - 1) run(); }); }); } run(); DEMO: http://jsfiddle.net/eDu6W/
{ "pile_set_name": "StackExchange" }
Q: Counting number of pixels with negative NDVI value within polygon using Google Earth Engine? I have made a map of vegetation loss and gain for a polygon in Google Earth Engine using NDVI and would like to calculate the area where loss occurred. I attempted to use the reducer to get the sum of pixels but I somehow need to specify the range of pixels to count only negative values where loss occurred and then total in square feet. My code is posted below, bottom part is where I'm having difficulty. Can I use the stats.get function to only return negative values somehow? var collection = ee.ImageCollection('LANDSAT/LE07/C01/T1_8DAY_NDVI'); var filtered2000 = collection.filterDate('2000-01-01', '2000-12-31'); var ndvi = filtered2000.median(); print(ndvi) var geometry = ee.FeatureCollection('ft:1peQqvrT-WKfsXa_c63gI5h0-Wo_LmBuMnrEg3C').filterMetadata('geometry_vertex_count', 'equals', 10642) Map.addLayer(ndvi, {palette: '000000, 00FF00', min: 0, max:.8}); //compare the ndvi in 2000 and 2010 var collection = ee.ImageCollection('LANDSAT/LE07/C01/T1_8DAY_NDVI'); //filter for the year 2000 var filtered2000 = collection.filterDate('2000-01-01', '2000-12-31') //filter for the year 2010 var filtered2010 = collection.filterDate('2010-01-01', '2010-12-31'); //identify the median pixel value per year for 2000 and 2010 var ndvi2000 = filtered2000.median(); var ndvi2010 = filtered2010.median(); //subtract the 2000 ndvi values from the 2010 ndvi values var difference = ndvi2010.subtract(ndvi2000).clip(geometry); //add layer with loss in red, gain in green Map.addLayer(difference, {palette: 'FF0000, 000000, 00FF00', min: -0.3, max: 0.3}); //count pixels where loss occurred var stats = difference.reduceRegion({ reducer: ee.Reducer.sum(), geometry: geometry, scale: 30, maxPixels: 1e9 }); print (stats); print('Area where vegetation loss ocurred: ', stats.get(''), 'square meters') A: In lieu of the geometry you use, here's an example with Maine. You can mask out all values you don't want, then multiply the ones you want by 0 and add 1 in order to get pixel value = 1 for each pixel that had a negative difference. Then by summing over the region you're just getting a total pixel count for where there was loss. Some simple math from there will get you the total area. var maineCounties = ee.FeatureCollection('TIGER/2016/Counties') .filter(ee.Filter.eq('NAME', 'Waldo')); print(maineCounties); var geometry = maineCounties; Map.addLayer(geometry); var negmask = function(image) { return image.updateMask(image.lt(0)); }; print("negmask function",negmask); var collection = ee.ImageCollection('LANDSAT/LE07/C01/T1_8DAY_NDVI'); var filtered2000 = collection.filterDate('2000-01-01', '2000-12-31'); var ndvi = filtered2000.median(); print(ndvi); Map.addLayer(ndvi, {palette: '000000, 00FF00', min: 0, max:.8}); //compare the ndvi in 2000 and 2010 var collection = ee.ImageCollection('LANDSAT/LE07/C01/T1_8DAY_NDVI'); //filter for the year 2000 var filtered2000 = collection.filterDate('2000-01-01', '2000-12-31') //filter for the year 2010 var filtered2010 = collection.filterDate('2010-01-01', '2010-12-31'); //identify the median pixel value per year for 2000 and 2010 var ndvi2000 = filtered2000.median(); var ndvi2010 = filtered2010.median(); //subtract the 2000 ndvi values from the 2010 ndvi values var difference = ndvi2010.subtract(ndvi2000).clip(geometry); var diff_neg = negmask(difference); var diff_neg0 = diff_neg.expression( '0 * DIFF', { 'DIFF': diff_neg }); var diff_to1 = diff_neg0.expression( '1 + DIFF', { 'DIFF': diff_neg0 }); Map.addLayer(diff_neg0, {palette: 'FF0000, 000000, 00FF00', min: -0.3, max: 0.3},"Negative differences"); Map.addLayer(diff_to1, {palette: 'FF0000, 000000, 00FF00', min: -0.3, max: 0.3},"Diff to 1"); //count pixels where loss occurred var stats = diff_to1.reduceRegion({ reducer: ee.Reducer.sum(), geometry: geometry, scale: 30, maxPixels: 1e9 }); print (stats);
{ "pile_set_name": "StackExchange" }
Q: Return 2 counted values from one function I want to create a function which returns two counted values. The values are counted by iterating over a for-loop. For example, I have an array of persons (male, female, adults, children) and I only want to find the amount of boys (child + male) and the amount of women (adult + female). In the last few years I've been writing in javascript and this is how I would have done it in javascript. function countBoysAndWomen() { var womenCounter = 0; var boysCounter = 0; for (var p of persons) { if (p.isAdult() && p.isFemale()) womenCounter++; else if (p.isChild() && p.isMale()) boysCounter++; } return {amountOfWomen: womenCounter, amountOfBoys: boysCounter}; } Now my problem is, how do I return such an object in java? Do I need to create a new class? What would you call that class? Isn't that extremely inefficient, having a complete class only for this one small purpose? What if I wanted to count a different pair of values? Would I have to create another entirely new class? Is this below actually the best way of creating such a function? private Counter countBoysAndWomen() { Counter counter = new Counter(); for (Person p:persons) { if (p.isBoy()) counter.addBoy(); else if (p.isWomen()) counter.addWoman(); } return counter; } Of course, another option would be to seperate the function into the functions "countBoys()" and "countWomen()" but then I'd have to iterate over the array twice and that wouldn't be optimal right? A: You can call below method from your main function or any method. it will return a map of desired value. in below code i am assuming that persons is a list. but if person is an array, change size() with length method. public HashMap<String,Integer> countBoysAndWomen() { int womenCounter = 0; int boysCounter = 0; HashMap<String,Integer> hm = new HashMap<>(); for (int i = 0 ; i < persons.size() ; i++ ) { if (p.isAdult() && p.isFemale()){ womenCounter++; } else if (p.isChild() && p.isMale()) { boysCounter++; } } hm.put("women",womenCounter ); hm.put("boy" , boysCounter); return hm; } for retrieving hashmap value :- for (Map.Entry<String,String> entry : hm.entrySet()) System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } A: While there are some good Answers, especially the one by ash, they address the specific question raised in the Title about returning two values. However, you raised two other questions that show the larger problem. Premature Optimization Isn't that extremely inefficient, having a complete class only for this one small purpose? Always go with clean design first. Do not build an initial design on some imaginary possible performance issue or on excessive worry about efficiency. Processors do two to four billion instructions per second nowadays, so we can afford a little bit of inefficiency. Making code clear, easy to read, easy to debug, and easy to modify is almost always more important than efficiency. On top of that, programmers of all caliber are notoriously bad at predicting performance and bottlenecks. Do not muddy your design with compromises until you have a proven measurable bottleneck of some significance. What if I wanted to count a different pair of values? Would I have to create another entirely new class? That question points to the clumsiness of your trying to combine queries that should be separate. Let's write some code. First, the Person class. Enum Notice that we have nested two enums, Gender & Maturity. If not familiar, see Oracle Tutorial. The enum facility in Java is much more useful, flexible, and powerful than in other languages. Using strings as value flags is clumsy and error-prone. The compiler cannot help you with typos. In contrast, the compiler can help you with enums, bringing type-safety to your code while ensuring valid values. Bonus benefits to using enums: Very little memory used, and very fast to execute. package work.basil.example; import java.util.Objects; import java.util.UUID; public class Person { public enum Gender { FEMALE, MALE } public enum Maturity { ADULT, CHILD } // Members private UUID id; private Gender gender; private Maturity maturity; // Constructor public Person ( UUID id , Gender gender , Maturity maturity ) { Objects.requireNonNull ( id ); Objects.requireNonNull ( gender ); Objects.requireNonNull ( maturity ); this.id = id; this.gender = gender; this.maturity = maturity; } // Accessors public UUID getId ( ) { return id; } public Gender getGender ( ) { return gender; } public Maturity getMaturity ( ) { return maturity; } // Object overrides @Override public String toString ( ) { return "Person{" + "id=" + id + ", gender=" + gender + ", maturity=" + maturity + '}'; } @Override public boolean equals ( Object o ) { if ( this == o ) return true; if ( o == null || getClass () != o.getClass () ) return false; Person person = ( Person ) o; return id.equals ( person.id ); } @Override public int hashCode ( ) { return Objects.hash ( this.id ); } } Write a method countPeople that takes a List of Person objects, along with your pair of criteria (gender & maturity). We can pass any combination of gender and maturity. This design continues to work even as you add values to your enums, such as Gender.UNKNOWN and Maturity.ADOLESCENT. private Integer countPeople ( List < Person > people , Person.Gender gender , Person.Maturity maturity ) { Objects.requireNonNull ( people ); Objects.requireNonNull ( gender ); Objects.requireNonNull ( maturity ); Integer count = 0; for ( Person person : people ) { if ( ( person.getGender ().equals( gender ) ) && ( person.getMaturity ().equals( maturity ) ) ) { count = ( count + 1 ); } } return count; } And, write some code to exercise that counting code. The List.of syntax is new in Java 9 and later, creating an unmodifiable List object of an indeterminate concrete class in one simple line of code. List < Person > people = List.of ( new Person ( UUID.randomUUID () , Person.Gender.FEMALE , Person.Maturity.CHILD ) , new Person ( UUID.randomUUID () , Person.Gender.FEMALE , Person.Maturity.ADULT ) , new Person ( UUID.randomUUID () , Person.Gender.MALE , Person.Maturity.ADULT ) , new Person ( UUID.randomUUID () , Person.Gender.FEMALE , Person.Maturity.CHILD ) , new Person ( UUID.randomUUID () , Person.Gender.MALE , Person.Maturity.ADULT ) , new Person ( UUID.randomUUID () , Person.Gender.MALE , Person.Maturity.CHILD ) , new Person ( UUID.randomUUID () , Person.Gender.FEMALE , Person.Maturity.ADULT ) ); Integer women = this.countPeople ( people , Person.Gender.FEMALE , Person.Maturity.ADULT ); Integer boys = this.countPeople ( people , Person.Gender.MALE , Person.Maturity.CHILD ); Report. System.out.println ( "people = " + people ); System.out.println ( "women = " + women ); System.out.println ( "boys = " + boys ); people = [Person{id=1ac225e6-f21c-49f5-82d5-8e0f289f16e0, gender=FEMALE, maturity=CHILD}, Person{id=333828cc-48e6-4d0c-9937-66f3168445bd, gender=FEMALE, maturity=ADULT}, Person{id=4d37bc08-1e1f-4806-8d84-dc314b6b2cd8, gender=MALE, maturity=ADULT}, Person{id=0cd2a38a-5b01-4091-9cb2-c0284739aa70, gender=FEMALE, maturity=CHILD}, Person{id=36d9af87-3cbb-44bc-bf03-67df45a5d8c8, gender=MALE, maturity=ADULT}, Person{id=2fef944a-79c9-4b29-9191-4bc694b58a4d, gender=MALE, maturity=CHILD}, Person{id=ffc8f355-9a4b-47c3-8092-f64b6da87483, gender=FEMALE, maturity=ADULT}] women = 2 boys = 1 Streams We could get fancy and use streams in place of that for loop. Not necessarily better in this case, but more fun. We are going to call Stream::count. This returns a long, so change our use of 32-bit integer to 64-bit long. Or else you could cast the long to an integer. Calling List::stream generates a stream of the Person objects held in the list. A Predicate object holds our test for gender and our test for maturity. The call to Stream::filter applies the predicate to select objects. These get counted by a call to Stream::count. private Long countPeople ( List < Person > people , Person.Gender gender , Person.Maturity maturity ) { Objects.requireNonNull ( people ); Objects.requireNonNull ( gender ); Objects.requireNonNull ( maturity ); Predicate < Person > predicate = ( Person person ) -> ( person.getGender ().equals ( gender ) && person.getMaturity ().equals ( maturity ) ); Long count = people.stream ().filter ( predicate ).count (); return count; } Tip: Performance with very large lists of people might be better if you went the next step, to parallelize the stream. Databases If this data were coming from a database, you should be doing this work within that database, rather than on the Java side. Database engines such as Postgres are highly optimized to do just this kind of selecting, comparing, sorting, and counting work.
{ "pile_set_name": "StackExchange" }
Q: JavaScript: Passing data to a cross-domain popup behind the scenes The sites of my users collect referrer data about their users and store it in a cookie, which is bound to their domain. If the customer wants to initiate a chat and send the referrer data, they click a button which creates a popup with the URL being on MY domain (so I cannot access their cookies directly). I would like the popup window to receive the data stored in the cookie on their domain (assume I control the JS on their sites too). Ideally, I would do: var w = window.open(...); w.originalReferrer = ...; ... but I hear this method of passing data to the popup only works if the popup is on the same domain (security restrictions). I could also pass it as a GET arg: window.open('chat?originalReferrer=' + encodeURIComponent(...) + ') ... but I'd prefer to keep the popup's URL clean, so no GET args should be visible. Is there a way to clean it up, such as using a redirect (and since the destination is now on the same domain (my domain), there might be a nice JS way to pass this data)? Thanks :-) A: On their site, inject JS that will collect data from the cookie and put it in a hidden form that posts to your domain in a new window (target="_blank"). Posting to a new window isn't always going to give you a popup (tabs) so alternatively you could craft a popup in JavaScript (using var popup_window = window.open(), which gives you a reference to that window, and thus the document etc.). Make the hidden form in the popup window and then post it to your domain. The POST-ing is only necessary to keep your URLs clean, which is a good idea I think.
{ "pile_set_name": "StackExchange" }
Q: If trigonometric ratios are just ratios of length of sides, then why do they become negative? This question might be basic, but it is confusing me: $$\begin{align} \text{sine of $\theta$} &= \frac{\text{length of opposite}}{\text{length of hypotenuse}} \\[4pt] \text{cosine of $\theta$} &= \frac{\text{length of adjacent}}{\text{length of hypotenuse}} \\[4pt] \text{tangent of $\theta$} &= \frac{\text{length of opposite}}{\text{length of adjacent}} \end{align}$$ Thus, trigonometric ratios are just ratios of lengths of sides of a right-angled triangle. So how come their sign changes in different quadrants? Lengths don't have signs. Eg. $\sin 45^\circ = 0.7071\dots$, whereas $\sin(-45^\circ) = -0.7071\dots$. Why ? A: You are right if taken just as triangles they should remain positive. But put them on the Cartesian plane then something changes. The triangles can placed in reference frame and the negative numbers have the meaning of direction and placement with respect to the origin. So you can now describe a triangle in different positions and infer which qaudrant the triangle is in. This is also useful because on the Cartesian plane is where graphs of functions are given if need be we can often describe some of these functions in terms of trig ratios(which are functions themselves) and for that we need our trig functions/ratios to be able to take on negative values. Hope this helps! Oh and I forgot if we do need to figure out the lengths we can do that in coordinate system by taking absolute values(because thats what the geometric interpretation of an absolute value is anyway).
{ "pile_set_name": "StackExchange" }
Q: Backbone.js and Django (Without Tastypie) I'm using Django for my site and trying to incorporate backbone.js. Backbone encourages using Tastypie - but I would rather not. Is there a way to use backbone.js and django without tastypie? Are there any examples out there of how to do this? A: I've been were you are. Needed to just make a custom API for backbone to read for the specific instances. All that really means, is making custom views in your views.py and attaching them to custom urls in urls.py for backbone. Your views will have to return a JSON version of the object or objects So you end up with friendly looking urls that backbone likes For example if I had a model of boxes and I want to write a url and a view that sends all the boxes in my database to my frontend delivering them to backbone - I could make a url like this /api/v1/box/all/ really anything you want. In your view you just need to remember to return JSON. Remember - you need update views to to update from backbone syncings (tastypie PUTS) something like /api/v1/box/3/update?updatedinfodata Let me know if you would like me to expand or show some code.
{ "pile_set_name": "StackExchange" }
Q: Can you intercept NSURLRequests in a UIWebView without breaking the back button? I'm having trouble loading custom HTML into my UIWebView without breaking its goBack method. What Works I'm intercepting the URL requests of my UIWebView so I can load custom HTML. I have control over all the HTML, so I have my special app requests use a custom scheme (ie. myapp://arg1/?arg2=val) that I can parse in webView:shouldStartLoadWithRequest:navigationType:. I decide what HTML I really want to load and call loadHTMLString:baseURL and return NO to cancel the original request. What Doesn't Work The above works great. The problem is that I want to make use of the UIWebView's goBack method and loadRequest: appears to be the only UIWebView method that adds to its history stack. I have a few ideas, but I'm not sure which are feasible and how to go about them. The main thing seems to be that I have to return YES in webView:shouldStartLoadWithRequest:navigationType and I have to use UIWebView's loadRequest method. Idea 1: Modify NSURLRequest/Response: Can I subclass NSURLRequest so that (when the UIWebView makes the request) it doesn't actually make an HTTP request and returns an NSURLResponse with my HTML in it? Or maybe modify/subclass/add a category method to NSURLResponse somehow? I like the idea of it being a real request, but I'm concerned about private APIs and being rejected from the App Store. Idea 2: Handle a custom URL Protocol Register a custom URL protocol so my app responds to it and I can have it return a legitimate NSURLResponse (filled with my custom HTML.) Idea 3: Fool the cache Create the request with this cache policy NSURLRequestReturnCacheDataDontLoad and then somehow get my HTML in between the webView and the cache? Or maybe I'm on the wrong track completely? A: There is another really clever approach which I just tested out: Instead of tinkering with the NSURLCache or rewriting the entire navigation history code, just create a custom NSURLProtocol which is used by the standard NSURLConnection whenever a HTTP request is made. There, you create your own NSURLRequest to load the data and can inspect the MIME type, change the content of the request or cache your data to disk as you please. This idea comes courtesy of Rob Napier: http://robnapier.net/blog/offline-uiwebview-nsurlprotocol-588 His code is now also on GitHub: https://github.com/rnapier/RNCachingURLProtocol A: I'd first try to go route #3. Maybe "Substituting local data for remote UIWebView requests" on Cocoa with Love is helpful for you. A: I would recommend against any of the above approaches. I got #3 working, but it was very, very fragile and hard to debug. (For example, Apple destroys and re-creates NSURLRequests, so you can't just subclass NSURLRequest and expect to come through in the subsequent response.) It ended up being (much) easier to my own back history and note what page to load and scroll position (vertical screen offset).
{ "pile_set_name": "StackExchange" }
Q: Is it necessary to have multiple html files in require.js? I made a simple app using backbone.js and require.js. Earlier i used to have just one index.html file and used to dynamically render/hide different views. Now with require.js, i still have index.html file but i have created separate html files for each of my four views in the app, and i put them all in templates folder. Main point is, these four html files don't have the <!DOCTYPE html></html> tags, just the <div> tags for the view. I'm not sure this is the right way to do it using require.js. Should i integrate all html code into just one index.html and using <script> tags for templating? A: You shouldn't put your templates into one big html file, require.js and Backbone.js are the perfect combination to have everything in highly flexible modules, loaded only when neccessary. With only a few modules you may not notice their advantages, but trust me, if you write more complex, dynamically growing high speed web applications, you save yourself hours of debugging and refactoring, and your code will be very simple to read and modify. You have several ways to handle templates with Backbone, e.x. this.$el.html( _.template(template, this.model.toJSON() )) if you loaded your template into a template variable. It won't affect speed, templates are only a few kilobytes. Comparing to the fact that your page is likely to already load a dozen files(many icons, a few images, css-es, js-es) even without BB.js or Require.js and modules, a new few-kilobyte-big file will not be noticable. Also, you can cache templates after first load if you use Require.js to load them.
{ "pile_set_name": "StackExchange" }
Q: How may I use Umlaute programmatically to show up correctly in PyQGIS messagebar? So far I couldn't figure out how to write something like u"Einstellungen aus ArcView übernehmen" to show up correctly as the titel of my messagebar. At least I can save my source (although this seems to depend heavily on the editor) by marking it as -- coding: iso-8859-1 -- . But it doesn't give me the desired result for my messagebar. I also tried .encode('latin1'), which helped for writing the string correctly to a file, but not for displaying it correctly in the messagebar. Any ideas how to do it? A: Two steps: - add a line that indicates UTF-8 encoding to the top of your script - add the letter u (to indicate unicode) before the string that contains the umlaut For example, the following snippet: # -*- coding: utf-8 -*- from qgis.gui import QgsMessageBar iface.messageBar().pushMessage('Hallo', u'PyQGIS könnte einfacher sein!', QgsMessageBar.WARNING, 2) Would return this:
{ "pile_set_name": "StackExchange" }
Q: Python Scatterplot Index Error I can't determine why I am getting an index error for my scatterplot. fig,ax=plt.subplots(figsize=(12,8)) colors=['b','r'] for i in [2,4]: indices=np.where(benign_or_malignant==i) ax.scatter(clump_thickness[indices],single_ep_cell_size[indices], s=55,c=colors[i]) IndexError Traceback (most recent call last) in () 4 for i in [2,4]: 5 indices=np.where(benign_or_malignant==i) ----> 6 ax.scatter(clump_thickness[indices],single_ep_cell_size[indices], s=55,c=colors[i]) IndexError: list index out of range The dataset is formated like so (ct=clump_thickness, secs=single_ep_cell_size, cl=clump benign(2) or malignant(4): id ct secs cl<br> 1000025 5 2 2<br> 1002945 5 7 2<br> 1015425 3 2 2<br> 1016277 6 3 2<br> 1017023 4 2 2<br> 1017122 8 7 4<br> 1018099 1 2 2<br> 1018561 2 2 2<br> 1033078 4 2 2<br> 1035283 1 1 2<br> 1036172 2 2 2<br> 1041801 5 2 4<br> As I understand it, it should plot clump thickness vs single ep cell size and color the points differently based on whether i = 2 or 4. Can someone point me in the right direction? A: You can try this fig,ax=plt.subplots(figsize=(8,6)) for name, group in df.groupby('cl'): ax.plot(group['ct'], group['secs'], marker='o', linestyle='', label=name, ms = 10) ax.set(xlabel='clump thickness', ylabel='single ep cell size') ax.legend()
{ "pile_set_name": "StackExchange" }
Q: How to call a class function from a tkinter button? I am trying to create a program which prints something everytime i click a button, but it has to bee done using a class. When i run my code, i get this error : NameError: name 'self' is not defined (I dont want to put the test_button inside the class, because this is just a part of a much bigger program, and if i fix my problem in this way, then some other functions wont work.) Any help is much appreciated!! import tkinter as tk from tkinter import * window = tk.Tk() window.geometry("500x400") window.configure(background='grey') class person(): def __init__(self): pass def test(self): print('something') #title label label = tk.Label(window, text = "title",bg = '#42eff5',fg ='red',width = 35, height = 5).pack() #button test_button = Button(window,text='something',command = person.test(self),width= 11,height = 2,bg='blue',activebackground = 'blue',fg='white').place(x = 10,y = 30) window.mainloop() A: You need to create an instance of the person, and call the method on that person. somebody = person() test_button = Button(.., command=somebody.test, ...)
{ "pile_set_name": "StackExchange" }
Q: SQLite - Odd NPE in Bukkit plugin I'm running into a pretty big bug on an SQL-based Bukkit plugin that uses PatPeter's SQLite Bukkit plugin "SQLibrary". I'm attempting to determine whether a player is already entered into the database using the first solution from another SO thread. More information can be found on this forum thread, but I'll give a brief outline here as well. This is the stack trace: And here is the suspect method, with the line indicated in the stack trace marked: SQLite sqlite; // Set in plugin.onEnable(), which executes before anything String QUERY_PLAYEREXISTS = "SELECT playername FROM table WHERE playername = ?"; ... public boolean exists(String name) throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; boolean exists = false; try { connection = sqlite.getConnection(); statement = connection.prepareStatement(QUERY_PLAYEREXISTS); // 109 statement.setString(1, name.toLowerCase()); resultSet = statement.executeQuery(); exists = resultSet.next(); } finally { connection.close(); statement.close(); resultSet.close(); } return exists; } What's going on here? A: I've never personally used SQLite, yet I would say that you may have misconfigured the SQLite setup onEnable(), because sqlite.getConnection() must be returning null. Try adding the following code before line 109: if(connection == null) { throw new RuntimeException("SQLite connection is null!"); } If you get a RuntimeException when next running it, you should probably look into your SQLite setup.
{ "pile_set_name": "StackExchange" }
Q: determine aplication is connected to server or not I am developing one application which is connecting to server to get some data. In this I want to check first if application is connected to server or not. And then, if server is on or off? Based on the result I want to do my further manipulations. So how do I get the result of server status? Here is the code which I am using: Code: try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://192.168.1.23/sip_chat_api/getcountry.php"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { } A: Maintaining session cookies is best choice here, please see how to use session cookie: How do I make an http request using cookies on Android? here, before sending request to server, check for session cookie. If it exists, proceed for the communication. Update: The Java equivalent -- which I believe works on Android -- should be: InetAddress.getByName(host).isReachable(timeOut)
{ "pile_set_name": "StackExchange" }
Q: r run lm on selected variables I have about 26 variables for which I need to run analysis as follows: model1=lm(var1~condition*time,data=main_df) How do I avoid writing this 26 times and do the same analysis for variables 1 - 26 easily? A: I would use a list to store all the ouctomes for easy further manipulations (summary, coefficients extractions...) Something to be tried: lapply(as.list(1:26),FUN=function(i){lm(as.formula(paste("var",i,"~condition*time",sep="")),data=main_df)})
{ "pile_set_name": "StackExchange" }
Q: Java code logic New to Java and using old MIT course to self teach. Here's my code. It returns Thomas: 273 John: 243 Can anyone explain why it's returning two values rather than just the fastest runner? public class Marathon { public static void main(String args[]) { String[] names = { "Elena", "Thomas", "Hamilton", "Suzie", "Phil", "Matt", "Alex", "Emma", "John", "James", "Jane", "Emily", "Daniel", "Neda", "Aaron", "Kate" }; int[] times = { 341, 273, 278, 329, 445, 402, 388, 275, 243, 334, 412, 393, 299, 343, 317, 265 }; int smallest = times[0]; // sets smallest to 341 for (int x = 0; x < times.length; x++) { if (times[x] < smallest) { smallest = times[x]; System.out.println(names[x] + ": " + times[x]); } } } } A: Because you are printing everytime you find a smaller value: if (times[x] < smallest) { smallest = times[x]; System.out.println(names[x] + ": " + times[x]); // print always } If you need to print only fastest, than you need to separate logic to find fastest and print the result. int smallest = times[0]; // sets smallest to 341 for (int x = 0; x < times.length; x++) { if (times[x] < smallest) { smallest = times[x]; } } System.out.println(names[smallest] + ": " + times[smallest]);
{ "pile_set_name": "StackExchange" }
Q: Sending POST data from Android application to PHP script I'm trying to send some POST data to a PHP script from an android application. How should the PHP script look like? This is what I tried but it doesn't work; Android code: class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.alex26.0fees.net/script.php"); try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return null; } @Override protected void onPostExecute(String result) { } } PHP script: <?php if(isset($_POST['id'])) echo $_POST['id']; if(isset($_POST['stringdata'])) echo $_POST['stringdata']; ?> A: Anything sent via POST to PHP script ends in $_POST array. What the script will do with it is another question. Simplest test, that writes content of $_POST to a file named "myfile.txt" (note each request would overwrite content of the file): <?php file_put_contents("myfile.txt", print_r( $_POST, true )); ?> echoing in your script is pointless - you are not consuming server response nor displaying it so how could it "work"?
{ "pile_set_name": "StackExchange" }
Q: Get dict of sums per date from 2 lists I have two lists of equal lengths, one with dates (YYYY-MM-DD) where some are repeating, and one with floats (both positive and negative). How would I get a dictionary object with the sum of floats corresponding to each unique date (sorted), in this format: result_dict = {unique_date_1: float_sum_1, unique_date_2: float_sum_2, etc...} My lists: dates = [2013-06-22, 2009-07-09, 2016-07-09, 2009-07-09] floats = [0.0, 0.8, -0.4, 0.1] What I hope to get: {2009-07-09: 0.9, 2013-06-22: 0.0, 2016-07-09: -0.4} What I have tried so far: unique_dates = set(dates) sum_list = [sum(number) for number in floats] A: You'll want to use a defaultdict with float as the default factory. Then zip the lists and iterate over the keys and values whilst summing the values with the appropriate key. from collections import defaultdict dates = ['2013-06-22', '2009-07-09', '2016-07-09', '2009-07-09'] floats = [0.0, 0.8, -0.4, 0.1] sum_dic = defaultdict(float) for date, value in zip(dates, floats): sum_dic[date] += value output defaultdict(<class 'float'>, {'2013-06-22': 0.0, '2009-07-09': 0.9, '2016-07-09': -0.4}) You can also do it without importing defaultdict like this: sum_dic = {} for date, value in zip(dates, floats): sum_dic[date] = sum_dic.get(date, 0.0) + value A: I'd start with an empty result, then for each date/float pair, update the result. I'm using defaultdict so we don't have to mess around with checking if the date's been seen yet. from collections import defaultdict result = defaultdict(float) # Default value of 0 for date, val in zip(dates, floats): result[date] += val For the part of your question about being sorted, dicts aren't an ordered collection, but that doesn't stop you from iterating over them in order: for date, float in sorted(result.items()): do_stuff_with_dates_in_order() Or, if you don't want to call sorted every time: from collection import OrderedDict sorted_result = OrderedDict(sorted(result.items()))
{ "pile_set_name": "StackExchange" }
Q: Eclipse generate getter/setter for domain objects and classmembers with 'm' suffix I have a small question regarding generated getter and setter methods in my domain objects. I want to use a common style guide for my source code. One part of that style guide says that I start each class member name with the prefix 'm' for member. class User{ String mName; List<Call> mAllCall; List<Geo> mAllGeo; Unfortunately I have a couple of classes with many more member variables. The problem I have is that I am a very lazy developer, and that I create the getter and setter methods in Eclipse with "Source"->"Generate Getters and Setters". The result is public String getmName() { return mName; } public void setmName(String mName) { this.mName = mName; } public List<Call> getmAllCall() { return mAllCall; } public void setmAllCall(List<Call> mAllCall) { this.mAllCall = mAllCall; } public List<Geo> getAllGeo() { return mAllGeo; } public void setmAllGeo(List<Geo> mAllGeo) { this.mAllGeo = mAllGeo; } That is not the result I want. I need this: public String getName() { return mName; } public void setName(String pName) { this.mName = pName; } public List<Call> getAllCall() { return mAllCall; } public void setAllCall(List<Call> pAllCall) { this.mAllCall = pAllCall; } public List<Geo> getAllGeo() { return mAllGeo; } public void setmAllGeo(List<Geo> pAllGeo) { this.mAllGeo = mAllGeo; } I currently remove and replace the prefix in the method names by hand. Is there an easier way to do this? A: For the prefix m, you add the letter m to your list of prefixes in the Java Code Style. Follow these steps: open Preferences, in left panel, expand Java, expand Code Style, right panel is where you should now be looking at You will see a list with Fields, Static Fields, etc. This is what you need to modify. Set m against Fields. Set p against the Parameter. As the name of the field will now be different from the name of the argument, the this. qualification will no longer be added automatically. However, you can check the option Qualify all generated field accesses with 'this.' to have it again. I suppose that you know the difference between Enable project specific settings and Configure Workspace Settings... in the upper left and right of the window? A: I don't like the idea at all, but.. You can write the members without the prefix m, let Eclipse create the getters and setters, an afterwards rename the members (Shift-Alt-R); Eclipse will change the references, but not (unless you explicitly tell it) the getters/setters signature.
{ "pile_set_name": "StackExchange" }
Q: How can I splat a hashtable directly from a class static method? How can I get the same output as: $ht = @{Object="Hi there";Foregroundcolor="Green"} Write-Host @ht without using a/the variable $ht ? Don't get me wrong, I know how to use a basic CMDLet. I have a static method that generates dynamic hashtables. Look at this simplified example code: class HashtableGenerator { static [hashtable]Answer() { return @{Object="Hallo Welt";ForegroundColor="Green"} } } $ht = [HashtableGenerator]::Answer() Write-Host @ht This works just fine, but is it possible to get rid of the $ht variable, so the code would look something like this: Write-Host @([HashtableGenerator]::Answer()) # Doesn't work A: I'm pretty sure what you are looking to do is not possible at least at this time. Splatting is specific to hashtable and array variables explicitly. Not return values of functions, methods etc. Technet for splatting sort of supports this Splatting is a method of passing a collection of parameter values to a command as unit. PowerShell associates each value in the collection with a command parameter. Splatted parameter values are stored in named splatting variables, which look like standard variables, but begin with an At symbol (@) instead of a dollar sign ($). The At symbol tells PowerShell that you are passing a collection of values, instead of a single value. Using the @ outside of that will tell PowerShell to treat the results as an array. IIRC there is a semi related feature request to splat directly from a hashtable definition instead of saving to a variable first. Related question talking about splatting from a variable property: Splatting a function with an object's property
{ "pile_set_name": "StackExchange" }
Q: JQuery to capture form (not html form) data and send to another location First of all, pardon my complete lack of skills. We have a website with a simple slide-in form (appears if clicked on by the user) that sends us a request to return a call to the user. We request name, email, phone number and time of the call. The data is sent through $.post to another php file, but there isn't any <form> tag in the html, only <input> tags. So I assumed the JS/JQuery (I don't know what to call it) is capturing and sending the data that is typed in the input fields. I need to gather all these inputs (except for time) and send it to a API of a marketing service provider we contracted. So, this is what the form does for now: The first part is what is actually necessary <script> $(document).ready(function() { $('#G4_Envia').click(function() { var Nome = $('#g4_nome').val(); var Email = $('#g4_email').val(); var Telefone = $('#g4_telefone').val(); var Horario = $('#g4_horario').val(); The second part is not relevant, but I put it here if someone needs it. if (Nome != '' && Email != '' && Telefone != '' && Horario != '') { $('.liga_form').hide(300); $('.liga_wait').show(300); $.post("<?=$URL_BASE?>Paginas/G4Liga/Acoes/Envia.php", {nome: Nome, email: Email, telefone: Telefone, horario: Horario}, function() { $('.liga_wait').hide(300); $('.liga_done').show(300); }); } }); }); </script> And right after this script, begins the "fake" form: <div class="cursos-categorias boletim"> <hgroup> <h2>G4 Liga para você</h2> <h4 class="boletimTexto">Deixe seu nome e telefone nos campos abaixo e ligaremos para você.</h4> </hgroup> <div class="g4_liga"> <div class="liga_form"> <div> <input type="text" id="g4_nome" class="inputHome" placeholder="Nome"/> </div> <div> <input type="text" id="g4_email" class="inputHome" placeholder="E-Mail"/> </div> <div> <input type="text" id="g4_telefone" class="inputHome stdmask-phone" placeholder="Telefone"/> </div> <div> <input type="text" id="g4_horario" class="inputHome stdmask-hora" placeholder="Horário de preferência"/> </div> <button id="G4_Envia" class="btHome">Enviar</button> </div> <div class="liga_wait"> <b>Aguarde,</b><br/> solicitação em andamento </div> <div class="liga_done"> Solicitação Enviada </div> </div> After that, I have to load the service provider script: <script type ='text/javascript' src="https://d335luupugsy2.cloudfront.net/js/integration/stable/rd-js-integration.min.js"></script> So, the provider instructed me to put this code structure right after (this is just an example): <script type ='text/javascript'> var data_array = [ { name: 'email', value: '[email protected]' }, { name: 'identificador', value: 'YOUR_IDENTIFIER_HERE' }, { name: 'token_rdstation', value: 'YOUR_TOKEN_HERE' }, { name: 'nome', value: 'Test' } ]; RdIntegration.post(data_array, function () { alert('callback'); }); </script> Being RdIntegration the function provided that does the sending of data. And I wrote this : <script type="text/javascript"> var data_array = [ { name: 'nome', value: Nome }, { name: 'email', value: Email }, { name: 'telefone', value: Telefone }, { name: 'token_rdstation', value: '5535eb5bc797b015477039eddba3c803' }, { name: 'identificador', value: 'G4-liga' } ]; RdIntegration.post(data_array); And it didn't work. Am I doing something wrong with the values? Should I put it inside the first script? Sorry for the stupidity and the long post, but I hope I could explain well. Thanks in advance. :) A: It's easy, you just need to put the integration from your provider just after the current form send the form data. $.post("<?=$URL_BASE?>Paginas/G4Liga/Acoes/Envia.php", {nome: Nome, email: Email, telefone: Telefone, horario: Horario}, function() { $('.liga_wait').hide(300); $('.liga_done').show(300); // put your integration here.... }); So, your final code could looks like this: $.post("<?=$URL_BASE?>Paginas/G4Liga/Acoes/Envia.php", {nome: Nome, email: Email, telefone: Telefone, horario: Horario}, function() { $('.liga_wait').hide(300); $('.liga_done').show(300); var data_array = [ { name: 'nome', value: Nome }, { name: 'email', value: Email }, { name: 'telefone', value: Telefone }, { name: 'token_rdstation', value: '5535eb5bc797b015477039eddba3c803' }, { name: 'identificador', value: 'G4-liga' } ]; RdIntegration.post(data_array); });
{ "pile_set_name": "StackExchange" }
Q: SELECT with JOIN And SUM in JPQL I wanna do a query for extract information in a dashboard. I have two entities: User and Post, they are a manytomany relation. In my query, I wanna get the post information and the number of users by rol in each post. I have tried this query, and it is working, but when there is a post without users, it isn't coming in the resultset, and it should be "| post1 | information | 0 | 0 |". @Query("SELECT new com.project.dto.DashboardDTO(" + "post.title, " + "post.information, " + "SUM(CASE WHEN u.rol = 0 THEN 1 ELSE 0 END), " + "SUM(CASE WHEN u.rol = 1 THEN 1 ELSE 0 END)) " + "FROM Post post JOIN post.users u " + "GROUP BY post.title, post.information") Page<DashboardDTO> getDashboard(Pageable pageable); What have I to fix? A: You need to use left join instead of join, and you'll get the desired result. Also if you need to get the summarization details for each post, you can group by the post id instead of (title, information) because both of them functionally depend on the id. The query would be: @Query("SELECT new com.project.dto.DashboardDTO(" + "post.title, " + "post.information, " + "SUM(CASE WHEN u.rol = 0 THEN 1 ELSE 0 END), " + "SUM(CASE WHEN u.rol = 1 THEN 1 ELSE 0 END)) " + "FROM Post post LEFT JOIN post.users u " + "GROUP BY post") Page<DashboardDTO> getDashboard(Pageable pageable);
{ "pile_set_name": "StackExchange" }
Q: How to set a style when using a view from imported library I'm using this library to obtain round images. I want to create a style to control the CircularImageView view. <style name="vircularImageView" > <item name="android:layout_width">@dimen/cardViewImagesize</item> <item name="android:layout_height">@dimen/cardViewImagesize</item> <item name="app:civ_border_color">#000000</item> </style> The problem is the item app:civ_border_color, that gives me an error when compiling. The attribute civ_border_color is specific for this object com.mikhaellopez.circularimageview.CircularImageView, so i'm wondering how to solve the problem. I tried using parent but I dont' get any suggestion that matches CircularImageView. Thank you How can A: Well, in styles you should not use any prefix for custom attributes, so it should be: <style name="vircularImageView" > <item name="android:layout_width">@dimen/cardViewImagesize</item> <item name="android:layout_height">@dimen/cardViewImagesize</item> <item name="civ_border_color">#000000</item> </style>
{ "pile_set_name": "StackExchange" }
Q: Is strlen(__FILE__) evaluated at compile time Is strlen(__FILE__) evaluated at compile time -- assuming I'm using a recent compiler (GCC, Clang, MSVC)? A: Clang and gcc are both able to compute this at compile-time thanks to constant-folding optimization passes, but this is nowhere enforced in the C++ standard. Using sizeof could ensure that this is computed at compile-time.
{ "pile_set_name": "StackExchange" }
Q: Transaction receipt is 0x1 but the execution failed. How is it possible https://etherscan.io/tx/0x20081e3012905d97961c2f1a18e1f3fe39f72a46b24e078df2fe446051366dca As you can see from web3.eth.getTransactionReceipt { blockHash: '0xbd4c1f27df055d4aa7e1540808f1e63a6126e178ecb5324062d8df2525137ad7', blockNumber: 4891051, contractAddress: null, cumulativeGasUsed: 4035801, from: '0x2b5634c42055806a59e9107ed44d43c426e58258', gasUsed: 25236, logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', status: '0x1', to: '0x1063ce524265d5a3a624f4914acd573dd89ce988', transactionHash: '0x20081e3012905d97961c2f1a18e1f3fe39f72a46b24e078df2fe446051366dca', transactionIndex: 151 } the status is 0x1, meaning success. However, the gas limit was low(50k) for this transfer. So, what exactly happened there? A: I think I figured it out: aigangToken.methods.balanceOfAt('0x1f38ac62e62ecbc08e124297f84165b5f61cc96b', 4891051).call().then(console.log) The sender didn't have any token balance. So, Since the sender didnt have token balance, the tx simply executed this return: https://github.com/AigangNetwork/aigang-crowdsale-contracts/blob/master/contracts/MiniMeToken.sol#L220 Therefore, it was successful transaction
{ "pile_set_name": "StackExchange" }
Q: How to increase logical volume of a disk in AWS EC2 instance df -h command returns [root@ip-SERVER_IP ~]# df -h Filesystem Size Used Avail Use% Mounted on /dev/xvda1 7.8G 5.5G 2.0G 74% / tmpfs 32G 0 32G 0% /dev/shm cm_processes 32G 0 32G 0% /var/run/cloudera-scm-agent/process I have a volume with 500GB of disk space. Now, I installed some stuff in /dev/xvda1 and it keeps saying that: The Cloudera Manager Agent's parcel directory is on a filesystem with less than 5.0 GiB of its space free. /opt/cloudera/parcels (free: 1.9 GiB (25.06%), capacity: 7.7 GiB) Similarly: The Cloudera Manager Agent's log directory is on a filesystem with less than 2.0 GiB of its space free. /var/log/cloudera-scm-agent (free: 1.9 GiB (25.06%), capacity: 7.7 GiB) From the memory stats, I see that the Filesystem above stuff is installed in must be: /dev/xvda1 I believe it needs to be resized so as to have more disk space but I don't think I need to expand the volume. I have only installed some stuff and started with it. So I would like to know what exact steps I need to follow to expand the space in this partition and where exactly is my 500 GB? A: You cannot resize EBS on the fly. What you can do is create an AMI from the running machine and spawn off a new machine with 500GB root volume (/dev/sda1). To create an AMI you can login to console and in the navigation pane, choose Instances and select your instance. Choose Actions, Image, and Create Image. As you are already aware of the process of machine creation, the only difference here would be that you select your own AMI this time and make sure you increase the root volume storage to 500GB. To change the size of the root volume, locate the Root volume in the Type column, and fill in the Size field. AWS Documentation on AMI creation
{ "pile_set_name": "StackExchange" }
Q: Различие между ResultSet.TYPE_SCROLL_INSENSITIVE и ResultSet.TYPE_SCROLL_SENSITIVE Доброго времени суток. Как я понял ResultSet.TYPE_SCROLL_SENSITIVE, в отличии от ResultSet.TYPE_SCROLL_INSENSITIVE, чувствителен к изменениям, которые произошли с базой данных после создания объекта ResultSet. Но я не могу понять, что означает "чувствителен к изменениям". Я пробовал создавать ResultSet с типом TYPE_SCROLL_SENSITIVE и в течении 10 секунд запрашивать первую строку таблицы: ResultSet result = statement.executeQuery("select * from numbers"); for(int i = 0; i < 10; i++) { result.absolute(1); System.out.printf("number=%d name=%s\n", result.getInt("number"), result.getString("name")); Thread.sleep(1000); } В тоже время запускать второй поток в котором каждые 500 миллисекунд менять первую строку этой же таблицы: for(int i = 0; i < 10; i++) { Thread.sleep(500); String sql = String.format("UPDATE NUMBERS SET number=%d WHERE id=1", (int) (Math.random() * 900_000_000)); statement.executeUpdate(sql); } Я ожидал, что вносимые изменения увидит ResultSet из первого потока, но это не так. Объект ResultSet созданный с типом ResultSet.TYPE_SCROLL_INSENSITIVE ведет себя точно также. Объясните пожалуйста, в чем тогда заключается разница между этими двумя типами ResultSet. P.s. использую СУБД H2. A: @Override public boolean supportsResultSetType(int type) { debugCodeCall("supportsResultSetType", type); return type != ResultSet.TYPE_SCROLL_SENSITIVE; } Драйвер H2 не поддерживает TYPE_SCROLL_SENSITIVE.
{ "pile_set_name": "StackExchange" }
Q: How to Parse Apache config file, PHP config, FTP Server config I've just bough VPS account for testing and development. Is there a function of PHP to parse Apache config file, PHP config, FTP Server config, zone files, etc? Also a way to insert data into config file. I want to create a simple Control Panel to add ftp accounts and web account (with domain). If you have done it before - how did you do it? It would be quite challenging to learn Thanks. A: No, PHP has no functions to parse the config files of those programs - you'll have to write a custom parser for most of those formats. However, for php.ini you might be able to use PHP's ini functions. Most webhosting control panels either create the whole config file based on their database - i.e. they never read it but only (over)write it or they require you to include (apache and bind support that for example, for PHP you can use php_admin_value in the apache virtualhosts) their generated file - which is also never read by the tool. If you really want to create a tool that actually modifies existing files, don't forget that you cannot simply skip comments as nobody would want an application to rewrite his config file stripping all comments.
{ "pile_set_name": "StackExchange" }
Q: Universal app - how to? I'm using Xcode 4.2 and in the process of writing a universal app. I selected SingleView Application template when starting with a new project. XCode added ViewController1.h, ViewController1.m, ViewController1_iphone.xib and ViewController1_iPad.xib. I need to add more UIs and clicked on the File...New...New File and selected UIViewController subClass template and seeing two checkboxes (Targeted for iPad, With Xib for User Interface). What should I do here to support both iPad and iPhone while at the same time have a common .h and .m files that share the same code. Do I need to add code to check whether it is a iPad or iPhone by doing this in my view controllers? if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { } else { } Also, I have seen people talking about ~iPad and ~iPhone. What is this all about? If I understand correctly, do I have to design the UI separately both for iPad and iPhone due to different screen sizes? I'm totally confused here. Please help. A: You can either add two nibs (one for ipad and one for iphone), or you can add one nib that will properly scale for either interface. Normally you'd add two nibs if you're making a view that will cover all or most of the screen, and you'd add one nib if you're making something small that will, perhaps, be fullscreen on iphone but displayed in a popover on ipad. The tilde suffixes ~ipad and ~iphone are described under the heading “iOS Supports Device-Specific Resources” in the Resource Programming Guide. Notice that the suffixes are entirely lower-case, not camel-case as you wrote in your question. This matters because iOS uses a case-sensitive filesystem. When you get a path for a resource using an NSBundle message like -[NSBundle pathForResource:ofType:] or -[NSBundle URLForResource:withExtension:], iOS will first look for the resource file with a suffix of ~ipad or ~iphone, depending on the current device. For example, suppose you do this: NSString *path = [[NSBundle mainBundle] pathForResource:@"setup" ofType:@"plist"]; If you run this on an iPhone-type device (including an iPod touch), or on the simulator in iPhone mode, iOS will first look in your app bundle for a file named setup~iphone.plist. If it finds such a file, it will return the path of that file. If it doesn't find that file, it will instead return the path to setup.plist. If you this on an iPad-type device, or on the simulator in iPad mode, iOS will first look in your app bundle for a file named setup~ipad.plist. If it finds such a file, it will return the path of that file. If it doesn't find that file, it will instead return the path to setup.plist. All of the other APIs that get resources from bundles are built on top of NSBundle, so they all benefit from this device-specific lookup. That means if you use +[UIImage imageNamed:], it will automatically use a device-specific image, if you have one in your bundle. And if you use -[NSBundle loadNibNamed:owner:options:], it will automatically load a device-specific nib (.xib) file, if you have one in your bundle. This simplifies your code, if you use the suffixes. If you create MyViewController~ipad.xib and MyViewController~iphone.xib, your app will automatically load the correct one for the current device. You don't have to check the user interface idiom; NSBundle checks it for you. (You could also use the names MyViewController~ipad.xib and MyViewController.xib and get the same effect.) Now, you may have noticed that when you created your “universal” project, Xcode gave your project files named ViewController1_iPhone.xib and ViewController1_iPad.xib, which do not use the tilde suffixes, and it included code to look at the user interface idiom and choose a filename accordingly. Why does the universal project template do this? I don't know, but it is stupid. I suggest you fix the filenames to use the tilde suffixes and rip out the code that checks the user interface idiom.
{ "pile_set_name": "StackExchange" }
Q: $L^p$ integrable but not $L^q$ integrable Does there exist a continuous function on $[0, \infty)$ such that it is in $L^p(0,\infty)$ for some $p\in [1,2]$ but is not in $L^q(0,\infty)$ for any $q\in (2, 2/(2-p))$? Thanks! A: For any $n\in\mathbb N$, put $\delta_n=\frac{e^{-n}}{n^2}$. Now, let $f:[0,\infty)\to\mathbb R$ be the continuous function defined as follows: $f(t)\equiv e^n$ on $\left[n-\frac{\delta_n}2,n+\frac{\delta_n}2\right]$, $f(t)\equiv 0$ outside $\bigcup_{n\in\mathbb N} [n-\delta_n, n+\delta_n]$, and $f$ is linear on the remaining intervals. Then $f$ is in $L^1(0,\infty)$ because $$\int_0^\infty \vert f(t)\vert dt= \sum_{n=1}^\infty \frac32\delta_n\times e^n=\frac32\sum_{n=1}^\infty\frac{1}{n^2}<\infty\, .$$ On the other hand, $f$ is not in any $L^q$, $q>1$ since $$\int_0^\infty \vert f(t)\vert^q dt\geq \sum_{n=1}^\infty \delta_n\times e^{qn}=\sum_{n=1}^\infty \frac{e^{(q-1)n}}{n^2}=\infty\, . $$
{ "pile_set_name": "StackExchange" }
Q: Customizing Django Admin's verbose_name by init, using default As I would use in version 2 of django the default_app_config = 'catalog.apps.CatalogConfig' in __init__ to set verbose_name and customize django admin? It returns the error 'No Module named catalog' Details: I use my apps to a directory below and in INSTALLED_APPS I put projectName.AppName A: Your question isn't much clear (to me). What I understood is, you tried to customize the admin interface by adding verbose_name and during that process you got the error, 'No Module named catalog'. If that so, Initial you have to put the verbose_name name in your apps configuration class inside the apps module # catalog/apps.py from django.apps import AppConfig class CatalogConfig(AppConfig): name = 'catalog' verbose_name = 'Fantasy Title' and in your INSTALLED_APPS of settings.py, it should be either INSTALLED_APPS = [ 'catalog', ..... ] OR INSTALLED_APPS = [ 'catalog.apps.CatalogConfig', ..... ]
{ "pile_set_name": "StackExchange" }
Q: Message: Trying to get property of non-object Filename: controllers/site.php My Model name is common_model and there is a method: function select_fields_where_like_join($tbl = '', $data, $joins = '', $where = '', $single = FALSE, $field = '', $value = '',$group_by='',$order_by = '',$limit = '') { if (is_array($data) and isset($data[1])) { $this->db->select($data[0],$data[1]); } else { $this->db->select($data); } $this->db->from($tbl); if ($joins != '') { foreach ($joins as $k => $v) { $this->db->join($v['table'], $v['condition'], $v['type']); } } if ($value !== '') { $this->db->like('LOWER(' . $field . ')', strtolower($value)); } if ($where != '') { $this->db->where($where); } if($group_by != '') { $this->db->group_by($group_by); } if($order_by != '') { if(is_array($order_by)) { $this->db->order_by($order_by[0],$order_by[1]); } else { $this->db->order_by($order_by); } } if($limit != '') { if(is_array($limit)) { $this->db->limit($limit[0],$limit[1]); } else { $this->db->limit($limit); } } $query = $this->db->get(); if ($query->num_rows() > 0) { if ($single == TRUE) { return $query->row(); } else { return $query->result(); } } else { return FALSE; } } Here is my controller method: public function load_vo_training($themeID=NULL) { if (!isset($themeID) || !is_numeric($themeID) || empty($themeID) || $themeID == NULL) { $msg = 'Redirected To Themes, As No Record Found For your Request:FAIL'; $this->session->set_flashdata('msg', $msg); redirect('site/load_theme'); } $bool = is_admin($this->data['UserID']); if (!is_admin($this->data['UserID'])) { $PTable = 'Theme T'; $selectData = array('COUNT(*) AS TotalRecordsFound', true); $joins = array( array( 'table' => 'project_theme PT', 'condition' => 'PT.theme_id = T.theme_id AND PT.enabled = 1', 'type' => 'INNER' ), array( 'table' => 'project P', 'condition' => 'P.project_id = PT.projects_id', 'type' => 'INNER' ), array( 'table' => 'sys_groups_projects_themes_permissions SGPTP', 'condition' => 'SGPTP.projectID = P.project_id AND SGPTP.trashed = 0', 'type' => 'INNER' ), array( 'table' => 'sys_groups G', 'condition' => 'G.groupID = SGPTP.groupID', 'type' => 'INNER' ), array( 'table' => 'user_account U', 'condition' => 'U.groupID = G.groupID', 'type' => 'INNER' ) ); $where = array( 'T.theme_id' => $themeID ); $countResult = $this->common_model->select_fields_where_like_join($PTable, $selectData, $joins, $where); if ($countResult->TotalRecordsFound > 0) { echo $countResult->TotalRecordsFound; } else { echo "no record"; } } } I got the output like this with error message array(1) { [0]=> object(stdClass)#26 (1) { ["TotalRecordsFound"]=> string(3) "139" } } A PHP Error was encountered Severity: Notice Message: Trying to get property of non-object Filename: controllers/site.php Line Number: 5408 Please help me and thanks in advance. A: $countResult is an array of objects. So you have to use the array index to access the values inside it. Use the !empty($countResult) before accessing the array. if (!empty($countResult)) { if ($countResult[0]->TotalRecordsFound > 0) { echo $countResult[0]->TotalRecordsFound; } else { echo "no record"; } }
{ "pile_set_name": "StackExchange" }
Q: How to inject dependencies in app.config in angularjs? I've been getting errors when minifying my AngularJS app because manually injected dependencies aren't working how I'd expect. The following didn't work: var config = app.config(function($routeProvider) { $routeProvider .when('/', {controller: 'PageCtrl', templateUrl: '../templates/home.html'}); .otherwise({redirectTo: '/'}); }); config.$inject = ['$routeProvider']; The only thing that worked is: app.config(['$routeProvider', function($routeProvider) { ... }]); Why does the first dependency injection technique work for controllers but not configs? A: It is because app.config returns reference to the app (for chaining). This code works: var config = function($routeProvider) { $routeProvider .when('/', {controller: 'PageCtrl', templateUrl: '../templates/home.html'}) .otherwise({redirectTo: '/'}); }; config.$inject = ['$routeProvider']; app.config(config); http://jsfiddle.net/ADukg/3196/
{ "pile_set_name": "StackExchange" }
Q: Multithreading in Unity on Android Some "long work" needs to be performed during game process. Obviously game freezes on 1-2 seconds when this work is being performed. So i put algorithm of "long work" to second thread and, as was expected, freezing has disappeared... but only on PC. Game still freezed on android device. Please, tell me what I could have missed. Perhaps there are some compilation options that forbid multithreading or something like that? A: Threads work as they must. To find the real problem you should use profiler. They will show you when, where and why the program freezes.
{ "pile_set_name": "StackExchange" }
Q: How to list out invoice email template in magento 2? I want to list out all invoice email templates in my custom module. I want to add one dropdown in my custom admin form. A: List assume, you have form field like: $fieldset->addField( 'invoice_template_id', 'select', [ 'label' => __('Select Email Template'), 'title' => __('Select Email Template'), 'name' => 'invoice_template_id', 'required' => true, 'class' => 'selectopt', /* 'css_class' => 'hidden', */ 'values' => $this->getEmailTemplate() ] ); and write function who can get collection of invoice custom email templates: /** Email Template List * */ public function getEmailTemplate() { $emailList = array(); $collection = $this->emailTemplateCollectionFactory->create(); foreach ($collection as $list) { if (($list->getOrigTemplateCode() == "sales_email_invoice_template")) { $emailList[$list->getTemplateId()] = $list->getTemplateCode(); } elseif (($list->getOrigTemplateCode() == "sales_email_invoice_comment_guest_template")) { $emailList[$list->getTemplateId()] = $list->getTemplateCode(); } elseif ($list->getOrigTemplateCode() == "sales_email_invoice_comment_template") { $emailList[$list->getTemplateId()] = $list->getTemplateCode(); }elseif ($list->getOrigTemplateCode() == "sales_email_invoice_guest_template") { $emailList[$list->getTemplateId()] = $list->getTemplateCode(); } } return $emailList; } It will only return Invoice related custom template list.
{ "pile_set_name": "StackExchange" }
Q: Understanding a monad instance I have this Haskell code portion: newtype State st a = State (st -> (st, a)) instance Monad (State state) where return x = let f t = (t,x) in State f State f >>= g = State (\oldstate -> let {(newstate, val) = f oldstate; State f'= g val} in f' newstate) I'm new to monad but i think i got how return and bind works in the general case. But in the example above i have lots of problems: in Monad (State state) is State the Monad's name? How is it related with the newtype State ... ? in return x = let f t = (t,x) in State f where does t comes from? A: So by this point you've certainly heard of currying or partial application: if you have f :: a -> b -> c and x :: a, then f x :: b -> c. I.e., If f is a two-argument function and x has the type of f's first argument, then f x is a function that takes the second argument and "completes" the application. Well, in Haskell the same thing applies to type constructors like State. Types and type constructors have a kind, which is analogous to how values have types. A non-parametric type like Integer has kind *; a one-parameter type like Maybe has kind * -> *; State has kind * -> * -> *. And then, State state is a partial application of the State type constructor, and has kind * -> *. Monad is a class that applies to the kind * -> *. So, applied to our examples: instance Monad (Integer) where ... is forbidden because Integer has kind *. instance Monad (Maybe) where ... is allowed because Maybe has kind * -> *. instance Monad (State) where ... is forbidden because State has kind * -> * -> *. instance Monad (State st) where ... is allowed because State st has kind * -> *. How do we know that Monad applies to types of kind * -> *? We can infer it from the class declaration: class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b -- ... Look at how m is used in this class declaration: as part of m a and m b, i.e., as taking one argument. Because of this, Haskell infers that m is a type variable of kind * -> *. Compare to this: class Num a where (+) :: a -> a -> a (-) :: a -> a -> a -- ... Here the type variable a is not applied to other type variables—thus it must be of kind *. So strictly speaking, State is not a monad; it's a two-place type constructor that, when partially applied to just one type, gives you a monad. So State state is a monad, as is State Integer, State [a], etc. People do often speak loosely and talk of State and similar things as monads, though, but you should understand it's a parametrized monad—it's a monad that has an internal type parameter and thus many variants that differ in the type of that parameter.
{ "pile_set_name": "StackExchange" }
Q: Xpath xlst text function in brackets having this xml <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book> <title lang="en">Harry Potter</title> <price>29.99</price> </book> <book> <title lang="en">Learning XML</title> <price>39.95</price> </book> </bookstore> how to understand count(bookstore/book[text()]) > 1 ? A: I assume xpath should be like this, if you are checking for '<book>' with immediate text, where XML elements are having indentations and line breaks. count(bookstore/book[text()[normalize-space()]]) gt 0 count(bookstore/book[text()]) > 1 will give result 'true' as <book> is having space after it, which is also text. Sample XML: <bookstore> <book> <title lang="en">Harry Potter</title> <price>29.99</price> </book> <book>2 <title lang="en">Learning XML</title> <price>39.95</price> </book> <book>7</book> </bookstore> XSLT: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="@*|node()"> <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy> </xsl:template> <xsl:template match="/"> <xsl:if test="count(bookstore/book[text()[normalize-space()]]) gt 0"> <xsl:value-of select="count(bookstore/book[text()[normalize-space()]])"/> </xsl:if> </xsl:template> </xsl:stylesheet> Will give the result 2 as there are three <book> elements are there, but second and third <book> elements are having immediate text (those text are 2 and 7), but first one is having one element (not the immediate text). If your input xml supplied to this XSLT then there will be count=0, because <book> is not having immediate text (spaces are not consider, because I used normalize-space() function).
{ "pile_set_name": "StackExchange" }
Q: iPhone (iOS): copying files from main bundle to documents folder error I am trying to copy some files across from my app bundle to the documents directory on first launch. I have the checks in place for first launch, but they're not included in code snippet for clarity. The problem is that I am copying to the documents directory (which already exists) and in the documentation, it states that: dstPath must not exist prior to the operation. What is the best way for me to achieve the copying straight to the documents root? The reason I want to do this is to allow iTunes file sharing support. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Populator"]; NSLog(@"\nSource Path: %@\nDocuments Path: %@", sourcePath, documentsDirectory); NSError *error = nil; if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:documentsDirectory error:&error]){ NSLog(@"Default file successfully copied over."); } else { NSLog(@"Error description-%@ \n", [error localizedDescription]); NSLog(@"Error reason-%@", [error localizedFailureReason]); } ... return YES; } Thanks A: Your destination path must contain the name of item being copied, not just the documents folder. Try: if([[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:[documentsDirectory stringByAppendingPathComponent:@"Populator"] error:&error]){ ... Edit: Sorry misunderstood your question. Don't know if there's a better option then iterating through folder contents and copy each item separately. If you're targeting iOS4 you can use NSArray's -enumerateObjectsUsingBlock: function for that: NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL]; [resContents enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSError* error; if (![[NSFileManager defaultManager] copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] toPath:[documentsDirectory stringByAppendingPathComponent:obj] error:&error]) DLogFunction(@"%@", [error localizedDescription]); }]; P.S. If you can't use blocks you can use fast enumeration: NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:copyItemAtPath:sourcePath error:NULL]; for (NSString* obj in resContents){ NSError* error; if (![[NSFileManager defaultManager] copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] toPath:[documentsDirectory stringByAppendingPathComponent:obj] error:&error]) DLogFunction(@"%@", [error localizedDescription]); } A: a note: don't issue lengthy operation in didFinishLaunchingWithOptions: is a conceptual mistake. If this copy takes too much time, watchdog will kill you. launch it in a secondary thread or NSOperation... I personally use a timer proc.
{ "pile_set_name": "StackExchange" }
Q: Would it be legal to change the functionality of your own software to do something apparently malicious if fullly documented? This topic came up when discussing the infamous left-pad disaster from awhile back. To give a brief summary the author of a small package hosted on the npm repository that numerous other packages had (indirect) dependencies on decided to remove his package in protest of the repositories policies. The result was that a significant number of highly important programs and packages all failed overnight when the dependency they all required could no longer be found. We were wondering, purely hypothetically, could the developer have done something more malicious legally. Let's say, purely hypotehtically, that instead of removing the left-pad software he instead changed it so that it now did some bizzare or malicious behavior, like trying to remove everything from the computer (which the browser should prevent), or giving the wrong response 1/5 of the time (which would be allowed and would be much harder to trace the root issue to. Assuming the individual fully documented the change and new behavior when he updated his source code then this package would still be doing exactly what it reported to do, and as such arguably anyone who downloaded the package would thus be choosing to run whatever bizzare apparently-malicious behavior he had added to the code. In reality the nature of how package dependencies work means that most people wouldn't know they had a dependency on the package, much less read the documentation to know that this package their unaware of now does something malicious. Legally, if a develop tried something like this with a package would they be guilty of a crime? Or is it within the developers legal rights to change a package to do whatever he chooses, so long as documented, and thus fall under some 'buyer beware' clause where it's their fault they didn't realize the package had new functionality? for now I'll narrow this down to focusing on US law, since I believe that's where the original author of the package lived. A: The following list of the grounds on which virus creation or distribution may be found to be illegal: from this source Unauthorized access - you may be held to have obtained unauthorized access to a computer you have never seen, if you are responsible for distribution of a virus which infects that machine. Unauthorized modification - this could be held to include an infected file, boot sector, or partition sector. Loss of data - this might include liability for accidental damage as well as intentional disk/file trashing. Endangering of public safety Incitement - includes making available viruses, virus code, information on virus creation, and virus engines. Denial of service Application of any of the above with reference to computer systems or data in which the relevant government has an interest. As soon as your programmer alters the function left-pad to be malicious it is essentially a virus, and your example includes unauthorized access, modification, and loss of data. The fact that he tells you it will now do these things doesn't make it any less illegal. Think someone walking into a bank and saying "This is a robbery." Great. Still illegal. However, doing something bizarre may not be illegal, like the April Fools' prank by Google, which resulted in users being unable to respond to email conversations ("Drop the Mic" if I remember correctly.) It might still open the programmer to liability if it caused damages and he knew this was a possibility. (I think Google did end up facing lawsuits over their prank.) Great rule of thumb: If an act is intentional and is meant to cause harm, it's probably illegal.
{ "pile_set_name": "StackExchange" }
Q: How can US stocks change so much without any new company activity? I follow the market every day. It is rushing to recover losses over the last few weeks. However, stock prices are not mirroring the actual activity of the companies, only because liquidity in market shares costs more. There is no connection to company activity. How does this make any sense? A: Stock prices are not tied to current performance, they are tied to future performance that may be tied to current (and future) market conditions. So if the market thinks that a company will perform poorly going forward based on the current environment, then it's likely that it's stock price will suffer. The financial (i.e. ignoring voting rights) value of a stock is tied to the future cash flows of that portion of ownership. That cash flow can come in the form of: Dividends Acquisition/Merger Liquidation Buybacks Income for a company increases its value in an acquisition/liquidation scenario - and dividends/buybacks are a way to directly distribute profits to shareholders. So the more profitable a company is in the future, the more it's stock is worth. That's why you see many companies like Facebook lose money hand over fist for years, but their stock is highly valuable - because the expectation is that at some point the company will become profitable as it builds market share, loyalty, etc.
{ "pile_set_name": "StackExchange" }
Q: verify URL is live and running or not I will be taking URL from user. Now I need to verify whether address is live or not. For example: If user enters "google.com", then I will pass "google.com" as argument to some function, and function will return me TRUE if URL is live, upload and running, otherwise FALSE. Any in-built function or some help. A: I'd suggest using get_headers($url) and checking to see if one of your responses contains "200 OK". If so, then the site is alive and responded with a valid request. You can also check for other status codes if you want, such as redirects and whatnot.
{ "pile_set_name": "StackExchange" }
Q: Add a view at the top of another view iOS I need help. I'm designing my UI, and I have been using the properties FRAME and CENTER to layout my views. Both of those are so much helpful to me. I also use the technique of adding my elements as subview of UIViews container. But, right now, I want to place a UIView at the top of another. Please take a look at my picture. The buttons at the bottom of the screen is already set and is perfect right now, I'm only having a hard time to place my UIView (a container of my textfields) above the button/divider. I'm only starting in iOS, I think 1 month plus already. I know basics of constraints programmatically but I don't want to use this for now as much as possible. PS. I make my screen programmatically. Sample of my code in this screen // start adding container UIView *container2 = [[UIScrollView alloc] init]; container2.frame = CGRectMake(0, 0, [TPRConstants screenWidth] * 0.95, heightOfScrollView); container2.backgroundColor = [UIColor blueColor]; container2.contentSize = CGSizeMake([TPRConstants screenWidth] * 0.95, 250); [self.view container2]; // stuffs and subviews/textfields inside the container self.phoneTextField = [[UITextField alloc] init]; _phoneTextField.frame = CGRectMake(0, 200, scrollView.frame.size.width, 50); _phoneTextField.delegate = self; _phoneTextField.borderStyle = UITextBorderStyleNone; _phoneTextField.background = [UIImage imageNamed:@"textfieldLogIn.png"]; _phoneTextField.backgroundColor = [UIColor clearColor]; [_phoneTextField setKeyboardType:UIKeyboardTypeNumberPad]; [container2 addSubview:_phoneTextField]; // add container for divider and log in button UIView *container = [[UIView alloc] init]; container.frame = CGRectMake(0, 0, [TPRConstants screenWidth], 80); container.backgroundColor = [UIColor whiteColor]; container.center = CGPointMake([TPRConstants screenWidth] * 0.50, [TPRConstants screenHeight] - container.frame.size.height/2); [self.view addSubview:container]; // add divider UIImageView *divider = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, container.frame.size.width, 5)]; divider.image = [UIImage imageNamed:@"dividerCP.png"]; divider.backgroundColor = [UIColor clearColor]; divider.contentMode = UIViewContentModeCenter; [container addSubview: divider]; // add save login UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom]; saveBtn.frame = CGRectMake(0, 0, container.frame.size.width * 0.95, 50); saveBtn.center = CGPointMake(container.frame.size.width /2 , (container.frame.size.height - saveBtn.frame.size.height/2) - 10 ); [saveBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside]; [saveBtn setBackgroundImage:[UIImage imageNamed:@"logoutupCP.png"] forState:UIControlStateNormal]; [saveBtn setTitle:@"Save" forState:UIControlStateNormal]; [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [saveBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; [saveBtn setBackgroundImage:[UIImage imageNamed:@"logoutdownCP.png"] forState:UIControlStateHighlighted]; [container addSubview: saveBtn]; A: If you wish to place a UIView at the base of phoneTextField use the maximum y position of phoneTextField for the y origin position of the UIView. UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(phoneTextField.frame)+0,[TPRConstants screenWidth],50); newView.backgroundColor = [UIColor blueColor]; [self.view addSubview:newView]; Then change the saveBtn frame to make space for newView: saveBtn.frame = CGRectMake(0, CGRectGetMaxY(newView.frame), container.frame.size.width * 0.95, 50);
{ "pile_set_name": "StackExchange" }
Q: Programmatically setting checkboxes I am building out a user management screen in Angular 2 and I want to be able to manage the roles for a user from the screen. Currently, I have a list of all the roles (id and name) and a list of users which contains an array (id and name) of all the roles for that user. I want to be able to list the roles on the screen as checkboxes and be able to set them for the roles the user already has. Currently I have all the roles listed in my template using *ngFor. <div class="row"> <div class="col-xs-12"> <div class="form-inline" style="display:inline" *ngFor="let role of allRoles"> <div class="form-check"> <label class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input"> <span class="custom-control-indicator"></span> <span class="custom-control-description">{{role.name}}</span> </label> </div> </div> </div> </div> I am trying to figure out the best way to populate the roles that have been selected. Should I have a list of all the roles for each user with a "selected" property, or is there a more elegant way to do it? A: You just need to map your list of all roles into something that combines information from your user specific set of roles. Assuming you have an allRoles collection in your component, you could do something like this: this.usersService.getUserRoles(this.selectedUser.id) .subscribe(userRoles => { this.userRoles = this.allRoles.map(r => { return { id: r.id, name: r.name, isAssigned: userRoles.some(ur => { return ur.id == r.id; }) }; }); }); Essentially creating a list of all available roles, but simply marking the ones the user is assigned to. You can see a basic implementation with this Plunker: https://plnkr.co/edit/zCCwLko5Nf2W92Ac7q4i?p=preview Example using groups of roles: https://plnkr.co/edit/OgAmFFozPMtQ75iOs5mR?p=preview
{ "pile_set_name": "StackExchange" }
Q: Defining Function with right T arrow I found a tutorial that preferred the use of the right T arrow (Esc fn Esc) to define functions which I had never seen before. It took me a while to find it in the Function help page buried in the Details section but it is interesting to note that it isn't referenced in the basic examples and seems to be very uncommon in general usage (at least in the books I've purchased and the pdf tutorials I've found online). Perhaps it is very new or very old and people just get used to the # & and f[ _ ]:= formats? Can anyone comment on why this isn't more commonly used or is it just a matter of style? A: I do make use of \[Function] myself, but rarely. As Shadowray notes it does not present well outside of the Notebook so it is not as "nice" for preparing answers here on Stack Exchange. The primary reason I don't use it more often, and simultaneously the primary reason I use it when I do, is that its precedence feels a little odd. Regular & functions are direct to apply and it is easy to string a few together: {#, 3} & @ {#, 2} & @ {#, 1} & @ 0 {{{0, 1}, 2}, 3} 0 // {#, 3} & // {#, 2} & // {#, 1} & {{{0, 3}, 2}, 1} With \[Function] even a simple application require more work; this does not do what I "expect:" a \[Function] {a, 1}[5] Function[a, {a, 1}[5]] Parentheses force the precedence: (a \[Function] {a, 1})[5] {5, 1} Stringing operations doesn't quite work either: a \[Function] {a, 1} @ a \[Function] {a, 2} @ a \[Function] {a, 3} @ 0 Function[a, Function[{a, 1}[a], Function[{a, 2}[a], {a, 3}[0]]]] 0 // a \[Function] {a, 1} // a \[Function] {a, 2} // a \[Function] {a, 3} Function::flpar: Parameter specification a[0] in Function[a[0],Function[a[{a,1}],Function[a[{a,2}],{a,3}]]] should be a symbol or a list of symbols. >> Function[a[0], Function[a[{a, 1}], Function[a[{a, 2}], {a, 3}]]] Of course parentheses can force grouping here too, but it doesn't make this syntax convenient in most cases. The precedence is convenient in other cases where one actually wants it. I'll try to add an example or two later if I have time. A: I think this is more like a personal preference. But I see a couple of possible issues with \[Function]: First, \[Function] looks very similar to \[Rule] and can make reading of the source code more difficult. Second, it can look cumbersome, especially in an external editor. Compare for example the following two expressions: Map[(#^2)&, Range[10]] Map[x \[Function] x^2, Range[10]]
{ "pile_set_name": "StackExchange" }
Q: Easy infinite scroll jQuery with Ajax I am trying to do a really simple infinite scroll that checks in a .html file whenever the scroll is at the bottom, then loads the content of another .html file (which is more text). The second HTML file (the one that will be loaded whenever you scroll to the "limit" and make the "infinite scroll", is this one "Ej7.1.html": <html> <body> <p> lorem ipsum etc etc etc </p> </body> </html> There are more <p> lorem ipsumwith more text, but to make it shorter to read in here, I'm taking that out. And the first HTML file which I am trying to implement the jQuery version for is this one: <!DOCTYPE html> <html> <head> <script> src= "https://code.jquery.com/jquery-3.3.1.min.js" </script> </head> <script> $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() – $(window).height()) { // Here goes the Ajax $("body").load("Ej7.1"); } }); </script> <body> <h1> Pagina ej 7</h1> <p> lorem ipsum and a lot of text </p> </body> </html> So the error it gives me opening the html and pressing F12 is a syntax error in – $(window).height()) { as an unexpected identifiererror. I think I am having a syntax error, but I cannot seem to find what I am missing out nor doing wrong. A: Your script tag is mis-formatted. Put the src attribute in the tag itself: <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> A: You're using the wrong character for minus. You're using – (char code: 8211). You should use - (char code: 45). There could be something wrong with your keyboard or you copy pasted it from some non-properly formatted source. Also, your jQuery inclusion tag won't work as spotted by @agmcleod. That line is basically doing this: <script> src= "https://code.jquery.com/jquery-3.3.1.min.js" </script> If you console.log(src) on your page you'll see this: "https://code.jquery.com/jquery-3.3.1.min.js".
{ "pile_set_name": "StackExchange" }
Q: PS4 controller / Dualshock 4 for Mac not working I read here that the DS4 will work on Mac out-of-the-box by plugging the controller via a micro USB cable—they said it will automatically work as a regular joystick. I got the DS4 yesterday (controller only, no console) and tested it on my Mac but it doesn't seem to work. The computer detects the controller but the games I have doesn't seem to recognize any inputs on the DS4. I tried the controller on Fez, Rayman Origins and Monaco—which all have joystick support—but no luck. Also tried mapping the controller thru Joystick Mapper, it will say "1 Joystick Connected" but when I try to bind the controller, click "scan" while clicking a button on the controller, nothing. I've read on the manual that comes with the controller titled "Registering (pairing) the controller" that there is a need to pair it on the PS4 console to complete registration. Is this a requirement for the controller to work? It's either that is the reason why it's not working or the DS4 is just not compatible with my games (I think it should be tho, since it's supposed to work as a regular joystick when plugged thru USB cable). A: Okay, so I found out the problem, it is due to an app called USB Overdrive taking precedence over the controls of the DS4 controller. If you're like me and you happen to also have a gaming mouse (with no driver support from the maker, pffft Roccat Kova[+]) for FPS games, this app is probably installed on your Mac. On USB Overdrive settings, don't enable "Any Gaming, Any Application". This is the culprit. I tried the controller on Steam's Big Picture and also Monaco after and it worked.
{ "pile_set_name": "StackExchange" }
Q: Nullable DateTimes and the AddDays() extension I have a DateTime variable that can either be null or a Datetime. I figured a nullable DateTime type would work, but I am getting an error telling me that said Nullable<DateTime> does not have a definition for AddDays . Is there any way to resolve this error? DateTime? lastInvite = (DateTime?)Session["LastInviteSent"]; if ((string)Session["InviteNudgeFlag"] == "False" && ((lastInvite == null && DateTime.Now >= AcctCreation.AddDays(7)) || (int)Session["InviteCount"] > 0 && DateTime.Now >= lastInvite.AddDays(7))) { // Non important code here } A: You need to go through the "Value" property: lastInvite.Value.AddDays(7) Note that this will throw an exception if the DateTime is actually null. Luckily, there is another property you can use to test for this, "HasValue". if (lastInvite.HasValue){ /* code */ } A: You should consider trying to make your logic more readable: var inviteNudgeFlag = bool.Parse((string) Session["InviteNudgeFlag"]); if(!inviteNudgeFlag) { return; } var lastInvite = (DateTime?) Session["LastInviteSent"]; var inviteCount = (int) Session["InviteCount"]; var numOfDays = 7; var now = DateTime.Now; var weekSinceLastInvite = lastInvite.HasValue ? now >= lastInvite.Value.AddDays(numOfDays) : now >= AcctCreation.AddDays(numOfDays); var hasInvites = !lastInvite.HasValue || inviteCount > 0; var canInvite = hasInvites && weekSinceLastInvite; if(!canInvite) { return; } A: There are multiple ways to resolve this error. Use Convert.ToDateTime() method which handles null datetime values. Convert.ToDateTime(lastInvite).AddDays(7); Use Value property lastInvite.Value.AddDays(7) Use GetValueOrDefault() method lastInvite.GetValueOrDefault().AddDays(7)
{ "pile_set_name": "StackExchange" }
Q: Why couldn't Octavian (Tavi) manifest a fury sooner? Octavian starts to be able to internalize furies about 5 years after leaving his valley. However it's 2 more years until he is actually able to manifest a fury of his own. In a conversation between Marcus and the First Lord it's said that the First Lord's son manifested a fury at 5 years old and burnt down his nursery. So why did Tavi struggle for so much longer to manifest a fury? A: An insane amount of learning goes on while you're a kid. Septimus grew into his inherited fury power naturally. For the Alerans it seems to be a natural part of childhood, instinct coming first and power and control coming with time (although most aren't powerful enough to set fires at age 5). Octavian labored for fifteen years under not only the block that prevented him from doing anything of the sort, but also the very well reinforced illusion that he would never be able to call on any power (that held for years further). He never had the chance to grow into it naturally. He'd have no developed sense of what the furies would feel like, no mental muscle for the will required to shape them. The rest of his mind and body would have grown on without it. It'd be like a limb that had hung uselessly all his life, that just started to twitch; it'd be a wonderful healing, and you can try and push it and use it and eventually get just as strong with it, but it would never be like you suddenly had it all along. Also notable, he still had to hide his developing powers afterwards for at least a few more years, he had nothing like a regular teacher for many years further, and his life didn't stop being interesting enough to just settle down and do nothing else but push his talent. Any of the above would add to the delay before he was fully developed.
{ "pile_set_name": "StackExchange" }
Q: Django user authentication: django_auth_ldap.backend.LDAPBackend I don't understand how to use the LDAPBackend in django, all I want to do is to authenticate a user against LDAP. I have tried the following: from django_auth_ldap.backend import LDAPBackend auth = LDAPBackend() user = auth.authenticate(username='my_uid',password='pwd') At this point user is None and looking at tcpdump I can't see any connection attempt to the LDAP server. settings.py AUTH_LDAP_SERVER_URI = 'ldap.example.com' AUTH_LDAP_USER_DN_TEMPLATE = 'uid=%(user)s,ou=People,dc=example,dc=com' AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'django_auth_ldap.backend.LDAPBackend', ) The official django doc doesn't provide any snippet about how to use this backend in a view. Many thanks for your help! A: All of the documentation for django-auth-ldap is here. For debugging your configuration, you'll want to install a logging handler on the 'django_auth_ldap' logger; see Django's logging documentation for more on that. At a glance, I would say that one problem is that AUTH_LDAP_SERVER_URI is not set to a URI; try something of the form ldap://ldap.example.com/. You'll also want to review the documentation for AUTH_LDAP_BIND_AS_AUTHENTICATING_USER: this is an advanced and somewhat subtle option that you should only enable if you know that you need it.
{ "pile_set_name": "StackExchange" }
Q: Why does milk curdle after being boiled with ginger? I had heard that raw or simply pasteurized milk does curdle if Ginger is put in it before it reaches its boiling point. Alright, so yesterday I boiled the pasteurized milk at 23:00. Room temperature was around 17 degree Celsius. In the morning I put in the Ginger and then started boiling it! Damn! The milk curdled. (I had put the plain tea leaves and sugar also along with the Ginger). When the milk had been boiled in the previous night, why did it then curdle with Ginger in the morning? I boiled the remaining milk separately and it was fine. A: If you want to prevent the milk from curdling when adding ginger, you have to boil the ginger or at least add it to boiling milk. Ginger protease (the curdling agent in fresh ginger) is rapidly destroyed at temperatures above 70°C. It does not matter if the milk has been boiled in advance if you add ginger to cold or room-tempered milk, it will still curdle.
{ "pile_set_name": "StackExchange" }
Q: applying knockout if and options binding together in one data-bind I am trying to move an if statement into a data-bind but i am running into an error stating: Multiple bindings (if and options) are trying to control descendant bindings of the same element. what i am trying to do is to control the visibility of a dropdown list so it doesn't appear based on the if statement condition. I tried to use the visible bind but it only removed the dropdown elements not the actual dropdown. This is what i am currently attempting: <select id="IdField" name="Id" data-placeholder="Select an item" data-bind="if: items().length > 0, options: items(), optionsText: 'Name', optionsValue: 'Id', value: DdlSelectedValue, event: { change: selectChanged }"> </select> This is what my original code looked like: <!-- ko if: items().length > 0 --> <select id="IdField" name="Id" data-placeholder="Select an item" data-bind="options: items(), optionsText: 'Name', optionsValue: 'Id', value: DdlSelectedValue, event: { change: selectChanged }"> </select> <!--/ko--> is there a way i could move the if statement into the data-bind with the options? A: What you have is the correct way if you want the select to actually be absent from the page when items().length is zero. Alternately, you could use visible, which is of course slightly different (when items().length is 0, the select will be there, it'll just be hidden): <select id="IdField" name="Id" data-placeholder="Select an item" data-bind="visible: items().length > 0, options: items(), optionsText: 'Name', optionsValue: 'Id', value: DdlSelectedValue, event: { change: selectChanged }"> </select>
{ "pile_set_name": "StackExchange" }
Q: Was the BeamRecord type removed from Apache Beam? I'm working on an Apache Beam project and have found usage of the BeamRecord type in other projects. I'm unable to import this type using the latest version of the Java SDK (2.14.0) and am only able to access it when downgrading to version 2.3.0. I checked the API documentation and there is no indication that this type has been deprecated. Is the API documentation out of date? If so, which type should be used instead? A: You might be interested in Beam Row, which replaced BeamRecord. You are correct, there's no mention of it in the release notes. This is the commit that migrated to BeamRecord to Row. It's still annotated @Experimental, but it's become one of the key element types in Beam, used with the Beam SQL APIs and is integrated with a number of IOs.
{ "pile_set_name": "StackExchange" }
Q: ISNULL from Mysql not showing Results on webpage via PHP I'm working on a server based POS and I have a php page that displays the client current money on a table, I have 2 tables (Mov_ctes and Clientes), it works fine when I add WITH ROLLUP on the mysql query, It displays the Total but without A Name (NULL value), so I used IFNULL(Clientes.Nombre,'TOTAL') so It could change the NULL value to TOTAL, I entered the whole command on mysql and worked fine, however if I enter the same query via PHP it doesnt output the "Nombre" column heres my code and a Mysql screenshot <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> <!-- @import url("source/style.css"); --> </style> </head> <body> <?php session_start(); $log=$_SESSION['sesion']; $nombr=$_SESSION['username']; if($log==1) { $con=mysqli_connect("localhost","user","pw","My_db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //Mysql query $result = mysqli_query($con,"SELECT Clientes.cliente_id,IFNULL(Clientes.Nombre,'TOTAL'), sum(Mov_ctes.Movimiento) FROM Clientes NATURAL LEFT JOIN Mov_ctes GROUP BY Nombre WITH ROLLUP"); echo "<table id='hor-minimalist-b' summary='Employee Pay Sheet'>"; echo "<thead>"; echo "<tr>"; echo "<th scope='col'>ID</th>"; echo "<th scope='col'>Nombre</th>"; echo "<th scope='col'>Saldo</th>"; echo "</tr>"; echo "</thead>"; echo "<tbody>"; while($row = mysqli_fetch_array($result)) {echo "<tr>"; echo "<td>" . $row['cliente_id'] . "</td>"; echo "<td>" . $row['Nombre'] . "</td>"; echo "<td>" . $row['sum(Mov_ctes.Movimiento)'] . "</td>"; echo "</tr>"; } echo "</tbody>"; echo "</table>"; mysqli_close($con); } ?> A: You need an alias for the column, otherwise the column name will be IFNULL(Clientes.Nombre,'TOTAL'): SELECT IFNULL(Clientes.Nombre,'TOTAL') AS Nombre ...
{ "pile_set_name": "StackExchange" }
Q: Need to port data in sql child table Need to port data in sql table I have a master table with columns (masterid, masterdata, year). Here masterid is an identity column. I have the data for year 2012. I need to same 2012 data for 2013 I could solve the problem by simply running a SQL statement like: INSERT INTO mastertable SELECT masterdata, 2013 FROM mastertable WHERE Year = 2012 I would like to run similar kind of run for child table also. My child table structure is: (childid , masterid, childdata) Here I have child data for the year 2012, I want to have similar data for year 2013 with proper masterid created for master data for the year 2013 in first step. Preferably I would like to have solution without adding additional temporary columns Any lead greatly appreciated. Regards, Kumar. A: You'll need to store the links between the 2013 and 2012 records created in the mastertable table. If you want to achieve this without adding any additional temporary columns you'll need to use T-SQL. (I've guessed a type of varchar(max) for masterdata as you haven't specified its type). DECLARE @links TABLE ( masterid int, newmasterid int ) DECLARE @mastertemp TABLE ( masterid int, masterdata varchar(max) ) DECLARE @masterid int, @masterdata varchar(max) INSERT INTO @mastertemp SELECT masterid, masterdata FROM mastertable WHERE [year] = 2012 WHILE EXISTS ( SELECT TOP 1 * FROM @mastertemp ) BEGIN SELECT TOP 1 @masterid = masterid, @masterdata = masterdata FROM @mastertemp INSERT INTO mastertable VALUES ( @masterdata, 2013 ) INSERT INTO @links VALUES ( @masterid, SCOPE_IDENTITY() ) DELETE FROM @mastertemp WHERE masterid = @masterid END INSERT INTO childtable SELECT l.newmasterid, c.childdata FROM childtable c INNER JOIN @links l ON c.masterid = l.masterid
{ "pile_set_name": "StackExchange" }
Q: Recovering cleanly from Resque::TermException or SIGTERM on Heroku When we restart or deploy we get a number of Resque jobs in the failed queue with either Resque::TermException (SIGTERM) or Resque::DirtyExit. We're using the new TERM_CHILD=1 RESQUE_TERM_TIMEOUT=10 in our Procfile so our worker line looks like: worker: TERM_CHILD=1 RESQUE_TERM_TIMEOUT=10 bundle exec rake environment resque:work QUEUE=critical,high,low We're also using resque-retry which I thought might auto-retry on these two exceptions? But it seems to not be. So I guess two questions: We could manually rescue from Resque::TermException in each job, and use this to reschedule the job. But is there a clean way to do this for all jobs? Even a monkey patch. Shouldn't resque-retry auto retry these? Can you think of any reason why it wouldn't be? Thanks! Edit: Getting all jobs to complete in less than 10 seconds seems unreasonable at scale. It seems like there needs to be a way to automatically re-queue these jobs when the Resque::DirtyExit exception is run. A: I ran into this issue as well. It turns out that Heroku sends the SIGTERM signal to not just the parent process but all forked processes. This is not the logic that Resque expects which causes the RESQUE_PRE_SHUTDOWN_TIMEOUT to be skipped, forcing jobs to executed without any time to attempt to finish a job. Heroku gives workers 30s to gracefully shutdown after a SIGTERM is issued. In most cases, this is plenty of time to finish a job with some buffer time left over to requeue the job to Resque if the job couldn't finish. However, for all of this time to be used you need to set the RESQUE_PRE_SHUTDOWN_TIMEOUT and RESQUE_TERM_TIMEOUT env vars as well as patch Resque to correctly respond to SIGTERM being sent to forked processes. Here's a gem which patches resque and explains this issue in more detail: https://github.com/iloveitaly/resque-heroku-signals
{ "pile_set_name": "StackExchange" }