text
stringlengths
64
89.7k
meta
dict
Q: load specific div from external webpage I was looking to do something advanced: open multiple user accounts on a specific webpage, to make multiple appointments at the same time so I want to only load or refresh, the appointment div calendar, without refresh whole website. Again it is not my website, just external webpage for appointment A: You can reference a div on another website using an iFrame. The iFrame is used to reference the div on the other website where the calendar of that person is located. You might want to add more information / code examples so that we can help you easier. $('#yourPage').load('wwww.webSiteWithElementYouWant.com #calendarDivIdName'); This is a solution with inspiration from Pointy's answer on this page. Edit 1 You should be able to target a class by using: $('#yourPage').load('wwww.webSiteWithElementYouWant.com .calendarDivClassName');
{ "pile_set_name": "StackExchange" }
Q: Trying to access response globally I'm using Alamofire and when I get the response I'm trying to set it as a variable that I can access anywhere. Here's what I got going var data: NSData? Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters) .responseJSON { (request, response, JSON, error) in let data: AnyObject? = JSON } println(data) And when I run that I get nil.... Any ideas? I know that the request is good because I can see the response inside the scope when I don't assign it to a variable. A: Almofire.request is an asynchronous function. You call it and it will return immediately; before it actually does the request. So, println(data) gets called before anything ever sets data to something other than nil. When the request is actually complete, Alamofire will call the closure you pass to responseJSON, in that closure is where you'll want to actually use data (print it or whatever): Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters) .responseJSON { (request, response, JSON, error) in let data: AnyObject? = JSON // do something useful with data println(data) } Question from comments: But then lets say I want to turn that data into a table. Would I just put all the table code inside the closure? You could put all that code inside the closure, but that will probably get messy pretty quickly. A better way to handle that is to implement the same sort of pattern that Alamofire.request is using. Basically, make your request its own function will takes a closure as a parameter. Then, in the closure you pass to responseJSON, call the closure passed to your function passing it data. Then, make a separate function to "turn that data into a table" and call it with data from your closure. Something like this: func callSomeAPI(resultHandler: (data: AnyObject?) -> ()) -> () { Alamofire.request(.POST, "http://localhost/api/notifications", parameters: parameters) .responseJSON { (request, response, JSON, error) in let data: AnyObject? = JSON resultHandler(data) } } func makeTable(data: AnyObject?) -> () { // make your table } callSomeAPI() { data in makeTable(data) } Note: You'll probably want to convert data to something other than AnyObject? at some point in there.
{ "pile_set_name": "StackExchange" }
Q: Removing duplicate rows without checking the contents of the first column I have a table where the first column will always turn out to be unique. So when I remove the duplicate rows none would be removed. So i want to remove duplicates by eliminating the first row in the duplicate check. Each cell in the table may contain more than one value. Input Table Output table I found the script for eliminating the duplicate rows from other question. But that is not what I am looking for. This question has something similar, but it is done only on the first column. I do not know how I can eliminate the first column from being accessed. Script <script> var seen = {}; $('table tr').each(function() { var txt = $(this).text(); if (seen[txt]) $(this).remove(); else seen[txt] = true; }); </script> What I am trying to achieve I would first eliminate the duplicate elements within the cell and then eliminate the rows with duplicate values. So from the input table above, in the column C_fb 4000 being written twice would be eliminated and then checked for duplicate rows. A: Combined not selector and first selector, your code works! var seen = {}; $('table tr').each(function() { var txt = $(this).find("td:not(:first)").text(); if (seen[txt]) $(this).remove(); else seen[txt] = true; }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><td>id1</td><td>aaaaa</td><td>ccccccccc</td></tr> <tr><td>id2</td><td>bbbbb</td><td>dddddddd</td></tr> <tr><td>id3</td><td>bbbbb</td><td>dddddddd</td></tr> <tr><td>id4</td><td>bbbbb</td><td>dddddddd</td></tr> </table>
{ "pile_set_name": "StackExchange" }
Q: on does ot handle event like live in jQuery I have a page that at run time I add some control based on situations. I write this code for mouseover event for TDs in my table: $(".TableEntry .EntryCell").live("mouseover", function () { var parent = $(this).parent(); parent.css("background-color", "C4F7C3"); }); and it works fine.but according to jQuery doc: the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). I use on or delegate like this code but it does not works: $(".TableEntry .EntryCell").on("mouseover", function () { var parent = $(this).parent(); parent.css("background-color", "C4F7C3"); }); how I can add event handler dynamically using on or delegate? A: You have an invalid named variable par should be parent.. You need to find a persisted parent that you will bind the event handler to .. to simulate .live, you will need to add it to the $('body') so $("body").on("mouseover", '.TableEntry .EntryCell', function () { var parent = $(this).parent(); parent.css("background-color", "C4F7C3"); }); To use it as delegate you need to find a common persisted parent and bind to it.. $("_persisted_parent_id_tag_etc_").on("mouseover", '.TableEntry .EntryCell', function () { var parent = $(this).parent(); parent.css("background-color", "C4F7C3"); }); So you bind to the element in the $('...') and the handler applies to the selector you pass as the second parameter (if you do pass one)
{ "pile_set_name": "StackExchange" }
Q: Integrate both typescript and javascript files into angular same project Would it be possible to have both typescript and javascript files in the same angular project? I have a pretty big project in angular and I want to migrate it to typescript without renaming all files to .ts and fix the errors. Would it be possible to have only one part of an angular application written in typescript and the other one in javascript? A: Yes it is possible with the latest flag --allowjs in typescript 1.8. You can modify your tsconfig.json to include it like this: { "compilerOptions": { "allowJs": true } } See roadmap for more info: Typescript 1.8, and specifically here: link
{ "pile_set_name": "StackExchange" }
Q: Running out of cron.hourly won't import a Python module I have foo running out of cron.hourly. It's been chmod +x'd, and it runs fine. My problem is it does not recognize Python modules as importable. I have ~/Foo/src, and within that lies the original Python code that I turned into an executable (main), as well as the other module I'm trying to import (foobar). I have a init.py sitting there, empty, which should let either module be imported. In fact, running my script with python src/main.py Everything works just fine and I don't get this error. When running run-parts -v /etc/cron.hourly/main I get an error as follows: ImportError: No module named foobar run-parts: /etc/cron.hourly//main exited with return code 1 The way that I'm importing foobar is os.chdir("/home/ubuntu/Foo/src/") import foobar Again, this works when running from Python, but not when running my executable. Why is this, and what can I change to avoid this? A: import sys sys.path.append("/home/ubuntu/Foo/src") import foobar From the doc: sys.path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. A program is free to modify this list for its own purposes.
{ "pile_set_name": "StackExchange" }
Q: An exercise in an introduction to the theory of groups 4.4 Let $G$ be a finite p-group; show that if $H$ is a normal subgroup of G having order $p$, then $H$ is a subgroup of $Z(G)$. $Z(G)=\left\{x\in G| xy=yx, \forall y\in G \right\}.$ Can you help me solve it and explain in detail? Thank you very much. Good health! A: Use the previous exercise (4.3), which states that $K\cap Z(G)\ne 1$ whenever $K\lhd G$. Now $H\cap Z(G)\ne 1$, and so $H\cap Z(G)$ has order $p$. So $H\cap Z(G) = H$. Hint of Exercise 4.3: $K\lhd G$ implies that $K$ is a union of some conjugacy classes of $G$.
{ "pile_set_name": "StackExchange" }
Q: How to insert rows in one table based on another copying previous values in destination table? CREATE TABLE T1 (C1 INT); CREATE TABLE T2 (C1 INT, C2 INT); INSERT INTO T1 VALUES (9), (10), (12), (13), (21), (53), (111); INSERT INTO T2 VALUES (10, 3), (12, 6), (21, 9); Desired values in T2 C1 C2 10 3 12 6 13 6 -- duplicate value from row C1=12 21 9 53 9 -- duplicate value from row C1=21 111 9 -- duplicate value from row C1=21 How does one insert rows into table T2, that are in T1, matching on column C1 where the values of the columns come from previous rows in T2 ordered by C1? If there are no previous values, i.e. C1=9, no new row should be inserted. A: insert into T2 (C1, C2) select a.C1, b.C2 from T1 a cross apply ( select top 1 C2 from T2 where T2.C1 < a.C1 order by T2.C1 desc ) b where a.C1 not in (select C1 from T2) you can also use a correlated subquery instead of cross apply, but it takes an extra check to avoid inserting null if there is no previous C1.
{ "pile_set_name": "StackExchange" }
Q: On application start receiver? I would like to make a receiver that is called each time a new application is started. I see that the ActivityManager[0] allow me to see all the running applications, but I'd like to avoid polling it. How can I do it (if I can)? [0] http://developer.android.com/reference/android/app/ActivityManager.html A: How can I do it (if I can)? You can't. There are no broadcast Intents for such events.
{ "pile_set_name": "StackExchange" }
Q: Show message in alert box wih ajax and json laravel I have the following ajax code: $(function() { // Get the form. var form = $('#ajax-inquire'); // Get the messages div. var formMessages = $('#form-messages'); // Set up an event listener for the contact form. $(form).submit(function(event) { // Stop the browser from submitting the form. event.preventDefault(); // Serialize the form data. var formData = $(form).serialize(); // Submit the form using AJAX. $.ajax({ type: 'POST', url: $(form).attr('action'), data: formData }) .done(function(response) { // Make sure that the formMessages div has the 'success' class. formMessages.removeClass('alert-danger'); formMessages.addClass('alert-success'); // Set the message text. $(formMessages).text(response.success); // Clear the form. $('#fullName').val(''); $('#email').val(''); $('#telephone').val(''); $('#message').val(''); formMessages.show(); }) .fail(function(data) { // Make sure that the formMessages div has the 'error' class. formMessages.removeClass('alert-success'); formMessages.addClass('alert-danger'); // Set the message text. if (data.responseText !== '') { $(formMessages).text(data.responseText); } else { $(formMessages).text('Oops! An error occured and your inquire could not be sent.'); } formMessages.show(); }); }); }); And my code in controller: public function postInquire(Request $request) { $data = array( 'tripName' => $request->tripName, 'fullName' => $request->fullName, 'email' => $request->email, 'telephone' => $request->telephone, 'bodyMessage' => $request->message ); Mail::to('[email protected]')->send(new TourInquire($data)); return response() ->json(['code'=>200,'success' => 'Your inquire is successfully sent.']); } And my route for posting my ajax form is: Route::post('/inquire', 'PostPublicController@postInquire')->name('postInquire'); With the above codes I'm able to send mail via ajax request. I'm trying to show json response message in alert box in my view. But I'm unable to do so as json response message is show in white page with url of my post route for form. HTML code in view: <div class="modal-body"> <div id="form-messages" class="alert success" role="alert" style="display: none;"></div> <div class="preview-wrap"> <img src="{{asset($tour->featuredImage->path)}}" class="preview-img thumbnail" alt="{{$tour->featuredImage->name}}"> <div class="form-wrap"> <form action="{{route('postInquire')}}" id="'#ajax-inquire" method="POST"> {{csrf_field()}} <div class="form-group"> <input type="hidden" name="tripName" id="tripName" value="{{$tour->title}}"> <label>Name</label> <input type="text" class="form-control" placeholder="Enter Your Full Name" name="fullName" id="fullName" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" placeholder="Email Address" name="email" id="email" required> </div> <div class="form-group"> <label for="telephone">Phone</label> <input type="tel" class="form-control" placeholder="Phone Number" name="telephone" id="telephone" required> </div> <div class="form-group"> <label for="message">Message</label> <div class="row"> <textarea name="message" id="message" cols="30" rows="5" class="form-control"></textarea> </div> </div> <button class="btn btn-primary hvr-sweep-to-right">Send Message</button> </form> </div> </div> </div> A: You have a simple typo in your HTML: id="'#ajax-inquire" Both the single quote ' and the # should not be there, and mean that your jQuery selector does not match the form, so none of your Javascript is actually firing. The form is simply submitting normally, and so you end up on the URL specified in the form action. The id should be specified like: id="ajax-inquire" Side note: It doesn't technically matter but you don't need to use $() on existing jQuery objects. It works because jQuery accepts a jQuery object as a selector, but it is redundant if you are not filtering or editing the selector in any way. // Here you set form as a jQuery object var form = $('#ajax-inquire'); // You don't need "$(form)" here, "form" is all you need $(form).submit(function(event) { // You can simply use the existing jQuery object form.submit(function(event) {
{ "pile_set_name": "StackExchange" }
Q: Is this inequality true? If true what is the simplest proof? Suppose we have $$\frac{a_i^1}{b_i^1+c}>\frac{a_i^2}{b_i^2+c},~\forall ~i\in\{1,2,\cdots L\}$$ and $a_i^1<a_i^2$, $b_i^1<b_i^2$ $\forall ~i\in\{1,2,\cdots L\}$. Then can we say that following inequality is true $$\frac{\sum_{i=1}^La_i^1}{\sum_{i=1}^{L}b_i^1+Lc}>\frac{\sum_{i=1}^La_i^2}{\sum_{i=1}^{L}b_i^2+Lc}?$$ Please note that $a_i,b_i$ and $c$ are non-negative values. Further please note that the superscripts do not represent powers. A: A geometrical disproof: WLOG $c=0$, you can absorb it in the $b$'s. Now, in a $(b,a)$ coordinate system, the individual points that fulfill the constraints are contained in an axis aligned right triangle with a vertex at the origin. We choose a blue $p_1:=(a_1^1,b_1^1)$ and the locus of $q_1:=(a_1^2,b_1^2)$ follows. Similarly with a green $p_2:=(a_2^1,b_2^1)$. Now take the sum of $p_1$ and $p_2$, or equivalently their arithmetic average, to get $p$. The inequation to be proven expresses that the average of $q_1$ and $q_2$ must lie below the straight line by $p$. But it is clear that we can pick a $q_1$ and a $q_2$ such that this is invalidated. Finding numerical values shouldn't be a big deal.
{ "pile_set_name": "StackExchange" }
Q: AngularJS not working when paired with RequireJS. Any ideas? I am trying to build a very simply demo to get AngularJS working with RequireJS. Up to this point I have been closely following this tutorial. I have defined a main.js file, which requires both app.js and hello.js, which are both called in turn. app.js defines a new Angular module and returns it. hello.js then adds a controller named 'Hello' to the module. In the page itself, the div should output 'Hello', which is returned by the sayHello method in the Hello controller. However, all my browser shows is {{sayHello}}. A: Well, it seems like Shay Friedman's solution worked. I had seen Angularjs + RequireJs + Express Seed mentioned before, but I was sure there was a way to do the same thing by itself without too much effort. However, it seems like using this project is probably the easiest solution.
{ "pile_set_name": "StackExchange" }
Q: Javascript Scope and local variables I'm really not sure if this is possible in Javascript. Here's my function: var tree = function(name, callback) { if (this.name) { this.name.push(name) print(this.name) } else { this.name = [] } callback() } I'd like to use it as follows and print out the hierarchy: tree("john", function() { tree("geoff", function() { tree("peter", function() { tree("richard", function() { }) }) }) tree("dave", function() { }) }) Here's the desired output: // ['john'] // ['john', 'geoff'] // ['john', 'geoff', 'peter'] // ['john', 'geoff', 'peter', 'richard'] // ['john', 'dave'] but unfortunately I'm getting // ['john', 'geoff', 'peter', 'richard', 'dave'] for the last function call. Is there a way to get the desired outcome? Kind regards Adam Groves A: The reason why the last line is printing all the names is because this.names is never removing the names that are being added to it. You're just appending names onto it. So when the function call is made callback() with the value function() { tree("richard", function() { }) this.names = ['john', 'geoff', 'peter'] and after the call this.names = ['john', 'geoff', 'peter', 'richard']. So now when you call tree("dave", function() { }); this.names is still ['john', 'geoff', 'peter', 'richard']. Try the following instead, and notice I changed this.name to this.names to make is easier to read. var tree = function(name, callback) { if (!this.names) { this.names = []; } this.names.push(name); print(this.names); callback(); this.names.pop(); }
{ "pile_set_name": "StackExchange" }
Q: Markov chains to generate text This is my Python 3 code to generate text using a Markov chain. The chain first randomly selects a word from a text file. Out of all the occurrences of that word in the text file, the program finds the most populer next word for the first randomly selected word. It continues the process to form a very understandable text. The best thing about this code is that it copies the style of writing in the text file. At the first trial of the code, I put 3 of the most famous Shakespeare's plays, the Macbeth, Julius Caesar and The Comedy of Errors. And when I generated text from it the outcome was very much like a Shakespeare poem. My knowledge in Python coding is between intermediate and expert. Please review my code and make changes as you like. I want suggestions from both experts and beginners. # Markov Chain Poetry import random import sys poems = open("text.txt", "r").read() poems = ''.join([i for i in poems if not i.isdigit()]).replace("\n\n", " ").split(' ') # This process the list of poems. Double line breaks separate poems, so they are removed. # Splitting along spaces creates a list of all words. index = 1 chain = {} count = 1000 # Desired word count of output # This loop creates a dicitonary called "chain". Each key is a word, and the value of each key # is an array of the words that immediately followed it. for word in poems[index:]: key = poems[index - 1] if key in chain: chain[key].append(word) else: chain[key] = [word] index += 1 word1 = random.choice(list(chain.keys())) #random first word message = word1.capitalize() # Picks the next word over and over until word count achieved while len(message.split(' ')) < count: word2 = random.choice(chain[word1]) word1 = word2 message += ' ' + word2 # creates new file with output and prints it to the terminal with open("output.txt", "w") as file: file.write(message) output = open("output.txt","r") print(output.read()) Thanks!!! A: Functions Split the code into functions, also split the generation and the presentation. Your algorithm has some clear distinct tasks, so split along these lines: read input assemble chain construct new poem output This way, you can reuse parts of the code, save intermediary results and test the parts individually. generators instead of keeping all the intermediary lists in memory, generators can be a lot more memory efficient. I try to use them as much as possible. substantiating them to a list or dict when needed is easy. read the input There is no need to assemble the intermediary list in ''.join([i for i in poems if not i.isdigit()]). join is perfectly capable of handling any iterable, so also a generator expression. use the with statement to open files: def read_input(filename): """reads `file`, yields the consecutive words""" with open(filename, 'r') as file: for line in file: for word in line.split(''): if word and not word.isdigit(): yield word with regular expressions, and by hoisting the IO, you can ease this method even more: def read_input_re(file): pattern = re.compile("[a-zA-Z][a-zA-Z']+") for line in file: for word in pattern.finditer(line): yield word.group() which then can be called with a file: def read_file(filename): with open(filename, 'r') as file: return read_input_re(file) or with any iterable that yields strings as argument. For example if poem holds a multi-line string with a poem:words = read_input_re(poem.split('\n')) This refactoring also makes loading the different poems from different textfiles almost trivial: filenames = ['file1.txt', 'file2.txt', ...] parsed_files = (read_file(filename) for filename in filenames) words = itertools.chain.from_iterable(parsed_files) If you want all the words in the chain lowercase, so FROM and from are marked as the same word, just add words = map(str.lower, words) assemble the chain Here a collections.defaultdict(list) is the natural datastructure to for the chain. Instead of using hard indexing to get the subsequent words, which is impossible to do with a generator, you can do it like this: def assemble_chain(words): chain = defaultdict(list) try: word, following = next(words), next(words) while True: chain[word].append(following) word, following = following, next(words) except StopIteration: return chain or using some of itertools' useful functions: from itertools import tee, islice def assemble_chain_itertools(words): chain = defaultdict(list) words, followings = tee(words, 2) for word, following in zip(words, islice(followings, 1, None)): chain[word].append(following) return chain Or even using a deque: from collections import deque def assemble_chain_deque(words): chain = defaultdict(list) queue = deque(islice(words, 1), maxlen=2) for new_word in words: queue.append(new_word) word, following = queue chain[word].append(following) return chain whichever is more clear is a matter of habit and experience, If performance is important, you will need to time them. create the poem Since you will be asking for a new word a lot, it can pay to extract it to its own function: def get_random_word(choices): return random.choice(list(choices)) Then you can make an endless generator yielding subsequent words: def generate_words(chain): word = get_random_word(chain) while True: yield word if word in chain: word = get_random_word(chain[word]) else: word = get_random_word(chain) We then us islice to gather the number of words we need, which then can be pasted together with ' '.join() length = 10 poem = islice(generate_words(chain), length) poem = ' '.join(poem) "be tatter'd we desire famine where all eating ask'd where" Once you have that, making a poem of a number of lines with set length is also easy: def construct_poem(chain, lines, line_length): for _ in range(lines): yield ' '.join(islice(generate_words(chain), line_length)) lines = construct_poem(chain, 4, 10) lines = map(str.capitalize, lines) print('\n'.join(lines)) Be tatter'd we desire famine where all eating ask'd where Deep trenches that thereby the riper substantial fuel shall beseige Treasure of small pity the riper eyes were to the Foe to the riper by time spring within and make I think it makes sense to do the capitalization after the line has been assembled. Yet another separation of generation and presentation: def construct_poem2(chain, line_lengths): for line_length in line_lengths: yield ' '.join(islice(generate_words(chain), line_length)) line_lengths = [10, 8, 8, 10] lines = construct_poem2(chain, line_lengths) lines = map(str.capitalize, lines) print('\n'.join(lines)) Be tatter'd we desire famine where all eating ask'd where Deep trenches that thereby the riper substantial fuel Shall beseige treasure of small pity the riper Eyes were to the riper memory but eyes were to
{ "pile_set_name": "StackExchange" }
Q: Загрузка файлов на сервер через Retrofit Нужно на сервер передать несколько файлов ( 1-4 видео .mp4 ). Как передать их по отдельности знаю, а можно ли передать сразу все файлы одним запросом используя Retrofit. Либо с помощью других библиотек. A: Всё оказалось на много проще, чем я думал, просто на сервере не правильно разбирали мой запрос, поэтому я решил, что не могу передавать несколько файлов сразу) Так описываем запрос для ретрофит: @Multipart @PUT("/upload") Call<ResponseBody> upload(@Header("X-Security-Key") String token, @Part List<MultipartBody.Part> files); Так выполняем: Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(LoganSquareConverterFactory.create()) .build(); final RestAPI service = retrofit.create(RestAPI.class); List<MultipartBody.Part> files = new ArrayList<>(); String path = getOutputMarkStorage() + File.separator; for (int i = 0; i < model.getVideo_list().size(); i++) { File file = new File(path + model.getVideo_list().get(i)); // create RequestBody instance from file RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part is used to send also the actual file name MultipartBody.Part file_body = MultipartBody.Part.createFormData("video" + i, file.getName(), requestFile); files.add(file_body); } Call<ResponseBody> call = service.upload(context.getSharedPreferences("detail", Context.MODE_PRIVATE).getString(Constants.TOKEN, "null"), files);
{ "pile_set_name": "StackExchange" }
Q: 2d array sort wih conditions i have 2d array which consist of ). 1st row for y axis coordinate of point(i) ). 2nd row for x axis coordinate of point(i) ). i let consider following a(1,:)=[1,2,3,4,10,11,12,13,19,20,21,22]; a(2,:)=[4,1,3,2,4,3,1,2,3,2,4,1]; a(3,:)=[1,2,3,4,5,6,7,8,9,10,11,12]; according to the above array 'a' it shows that it is shorted according to the first column(according to y coordinates). but in my case i want to sort them with following steps identify the position where the difference between two consecutive values of y coordinates (values of a(a,:)) changes rapidly and sort the values between those rapidly change with respect to x coordination (a(2,:)) let consider the following a = 1 2 3 4 10 11 12 13 19 20 21 22 4 1 3 2 4 3 1 2 3 2 4 1 1 2 3 4 5 6 7 8 9 10 11 12 0 1 1 1 6 1 1 1 6 1 1 1 here 4th row represent the difference between two consecutive y coordinates (a(1,:)) in there 5th value shows rapid change so i want consider first 4 value set and analyze the x and y coordinates w.r.t x coordinate (a(2,:)) in same way for whole array and following array represented the expected results. a = 2 4 3 1 12 13 11 10 22 20 19 21 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 5 6 7 8 9 10 11 12 0 1 1 1 6 1 1 1 6 1 1 1 note by: the 3rd column value should not be changed. the rapid changed is not obtained in same period like in above it varying.(in my case it happened after every 4 values ) the rapid change is not 6 for every instant (let the solution should convenience for values greater than 3) can any one help me to code this* A: I am a little confused as to what you want. This code will group your array into blocks where they change only by a normal amount (specified by variable normalchange). It will produce a cell array where each cell is a group of similar elements. In this instance normal change is 1 then you get three groups. Let me know if this helps. a(1,:)=[1,2,3,4,10,11,12,13,19,20,21,22]; a(2,:)=[4,1,3,2,4,3,1,2,3,2,4,1]; a(3,:)=[1,2,3,4,5,6,7,8,9,10,11,12]; interestedmembers=0; thingtoanalyse={}; startOfMembers=1; normalchange = 1; for i=2:size(a,2) if a(1,i)-a(1,i-1) > normalchange thingtoanalyse{end+1}=a(:,startOfMembers:startOfMembers+... interestedmembers); interestedmembers=0; startOfMembers = i-1; end interestedmembers = interestedmembers+1; end % catch everything after the last jump and classify as interesting. thingtoanalyse{end+1} = a(:,startOfMembers:end);
{ "pile_set_name": "StackExchange" }
Q: Enabling debugging for a Node in Weblogic Cluster I have a Weblogic (10.3.5) AdminServer instance and two nodes running as a part of the cluster. I followed the instructions on this page and added a setting in startweblogic.cmd to enable debugging at port 4000. All is fine and I'm able to connect to this port to debug. But when I fire up a node in the cluster using the following command, I get an error saying that 4000 is used up. Here is the command I use to start the node and the error I get c:\Oracle\Middleware\user_projects\domains\base_domain\bin\startManagedWebLogic.cmd server1 http://adminServer_host_name:7001 starting weblogic with Java version: java version "1.6.0_24" Java(TM) SE Runtime Environment (build 1.6.0_24-b50) Java HotSpot(TM) Client VM (build 19.1-b02, mixed mode) Starting WLS with line: C:\Oracle\MIDDLE~1\JDK160~1\bin\java -client -Xms256m -Xmx512m -XX:CompileThre shold=8000 -XX:PermSize=1028m -XX:MaxPermSize=1024m -Dweblogic.Name=myhealth1 - Djava.security.policy=C:\Oracle\MIDDLE~1\WLSERV~1.3\server\lib\weblogic.policy - Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n - Xverify:none -da -Dplatform.home=C:\Oracle\MIDDLE~1\WLSERV~1.3 -Dwls.home=C:\Or acle\MIDDLE~1\WLSERV~1.3\server -Dweblogic.home=C:\Oracle\MIDDLE~1\WLSERV~1.3\se rver -Dweblogic.management.discover=false -Dweblogic.management.server=http:// DJX09cs1.co.ihc.com:7001 -Dwlw.iterativeDev=false -Dwlw.testConsole=false -Dwlw .logErrorsToConsole=false -Dweblogic.ext.dirs=C:\Oracle\MIDDLE~1\patch_wls1035\p rofiles\default\sysext_manifest_classpath;C:\Oracle\MIDDLE~1\patch_ocp360\profil es\default\sysext_manifest_classpath -Dweblogic.management.username=weblogic -Dw eblogic.management.password=weblogic1 weblogic.Server ERROR: transport error 202: bind failed: Address already in use ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510) JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../. ./../src/share/back/debugInit.c:690] FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_E RROR_TRANSPORT_INIT(197) This is crazy because the node is probably trying to enable debugging on the same port 4000 which the adminserver is set to. How can I set it up so that I can have debugging capabilities enabled on the nodes alone and not the adminserver? I tried adding the following config to startmanagedserver.cmd etc. but no dice. set JAVA_OPTIONS=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n A: Modifying startWebLogic.cmd is fine. But the thing is you are running in a domain with servers different from the admin server, which is not the case covered by the 'page' your provided. The only thing you need to do to fix this is to add a guarding condition before setting JAVA_OPTIONS in startWebLogic.cmd. Something like: if serverName=='managedServer1' then JAVA_OPTIONS="....debug_options....normal_options" else JAVA_OPTIONS="normal_options" endif OR if serverName=='managedServer1' then JAVA_OPTIONS="....debug_options....%JAVA_OPTIONS%" endif Sorry I can't remember exact syntax rules for this, please check details for your windows platform.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between 襲う、撃つ、and 襲撃? Based on their kanjis, they all appear to have the meaning of attack, and I think that is what makes them similar. How does one distinguish their uses? I would also appreciate a (brief) explanation of how the component kanjis of 襲撃 contribute to the meaning of this 熟語. A: 襲う and 襲撃(する) are a wago-kango pair (wago-and-kango). They are often interchangeable, but 襲撃 sounds more formal, and its usage is limited to violent attacks by brute force. 襲う has a little broader usages, and we can say 彼を不幸が襲う, (サッカー)選手がゴールを襲う and ウイルスが町を襲う, too. 撃つ is just "to shoot someone (with a gun, cannon, etc)" or "to shoot (a gun, etc)". There is also 討つ, which is an uncommon literary word meaning "to hit (and kill, often under the name of justice)".
{ "pile_set_name": "StackExchange" }
Q: Google Analytics V3 ASP.Net API beta 1.5 OAuth2 error I'm using the latest beta 1.5 (1.5.0.28991) of Google APIs with a service account, and am hitting this error on the AssertionFlowClient line when doing auth: Method not found: 'Void DotNetOpenAuth.OAuth2.ClientBase..ctor(DotNetOpenAuth.OAuth2.AuthorizationServerDescription, System.String, System.String)'. DotNetOpenAuth V4.3.1.13153 AuthorizationServerDescription desc = GoogleAuthenticationServer.Description; X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable); AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope }; I'm breaking my head over this - any pointers will be appreciated. A: Download the sample from... https://code.google.com/p/google-api-dotnet-client/source/browse/Plus.ServiceAccount/Program.cs?repo=samples (The download link has a bad certificate, so you can't use Chrome to download it, you have to use IE) Steal the packages.config and app.config files from the "Plus.ServiceAccount" project and place them in your project. Reload your project, then on the "Package Manager Console" when it asks to download the packages, let it. That made the error go away for me. I must have been using the wrong version of...something.
{ "pile_set_name": "StackExchange" }
Q: Animating lazy load of ArrayAdapter Hello I was using animation for an ArrayAdapter. I want to animate a thumbnail when its loaded... However every time any thumbnail of the list is loaded, the animation starts for every items of the array adapter. As consequence, the animation of each thumbnail is started 5 times. What do I have to do to prevent starting animation when any of the items is loaded? public View getView(int position, View item, ViewGroup parent){ ViewHolder holder; Video video = mVideoList.get(position); if(item == null) { item = mInflater.inflate(R.layout.adapter_recommended_videos, null); holder = new ViewHolder(); holder.title = (TextView)item.findViewById(R.id.adapter_recommended_videos_textview); holder.thumb = (ImageView)item.findViewById(R.id.adapter_recommended_videos_imageview); holder.title.setTypeface( Typeface.createFromAsset(mContext.getAssets(), "roboto_medium.ttf")); item.setTag(holder); } else { holder = (ViewHolder) item.getTag(); } holder.title.setText(video.getTitle()); ImageView iv = holder.thumb; if (video.getThumb() != null) { if(!mAnimationFlags.get(position)){ iv.startAnimation(mAnimation); mAnimationFlags.set(position, true); } holder.thumb.setImageBitmap(video.getThumb()); } else { holder.thumb.setImageResource(R.drawable.dummy_video_thumbnail); } return(item); } static class ViewHolder { TextView title; ImageView thumb; } A: Nevermind, I solved it by myself, I only had to instantiate a new animation in each call of ´getView()´. Here is the proper code: public View getView(int position, View item, ViewGroup parent){ ViewHolder holder; Video video = mVideoList.get(position); if(item == null) { item = mInflater.inflate(R.layout.adapter_recommended_videos, null); holder = new ViewHolder(); holder.title = (TextView)item.findViewById(R.id.adapter_recommended_videos_textview); holder.thumb = (ImageView)item.findViewById(R.id.adapter_recommended_videos_imageview); holder.title.setTypeface( Typeface.createFromAsset(mContext.getAssets(), "roboto_medium.ttf")); item.setTag(holder); } else { holder = (ViewHolder) item.getTag(); } holder.title.setText(video.getTitle()); ImageView iv = holder.thumb; if (video.getThumb() != null) { if(!mAnimationFlags.get(position)){ Animation anim = AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in); iv.startAnimation(anim); mAnimationFlags.set(position, true); } holder.thumb.setImageBitmap(video.getThumb()); } else { holder.thumb.setImageResource(R.drawable.dummy_video_thumbnail); } return(item); }
{ "pile_set_name": "StackExchange" }
Q: how to debug 'extern' in c with vscode I'm not familiar with c compiler,I know how to use gcc or g++ in terminal I have main.c #include <stdio.h> int count; extern void write_extern(); int main() { count = 5; write_extern(); } support.c #include <stdio.h> extern int count; void write_extern(void) { printf("count is %d\n", count); } gcc main.c support.c and the output file a.out works fine but if I debug with vscode or code-runner plugin error shows /"main Undefined symbols for architecture x86_64: "_write_extern", referenced from: _main in main-217186.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) my launch.json and task.json look like this: "configurations": [ { "name": "clang build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/${fileBasenameNoExtension}", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "lldb", "preLaunchTask": "clang build active file" } ] { "tasks": [ { "type": "shell", "label": "clang build active file", "command": "/usr/bin/clang", "args": [ "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "/usr/bin" } } ], "version": "2.0.0" } how to config this? A: By default, the task only compiles the currently open file, so you need to change your prelaunch task to compile everything you need. You can create a custom task for this like the following: { "tasks": [ { "type": "shell", "label": "clang build active file", "command": "/usr/bin/clang", "args": [ "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "/usr/bin" } }, { "type": "shell", "label": "clang build custom", "command": "/usr/bin/clang", "args": [ "-g", "${fileDirname}/main.c", "${fileDirname}/support.c", "-o", "${fileDirname}/main" ], "options": { "cwd": "/usr/bin" }, "problemMatcher": [ "$gcc" ], "group": "build" } ], "version": "2.0.0" } And then update your launch.json to use the new task: "configurations": [ { "name": "clang build and debug custom project", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/${fileBasenameNoExtension}", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "lldb", "preLaunchTask": "clang build custom" } ]
{ "pile_set_name": "StackExchange" }
Q: Pass a PHP string to a Javascript variable with Ajax I retrieve data from my database as such: while($row = mysql_fetch_array($result)) { echo $row['uid']; echo $row['note']; } and I print it with ajax as such: xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { console.log(xmlhttp.responseText) } } but the problem is that the uid and note its one string. For example: "45 note goes here" How can I print each row separately. Something like this: xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { console.log( <?php echo json_encode($row['uid']); ?> ); console.log( <?php echo json_encode($row['note']); ?> ); } } A: You're pretty much right. In your php script, return a json string, then in your javascript you can parse that string into a javascript object. So: $json = array(); while($row = mysql_fetch_array($result)) { $json['uid']=$row['uid']; $json['note']=$row['note']; } print json_encode($json); Then xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var jsontext = xmlhttp.responseText; var json = JSON.parse(jsontext); console.log(json.uid) console.log(json.note) } }
{ "pile_set_name": "StackExchange" }
Q: Creating a group of vertical buttons - Ionic I want something similar to this: http://imgur.com/a/JT5cI I do not want a side menu - since my views don't require side menu. I've tried using ionic col view layout but it creates a mess - I want the button group to take 100% height of the window and not slide other content to the right. Please help. Thank you. A: If I understood everything right, you want position: fixed; on your div that contains all the icons. Try these styles on that div: position: fixed; top: 0; bottom: 0; left: 0;
{ "pile_set_name": "StackExchange" }
Q: TypeError: expected string or bytes-like object while trying to plot data from a dataframe """ I am trying to plot a graph from data retrieved from a CSV file. The code is as below """ path = '/Users/pradeepallath/Documents/000_Edureka_Training/001_PredictiveAnalysis/Weather_WWII' import pandas as pd dataset = pd.read_csv(path+'/Weather.csv',low_memory=False,nrows=1000) dataset.plot(x='MinTemp',y='MaxTemp',style=0) plt.plot() """ I am Getting this error. Please note I am new to Python Traceback (most recent call last): File "/Users/pradeepallath/Documents/Pycharm/Big_Mart_Sale/Mean_Sale.py", line 13, in <module> dataset.plot(x='MinTemp',y='MaxTemp',style=0) File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py", line 794, in __call__ return plot_backend.plot(data, kind=kind, **kwargs) File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/__init__.py", line 62, in plot plot_obj.generate() File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/core.py", line 281, in generate self._make_plot() File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/core.py", line 1063, in _make_plot style, kwds = self._apply_style_colors(colors, kwds, i, label) File "/Users/pradeepallath/anaconda3/lib/python3.7/site-packages/pandas/plotting/_matplotlib/core.py", line 723, in _apply_style_colors nocolor_style = style is None or re.match("[a-z]+", style) is None File "/Users/pradeepallath/anaconda3/lib/python3.7/re.py", line 173, in match return _compile(pattern, flags).match(string) TypeError: expected string or bytes-like object Thanks for the assistance """ A: It's taking issue with style=0. Pandas supports matplotlib line styles. Here is a good stackoverflow question on how you can see valid options, but essentially the integer zero is not a valid line style.
{ "pile_set_name": "StackExchange" }
Q: What's the ideal database table structure for forum posts and replies? I have been trying to create an online discussion forum as a fun project. In this application, registered users can create a "topic". Other users can reply to that topic (lets call them "posts"). Also, people can "reply" to posts . However, reply to "replies" is not required at present. I thought of creating a DB schema like this But, the posts and replies table basically contain the same kind of fields. Only exception is that- the topic_id column in posts table will refer to topics table and post_id column in replies table will refer to the posts table So, if I have to keep only one table for posts and replies, how do I manage the relationship between "topics and posts" and "posts and replies" ? What would be the ideal solution in this case? Or Should I just keep my existing schema? Thanks! A: You can keep one table only for posts and replies. For the relationship between post and reply add a new column names post_id. This column can be null for post, and in the case of reply insert id of the post.
{ "pile_set_name": "StackExchange" }
Q: Web Api 2.0 Routing - multiple actions matching I have this WebAPI controller, having 2 methods. This controller is more of a utility type controller, and not really focusing on one type of entity, like most examples and boiler-plate template will generate. Anyway, my 2 methods are something like this: // api/Custom/SayHello [HttpGet] public async Task<string> SayHello() { return await Task.FromResult("Hello World Async").ConfigureAwait(false); } // api/Custom/SayFloat [HttpGet] public async Task<float> SayFloat() { return await Task.FromResult(1000.0f).ConfigureAwait(false); } And I've gone through a lot of routing template combinations, and my latest one is this: config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }); /* ----- this is trying to match my utility controller and its actions ----- */ config.Routes.MapHttpRoute( name: "ActionApi", routeTemplate: "Api/{controller}/{action}" ); I'm getting this error: Multiple actions were found that match the request .... So my current "workaround", is to create one controller, per utility method that I want to expose. I'm thinking that there's gotta be something that I haven't tried with the routing template. Any ideas? A: The other answer to this question is correct. However, I wanted to offer an alternative which I am a fan of, Attribute Routing. The first release of Web API used convention-based routing. In that type of routing, you define one or more route templates, which are basically parameterized strings. When the framework receives a request, it matches the URI against the route template. With Attribute Routing, on the other hand, you decorate your Controllers and Actions with Attributes which allows for a much more flexible routing scheme. [Route("api/custom")] public class CustomController : ApiController ... // api/Custom/SayHello [Route("SayHello")] [HttpGet] public async Task<string> SayHello() { return await Task.FromResult("Hello World Async").ConfigureAwait(false); } // api/Custom/SayFloat [Route("SayFloat")] [HttpGet] public async Task<float> SayFloat() { return await Task.FromResult(1000.0f).ConfigureAwait(false); }
{ "pile_set_name": "StackExchange" }
Q: List of platforms supported by the C standard Does anyone know of any platforms supported by the C standard, for which there is still active development work, but which are: not 2's complement or the integer width is not 32 bits or 64 bits or some integer types have padding bits or if you worked on a 2's complement machine, the bit pattern with sign bit 1 and all value bits zero is not a valid negative number or integer conversion from signed to unsigned (and vice versa) is not via verbatim copying of bit patterns or right shift of integer is not arithmetic shift or the number of value bits in an unsigned type is not the number of value bits in the corresponding signed type + 1 or conversion from a wider int type to a smaller type is not by truncation of the left most bits which would not fit EDIT: Alternatively, if there are platforms in the period 1995 to 1998 which influenced the C99 decision to include the above, but which were discontinued, I would be interested in them also. EDIT: The C rationale has this to say about padding bits: Padding bits are user-accessible in an unsigned integer type. For example, suppose a machine uses a pair of 16-bit shorts (each with its own sign bit) to make up a 32-bit int and the sign bit of the lower short is ignored when used in this 32-bit int. Then, as a 32-bit signed int, there is a padding bit (in the middle of the 32 bits) that is ignored in determining the value of the 32-bit signed int. But, if this 32-bit item is treated as a 32-bit unsigned int, then that padding bit is visible to the user’s program. The C committee was told that there is a machine that works this way, and that is one reason that padding bits were added to C99. Footnotes 44 and 45 mention that parity bits might be padding bits. The committee does not know of any machines with user-accessible parity bits within an integer. Therefore, the committee is not aware of any machines that treat parity bits as padding bits. So another question is, what is that machine which C99 mentioned? EDIT: It seems that C99 was considering removing support for 1's complement and signed magnitude: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n868.htm http://www.open-std.org/jtc1/sc22/wg14/www/docs/n873.htm (search for 6.2.6.2) A: It should be noted that you cannot rely on undefined behaviour even on commonly used platforms, because modern optimizing compilers perform program transformations that only preserve defined behaviour. In particular, you cannot rely on two's complement arithmetic giving you INT_MAX+1 == INT_MIN. For example, gcc 4.6.0 optimizes the following into an infinite loop: #include <stdio.h> int main() { int i = 0; while (i++ >= 0) puts("."); return 0; } EDIT: See here for more on signed overflow and GCC optimizations. A: About a decade ago we had to port our C embedded database to a DSP processor that happened to be the main processor of a car stereo. It was a 24-bit machine, in the worst way: sizeof(char) == sizeof(int) == sizeof(void*) == 1, which was 24 bits. We named the branch that dealt with this port "24-bit hell". Since then we ported our library to many platforms, but none as weird as that. They may still be out there (cheap 24-bit DSP chips are even cheaper now), found in low-cost devices where ease of programming is a distant second to a low bill of materials (BOM). Come to think of it, I think we did encounter a machine where a right shift of an unsigned integer did not necessarily insert zero bits. Even so, highly nonstandard arithmetic rules on a platform guarantee challenging, error-prone porting of software to it, which dramatically increases software development costs. At some point sanity prevails and standards are observed. I suspect that a lot of the motivation for the presence of these rules in C99 is their presence in C89, and earlier iterations of the language. Don't forget that when C was invented, computers were a lot more diverse than they are today. "Bit-slice" processor designs were available where you could add as many bits as you wanted to your processor just by adding chips. And before C you had to code in assembly language or worry about exactly where in RAM your code would reside, etc. C was a dramatic step forward in terms of portability, but it had to corral a diverse range of systems, hence the very general rules. 20 years later, when Java came around, it had the benefit of history to allow it to declare up-front how big primitive types were to be, which makes everything a lot easier, as long as Java's choices are sound. I know you are mostly asking about integers, but I have encountered some weirdness when it comes to pointers. Early Macintosh computers had 32-bit processors (Motorola 68000), but only 24-bit memory busses. Thus 0x00123456 and 0xFF123456 referred to the same memory cell, because the processor chopped off the upper 8 bits when accessing RAM. Apple engineers used these bits to store metadata about the memory that the pointer pointed to. Thus when comparing pointers, one had to mask off the upper bits first. And don't get me started on the segmented memory architectures of the x86. :) Since we are on this topic, take a look at the MISRA coding standard, which is favored by makers of automobiles that need maximum portability and safety. Also look at Hacker's Delight by Henry S. Warren, which has tons of useful bit twiddling tricks in it. A: I recently worked at a company which still used a version of the PDP-10, and a port of GCC to that platform. The 10 we used had a few of the attributes you list: Integers are not 32 or 64 bits they are 36 bits wide. Padding bits are used for some representations. For extended precision integers (e.g. of long long type), the underlying representation was 72-bits in which each of the 36-bit words had a sign-bit. In addition to the above unusual attributes, there was the issue that the machine had several different byte addressing mechanisms. Bytes with widths in the range of 6-12 bits wide could be addressed by using special bits in the address itself which indicated which width and word alignment was being used. To represent a char* one could use a representation which would address 8-bit bytes, all of which were left-aligned in the word, leaving 4-bits in each 36-bit word which were not addressed at all. Alternatively 9-bit bytes could be used which would fit evenly into the 36-bit word. Both such approaches had there pitfalls for portability, but at the time I left it was deemed more practical to use the 8-bit bytes because of interaction with TCP/IP networking and standard devices which often think in terms of 16, 24, or 32-bit fields which also have an underlying structure of 8-bit bytes. As far as I know this platform is still being used in products in the field, and there is a compiler developer at this company keeping relatively recent versions of GCC up to date in order to allow for further C development on this platform.
{ "pile_set_name": "StackExchange" }
Q: Counting tab views in the Facebook Graph API How do I go about counting basic tab views, like Wall, Videos, Photos, etc.? I see this information in the new Insights/Reach, but can't find it in the Graph API at all. I can see all my tabs in the {page id}/tabs graph, but there are no view counts (and what a great place to put them... Facebook, are you listening? ;) I did try a Page Insights on the tab page ID that I got from the /tabs graph, e.g.: {tab page id}/insights ... but the user doesn't seem to be an admin for those pages (they're run by an agency user). I'll look to gain Admin access to those tab pages, then post back here when I find out. Any insight until then would be greatly appreciated. A: "Any insight until then would be greatly appreciated." You will want to use the FQL insight table to get at specific insight values. See: http://developers.facebook.com/docs/reference/fql/insights/
{ "pile_set_name": "StackExchange" }
Q: "URL GOTO" keeps looping from iMacros javascript I have two files in the folder ~/iMacros/Macros/ that are related. One is an imacro (TodaysEvents.iim) like below: VERSION BUILD=8920312 RECORDER=FX TAB T=1 URL GOTO=http://www.event.com/schedual SET !EXTRACT_TEST_POPUP NO SET !ERRORIGNORE YES TAG POS={{loop}} TYPE=A ATTR=TXT:02 EXTRACT=HTM SAVEAS TYPE=EXTRACT FOLDER=/root/Desktop FILE=TodaysEvents.csv TAB CLOSE And the other is a javascript file (TodaysEvents.js) like below: var i; for (i = 1; i < 130; i++) { iimSet("loop", i); iimPlay("TodaysEvents"); } The way I use them together is: firefox "imacros://run/?m=TodaysEvents.js" When I used these files, I desired to have all the loops completed in the imacros script by only loading the website once. However, in order to do that from the command line I have to run it from a JavaScript file, hence the two files. The problem is, although the looping works, the website is reloaded for each loop. Which file do I edit, and how, so the site is loaded only once, and all the extraction loops are carried out? A: Use only one file "TodaysEvents.js". And let it be like this: const L = "\n"; iimPlayCode("TAB T=1" + L + "URL GOTO=http://www.event.com/schedual" + L); for (i = 1; i < 130; i++) { iimSet("loop", i); iimPlayCode("SET !ERRORIGNORE YES" + L + "TAG POS={{loop}} TYPE=A ATTR=TXT:02 EXTRACT=HTM" + L + "SAVEAS TYPE=EXTRACT FOLDER=/root/Desktop FILE=TodaysEvents.csv" + L); }
{ "pile_set_name": "StackExchange" }
Q: Test website on real iPad on macOS For responsive tests on macOS I'm using Xcode and his simulator, but I found something strange going on on real iPad and I want to test it. Is I possible that I pair my iPad with Mac Mini and test it with Inspect Element like I was testing with the simulator? A: On the iOS device, open Settings → Safari → Advanced and enable Web Inspector. Connect the device to your Mac over USB and open the website in Safari on your iOS device. On your Mac, open Safari → Preferences → Advanced and enable Show Develop menu in menu bar. Choose Develop → your iOS device name → your Safari window to open the web inspector for the iOS device on your Mac.
{ "pile_set_name": "StackExchange" }
Q: (When) Should I learn compilers? According to this http://steve-yegge.blogspot.com/2007/06/rich-programmer-food.html article, I defnitely should. Quote Gentle, yet insistent executive summary: If you don't know how compilers work, then you don't know how computers work. If you're not 100% sure whether you know how compilers work, then you don't know how they work. I thought that it was a very interesting article, and the field of application is very useful (do yourself a favour and read it) But then again, I have seen successful senior sw engineers that didn’t know compilers very well, or internal machine architecture for that matter, but did know a thing or two of each item in the following list : A programming paradigm (OO, functional,…) A programming language API (C#, Java..) and at least 2 very different some say! (Java / Haskell) A programming framework (Java, .NET) An IDE to make you more productive (Eclipse, VisualStudio, Emacs,….) Programming best practices (see fxcop rules for example) Programming Principles (DRY, High Cohesion, Low Coupling, ….) Programming methodologies (TDD, MDE) Design patterns (Structural, Behavioural,….) Architectural Basics (Tiers, Layers, Process Models (Waterfall, Agile,…) A Testing Tool (Unit Testing, Model Testing, …) A GUI technique (WPF, Swing) A documenting tool (Javadoc, Sandcastle..) A modelling languague (and tool maybe) (UML, VisualParadigm, Rational) (undoubtedly forgetting very important stuff here) Not all of these tools are necessary to be a good programmer (like a GUI when you just don’t need it) but most of them are. Where do compilers come in, and are they really that important, since, as I mentioned, lots of programmers seems to be doing fine without knowing them and especially, becoming a good programmer is seen the multitude of knowledge domains almost a lifetime achievement :-) , so even if compilers are extremely important, isn't there always stuff still more important? Or should i order 'The Unleashed Compilers Unlimited Bible (in 24H..))) today? For those who have read the article, and want to start studying right away : Learning Resources on Parsers, Interpreters, and Compilers A: If you just want to be a run-of-the-mill coder, and write stuff... you don't need to take compilers. If you want to learn computer science and appreciate and really become a computer scientist, you MUST take compilers. Compilers is a microcosm of computer science! It contains every single problem, including (but not limited to) AI (greedy algorithms & heuristic search), algorithms, theory (formal languages, automata), systems, architecture, etc. You get to see a lot of computer science come together in an amazing way. Not only will you understand more about why programming languages work the way that they do, but you will become a better coder for having that understanding. You will learn to understand the low level, which helps at the high level. As programmers, we very often like to talk about things being a "black box"... but things are a lot smoother when you understand a little bit about what's in the box. Even if you don't build a whole compiler, you will surely learn a lot. You will get to see the formalisms behind parsing (and realize it's not just a bunch of special cases hacked together), and a bunch of NP complete problems. You will see why the theory of computer science is so important to understand for practical things. (After all, compilers are extremely practical... and we wouldn't have the compilers we have today without formalisms). I really hope you consider learning about them... it will help you get to the next level as a computer scientist :-). A: You should learn about compilers, for the simple reason that implementing a compiler makes you a better programmer. The compiler will surely suck, but you will have learned a lot during the way. It is a great way of improving (or practising) your programming skill. A: You do not need to understand compilers to be a good programmer, but it can help. One of the things I realized when learning about them, is that compiling is simply a translation. If you have ever translated from one language to another, you have just done compiling. So when should you learn about compilers? When you want to, or need it to solve a problem.
{ "pile_set_name": "StackExchange" }
Q: How check if website support http, htts and www prefix with scrapy I am using scrapy to check, if some website works fine, when I use http://example.com, https://example.com or http://www.example.com. When I create scrapy request, it works fine. for example, on my page1.com, it is always redirected to https://. I need to get this information as return value, or is there better way how to get this information using scrapy? class myspider(scrapy.Spider): name = 'superspider' start_urls = [ "https://page1.com/" ] def start_requests(self): for url in self.start_urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): url = response.url # removing all possible prefixes from url for remove in ['https://', 'http://', 'www.']: url = str(url).replace(remove, '').rstrip('/') # Try with all possible prefixes for prefix in ['http://', 'http://www.', 'https://', 'https://www.']: yield scrapy.Request(url='{}{}'.format(prefix, url), callback=self.test, dont_filter=True) def test(self, response): print(response.url, response.status) The output of this spider is this: https://page1.com 200 https://page1.com/ 200 https://page1.com/ 200 https://page1.com/ 200 This is nice, but I would like to get this information as return value to know, that e.g. on http is response code 200 and than save it to dictionary for later processing or save it as json to file(using items in scrapy). DESIRED OUTPUT: I would like to have dictionary named a with all information: print(a) {'https://': True, 'http://': True, 'https://www.': True, 'http://www.': True} Later I would like to scrape more information, so I will need to store all information under one object/json/... A: Instead of using the meta possibility which was pointed out by eLRuLL you can parse request.url: scrapy shell http://stackoverflow.com In [1]: request.url Out[1]: 'http://stackoverflow.com' In [2]: response.url Out[2]: 'https://stackoverflow.com/' To store the values for different runs together in one dict/json you can use an additional pipeline like mentioned in https://doc.scrapy.org/en/latest/topics/item-pipeline.html#duplicates-filter So you have something like: Class WriteAllRequests(object): def __init__(self): self.urldic={} def process_item(self, item, spider): urldic[item.url]={item.urlprefix=item.urlstatus} if len(urldic[item.url])==4: # think this can be passed to a standard pipeline with a higher number writedata (urldic[item.url]) del urldic[item.url] You must additionally activate the pipeline
{ "pile_set_name": "StackExchange" }
Q: How to download video from dailymotion? I have to download videos from dailymotion. I searhed for java libraries and apis but I couldn't find anything useful. I learnt selenium at last and tried to use websites for video downloading manually like savefrom etc. Dailymotion videos can't be downloaded from any website right now. Is there a common way to video download form any website. If there is not, can you help me with dailymotion, spesifically? A: I've used Selenium to download videos. It opens savefrom.net in chrome browser, paste a link that is taken from a dailymotion video and just click download button. You can download videos with this way from any website. System.setProperty("webdriver.chrome.driver", "C:\\Users\\Faruk\\IdeaProjects\\Dailymotion\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://en.savefrom.net"); WebElement textField = driver.findElement(By.id("sf_url")); textField.sendKeys("https://www.dailymotion.com/video/x737y37"); WebElement button = driver.findElement(By.id("sf_submit")); button.click(); try { TimeUnit.SECONDS.sleep(15); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElement(By.linkText("Download")).click();
{ "pile_set_name": "StackExchange" }
Q: Set default properties in a library with spring-boot I have many different services using spring-boot. I'd like to set up some configuration that is common for each, but allow the services to have their own properties and override them if they want. Example properties include spring.show_banner, management url ones, etc. How can I do this? If I have the following: service-common with src/main/resources/application.yml with default properties service1 with src/main/resources/application.yml with its own properties I'd like them to be merged with the service1 version taking precedence. Instead, it seems that only the first one found on the classpath is used. (Alternatively, using @Configuration classes would be even better, but I'm not sure they can be used to define many of the properties) A: There are several options available to you, all based on the order in which property sources are considered. If your common library is responsible for creating the SpringApplication it can use setDefaultProperties. These values can be overridden by your services' application.properties. Alternatively, your library could use @PropertySource on one of its @Configuration classes to configure, for example, library.properties as a source. Again, these properties could then be overriden in your services' application.properties.
{ "pile_set_name": "StackExchange" }
Q: Initialization On Demand Holder idiom This is the implementation mostly seen on the web private static class LazySomethingHolder { public static Something something = new Something(); } public static Something getInstance() { return LazySomethingHolder.something; } Is the following simpler variation correct, if not what is wrong with it? Is the problem specific to java or also present in C++? public static Something getInstance() { private static Something something = new Something(); return something; } A: You cannot have static local variables in Java. Simpler alternatives are private static final Something something = new Something(); public static Something getInstance() { return something; } or my preference if for. enum Something { INSTANCE; } The only problem with these patterns is that if you have multiple instances you want lazily loaded, you need to have a class each, or loading one will mean loading them all.
{ "pile_set_name": "StackExchange" }
Q: Typescript reduce object array by specific value I have this: 0: {orderType: "orderType1", orderCount: 0, orderDate: 47} 1: {orderType: "orderType1", orderCount: 21, orderDate: 47} 2: {orderType: "orderType1", orderCount: 3, orderDate: 47} 3: {orderType: "orderType1", orderCount: 5, orderDate: 48} 4: {orderType: "orderType1", orderCount: 32, orderDate: 48} 5: {orderType: "orderType1", orderCount: 12, orderDate: 48} and I would like to achieve this: 0: {orderType: "orderType1", orderCount: 24, orderDate: 47} 1: {orderType: "orderType1", orderCount: 49, orderDate: 48} Basically I want to 'combine' or 'reduce' the entries by combining the orderCount based on orderDate. Apologies if combine or reduce are not the right terms here. A: Someone smarter than me can probably do this more succinctly, but if I group the data and then reduce it I can get the desired result. I have a feeling this could be done in fewer steps: function setFilter(value, index, self) { return self.indexOf(value) === index; } function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); } const data = [ { orderType: "orderType1", orderCount: 0, orderDate: 47 }, { orderType: "orderType1", orderCount: 21, orderDate: 47 }, { orderType: "orderType1", orderCount: 3, orderDate: 47 }, { orderType: "orderType1", orderCount: 5, orderDate: 48 }, { orderType: "orderType1", orderCount: 32, orderDate: 48 }, { orderType: "orderType1", orderCount: 12, orderDate: 48 } ]; const groupedData = groupBy(data, 'orderDate'); const reducedData = []; for (let key in groupedData) { let initialValue = 0; let sum = groupedData[key].reduce((accumulator, currentValue) => { return accumulator + currentValue.orderCount; },initialValue) reducedData.push({ orderType: groupedData[key][0].orderType, orderCount: sum, orderDate: key }); } console.log(reducedData); This doesn't take into account orderType and I feel it ought to.
{ "pile_set_name": "StackExchange" }
Q: Android: spinner works in Activity but not Fragment So I was able to make a Spinner work in a single Activity, but when I transferred the code to a Fragment it obviously didn't work. I am getting an error in these two lines: ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_array, android.R.layout.simple_spinner_item); ArrayAdapter<String> adapterItem = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, suggestedItems); and I know that the context this needs to be changed. I already tried to use getActivity(), but that didn't work as well. Some insight needed! Thank you! public class NominateFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_nominate_page, container, false); //SPINNER Spinner spinner = (Spinner)getView().findViewById(R.id.category); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_array, android.R.layout.simple_spinner_item); // Create an ArrayAdapter using the string array and a default spinner layout adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Specify the layout to use when the list of choices appears spinner.setAdapter(adapter); // Apply the adapter to the spinner //AUTOCOMPLETE AutoCompleteTextView nominateItem = (AutoCompleteTextView)getView().findViewById(R.id.autocomplete_nominate_item); // Get a reference to the AutoCompleteTextView in the layout String[] suggestedItems = getResources().getStringArray(R.array.suggested_items_array); // Get the string array ArrayAdapter<String> adapterItem = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, suggestedItems); // Create the adapter and set it to the AutoCompleteTextView nominateItem.setAdapter(adapterItem); return view; } } A: replce this line: ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category_array, android.R.layout.simple_spinner_item); with ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item); and this line: Spinner spinner = (Spinner)getView().findViewById(R.id.category); with: Spinner spinner = (Spinner)view.findViewById(R.id.category); and: AutoCompleteTextView nominateItem = (AutoCompleteTextView)getView().findViewById(R.id.autocomplete_nominate_item); // Get a reference to the AutoCompleteTextView in the layout with: AutoCompleteTextView nominateItem = (AutoCompleteTextView)view.findViewById(R.id.autocomplete_nominate_item); // Get a reference to the AutoCompleteTextView in the layout
{ "pile_set_name": "StackExchange" }
Q: Scrapyd: How to retrieve spiders or version of a scrapyd project? It apears that either the documentation of scrapyd is wrong or that there is a bug. I want to retrieve the list of spiders from a deployed project. the docs tell me to do it this way: curl http://localhost:6800/listspiders.json?project=myproject So in my environment it looks like this: merlin@192-143-0-9 spider2 % curl http://localhost:6800/listspiders.json?project=crawler zsh: no matches found: http://localhost:6800/listspiders.json?project=crawler So the command seems not to be recognised. Lets check the project availability: merlin@192-143-0-9 spider2 % curl http://localhost:6800/listprojects.json {"node_name": "192-143-0-9.ip.airmobile.co.za", "status": "ok", "projects": ["crawler"]} Looks OK to me. Checking the docs again, the other API calls take a parameter not as a GET but in a different way: curl http://localhost:6800/schedule.json -d project=myproject -d spider=somespider Applying this to listspiders: merlin@192-143-0-9 spider2 % curl http://localhost:6800/listspiders.json -d project=crawler {"node_name": "192-143-0-9.ip.airmobile.co.za", "status": "error", "message": "Expected one of [b'HEAD', b'object', b'GET']"} Missing the GET parameter. So it looks like we are runnning in circles. How can one retrieve a list of spiders or version (listversion) with scrapyd? A: Maybe the url needs to be wrapped in double-quotes, Try curl "http://localhost:6800/listspiders.json?project=crawler"
{ "pile_set_name": "StackExchange" }
Q: how to get fraction as it is ( without getting itssimplest fraction )? i vainly tried using this: x=7 y=14 from fractions import Fraction print(Fraction(7/14)) I got answer 1/2 but I needed 7/14. is there any way to write as it is without using string? A: Most fraction libraries will simplify the numerator and denominator as soon as they are created as a performance optimization. If you are working with large unsimplified fractions there is a chance that they will overflow. So before each operation the fractions will have to be simplified anyway. If you want to keep the original numerator and denominator intact you should create your own wrapper class like so: class MyFraction: def __init__(self, numerator=1, denominator=1): self.numerator = numerator self.denominator = denominator def get_fraction(self): from fractions import Fraction return Fraction(numerator=self.numerator, denominator=self.denominator) def __repr__(self): return '{}/{}'.format(self.numerator, self.denominator) f = MyFraction(numerator=7, denominator=14) print(f) # prints 7/14 print(f.get_fraction()) # prints 1/2 Note: You should be invoking fraction using the Fraction(numerator=0, denominator=1) constructor. Is your case what is happening is: Fraction(7/14) => Fraction(0.5) => 1/2
{ "pile_set_name": "StackExchange" }
Q: nontype object has no function python3 I wrote a program is python3 but I don't understand why when I call the function printed it returns the right output but when I call the same function in "find()" I have a no type object. In particular I have the error at the fourth line of the function "find()" when I use keys on the variable data. Can you help me understanding what's going on? Thanks def printed(filename, day, time): try: f = open(filename) lines = f.readlines() d = defaultdict(list) start = lines.index(day+"\n") if day == 'Monday\n' or day == 'Tuesday\n' or day == 'Wednesday\n' or day == 'Thursday\n' or day == 'Friday\n': stop = lines.index("Saturday\n") elif day == 'Saturday\n': stop = lines.index("Sunday\n") else: stop = len(lines) hour = time[0] + time[1] minutes = time[3:] for line in lines[start:stop]: line = line.strip(",") line = line.replace("\n","") line = line.replace(" ","") line = line.split(".") key = line[0] if len(line) == 2: d[key] += [line[1]] d = dict(d) print(d) except IOError: print("File not found") program() ... def find(filename, day, time): try: data = printed(filename, day, time) data2 = [int(h) * 60 + int(m) for h in data.keys() for m in data[h]] start_hour, start_minute = map(int, time.split('.')) start = start_hour * 60 + start_minute end = start + 30 after = list(filter(lambda x: start <= x <= end, data2)) if len(after) == 0: return "\nThere is no bus for this time" return list(map(lambda x: '%02d.%02d' % (x // 60, x % 60), after)) except IOError: print("The file was not found") program() Here is the output of printed(): '12': ['06', '36', '06', '36'], '13': ['06', '36', '06', '36'], '11': ['06', '36', '06', '36'], '21': ['05', '35', '06', '35'], '18': ['11', '26', '41', '56', '06', '36'], '06': ['11', '26', '41', '56', '35'], '15': ['06', '36', '56', '06', '36'], '19': ['11', '40', '06', '35'], '17': ['11', '26', '41', '56', '06', '36'], '22': ['05', '35', '06', '35'], '07': ['11', '26', '41', '56', '05', '35'], '09': ['06', '36', '06', '36'], '20': ['05', '35', '06', '35'], '14': ['06', '36', '06', '36'], '10': ['06', '36', '06', '36'], '16': ['11', '26', '41', '56', '06', '36'], '23': ['05', '35', '06', '35'], '08': ['11', '26', '41', '06', '36']} A: Cuz you put a print at the end of the printed() function. To call it you have to put a return instead of a print. Change: print(d) with: return d
{ "pile_set_name": "StackExchange" }
Q: Engineers end of game victory point stronghold When an Engineer builds a Stronghold they get 3 victory points for each bridge. My question is when the game ends do they get this victory point bonus for each bridge again? I'm kinda confused because the rule book says the end-of-turn bonus cards do NOT yield their bonuses on the final round. I'm wondering if the same rule applies for favor tiles and the Engineer-bridge victory points. A: The bonus cards the rule book is referring to are the cards that flip at the beginning of each round (each with one ongoing effect and one end-of-round bonus effect). It's simply stating that the final end-of-turn bonus effect does not apply on the final round (hence the tiny half-bonus card they provide you with to cover up the second half).
{ "pile_set_name": "StackExchange" }
Q: VSE playhead position variable How can I return the playhead frame number position, in the VSE, to a variable in script? I'm not sure where in the API to look. A: The VSE current frame is the same as the current frame for the rest of blender, which is a property of the current scene. It can be accessed with bpy.context.scene.frame_current and set with bpy.context.scene.frame_set(frameNumber). The best way to figure out the Python code for a specific property is to find it in the interface and hover your cursor over it, which will reveal the python code. In this case you can hover your cursor over the frame values in a Timeline editor.
{ "pile_set_name": "StackExchange" }
Q: how to dispatch network requests to the (geographically) closest server I'm a Java coder and not very familiar with how networks work (other than basic UDP/TCP connections) Say I have servers running on machines in the US, Asia, Latin America and Europe. When a user requests a service, I want their request to go to the server closest to them. Is it possible for me to have one address: mycompany.com, and somehow get requests routed to the appropriate server? Apparently when someone goes to cnn.com, they receive the pictures, videos, etc. from a server close to them. Frankly, I don't see how that works. By the way, my servers don't serve web pages, they serve other services such as stock market data....just in case that is relevant. Since I'm a programmer, I'm interested to know how one would do it in software. Since this is little more than an idle curiosity, pointers to commercial products or services won't be very helpful in understanding this problem :) A: One simple approach would be to look at the first byte (Class A) of the IP address coming into the UDP DNS request and then based off that you could deliver the right geo-located IP.
{ "pile_set_name": "StackExchange" }
Q: Kubernetes persistent volume on Docker Desktop (Windows) I'm using Docker Desktop on Windows 10. For the purposes of development, I want to expose a local folder to a container. When running the container in Docker, I do this by specifying the volume flag (-v). How do I achieve the same when running the container in Kubernetes? A: You should use hostpath Volume type in your pod`s spec to mount a file or directory from the host node’s filesystem, where hostPath.path field should be of following format to accept Windows like paths: /W/fooapp/influxdb //W/fooapp/influxdb /////W/fooapp/influxdb Please check this github issue explaining peculiarities of Kubernetes Volumes on Windows. I assume also that you have enabled Shared Drives feature in your Docker for Windows installation.
{ "pile_set_name": "StackExchange" }
Q: PathFileExists causes Linker error 2028/2019 trying out PathFileExists as explainded here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb773584%28v=vs.85%29.aspx causes Linker-Errors LNK2028 and LNK2019. Here is my code: char buffer1[] = "C:\\temp\\index.xml"; char *lpStr1; lpStr1 = buffer1; int retval; retval = PathFileExistsA(lpStr1); if (retval == 1 ) { this->lbl_stat->Text = "File found!"; }else{ this->lbl_stat->Text = "File not found!"; } A: As explained at the bottom of the MSDN page, you have to add to the project properties the dependency towards shlwapi.lib (look for "additional libraries" or something like that under the linker settings).
{ "pile_set_name": "StackExchange" }
Q: Gtkmm: Using RefPtr with widgets kept in std::vector I am trying to keep a std::vector of Gtk::Widgets that I am showing (and will potentially be) moving around between Gtk::Containers. At the moment I keep a Gtk::Notebook which is basically a one-to-one map to the std::vector, but if I use Glib::RefPtr around the widgets I get problems when removing the widget from the notebook. I already have to use a 'hack' to get a pointer to the underlying Gtk object when adding it to the notebook and I suspect that the Notebook container frees/deletes the object when I remove it from the container. I have defined my vector of widgets something like this: std::vector<Glib::RefPtr<Gtk::Widget>> widgets; When I add a widget to the vector and the notebook I do: Glib::RefPtr<Gtk::Widget> w (new Gtk::Widget()); widgets.push_back (w); Gtk::Widget *wptr = w.operator->(); // hack notebook.append_page (*wptr); when I try to remove it I do: int c = 1; // widget no. to remove notebook.remove_page (c); auto it = widgets.begin() + c; widgets.erase (it); but this results in a G_IS_OBJECT fail assertion when (I think) the element in the std::vector is cleaned up at the end of the iterator (end of function), since possibly notebook.remove_page() already freed the object. How can I do this? Is it possible with RefPtr's? Related (same assertion failure): Destructing Glib::RefPtr causes failed assertions in the GTK 3 core A: Glib::RefPtr<> should not be used with widgets. It is not a general purpose smartpointer. It should only be used with classes that force you to use it - by having no public constructor but having public create*() methods. A: Unfortunately you can't do this because the Gtk::Notebook takes ownership of the child objects. You have to refactor your code to use the Gtk::Notebook itself to access the widgets instead of the vector, for example with Gtk::Notebook::get_nth_page().
{ "pile_set_name": "StackExchange" }
Q: Why is int(50)<str(5) in python 2.x? In python 3, int(50)<'2' causes a TypeError, and well it should. In python 2.x, however, int(50)<'2' returns True (this is also the case for other number formats, but int exists in both py2 and py3). My question, then, has several parts: Why does Python 2.x (< 3?) allow this behavior? (And who thought it was a good idea to allow this to begin with???) What does it mean that an int is less than a str? Is it referring to ord / chr? Is there some binary format which is less obvious? Is there a difference between '5' and u'5' in this regard? A: It works like this1. >>> float() == long() == int() < dict() < list() < str() < tuple() True Numbers compare as less than containers. Numeric types are converted to a common type and compared based on their numeric value. Containers are compared by the alphabetic value of their names.2 From the docs: CPython implementation detail: Objects of different types except numbers are ordered by >their type names; objects of the same types that don’t support proper comparison are >ordered by their address. Objects of different builtin types compare alphabetically by the name of their type int starts with an 'i' and str starts with an s so any int is less than any str.. I have no idea. A drunken master. It means that a formal order has been introduced on the builtin types. It's referring to an arbitrary order. No. No. strings and unicode objects are considered the same for this purpose. Try it out. In response to the comment about long < int >>> int < long True You probably meant values of those types though, in which case the numeric comparison applies. 1 This is all on Python 2.6.5 2 Thank to kRON for clearing this up for me. I'd never thought to compare a number to a dict before and comparison of numbers is one of those things that's so obvious that it's easy to overlook. A: The reason why these comparisons are allowed, is sorting. Python 2.x can sort lists containing mixed types, including strings and integers -- integers always appear first. Python 3.x does not allow this, for the exact reasons you pointed out. Python 2.x: >>> sorted([1, '1']) [1, '1'] >>> sorted([1, '1', 2, '2']) [1, 2, '1', '2'] Python 3.x: >>> sorted([1, '1']) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: str() < int()
{ "pile_set_name": "StackExchange" }
Q: Whats wrong with this UIViewController? Swift 3, Loading Data I am simply trying to load this parsed Bitcoin price data into the tableview. I have it set to a test string right now but that still isn't working. I have triple checked everything in the storyboard so I am assuming it's something in this code: import UIKit import Alamofire import AlamofireObjectMapper import ObjectMapper class Response: Mappable { var data: [Amount]? required init?(map: Map){ } func mapping(map: Map) { data <- map["data"] } } class Amount: Mappable { var data : String? required init?(map: Map){ } func mapping(map: Map) { data <- map["data.amount"] } } let mount = [String]() let am = [String]() class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = "test" return cell } func Call_bitcoin(){ let url = "https://api.coinbase.com/v2/prices/BTC-USD/buy" Alamofire.request(url).responseObject{ (response: DataResponse<Amount>) in let mount = response.result.value let am = mount?.data print(am) } } override func viewDidLoad() { super.viewDidLoad() Call_bitcoin() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.delegate = self tableView.dataSource = self self.tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return am.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("You tapped cell number \(indexPath.row).") } } A: You just need to call the method reloadData() inside the callback of the Alamofire request. This is because Alamofire do an asynchronous call. Then, you will have the Call_bitcoin like this: func Call_bitcoin() { let url = "https://api.coinbase.com/v2/prices/BTC-USD/buy" Alamofire.request(url).responseObject{ (response: DataResponse<Amount>) in let mount = response.result.value let am = mount?.data print(am) self.tableView.reloadData() } } Also, you can refactor your viewDidLoad method, because you don't need to reloadData of the tableview (You are already doing it on the Call_bitcoin method). So, the viewDidLoad will be like this: override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.delegate = self tableView.dataSource = self Call_bitcoin() }
{ "pile_set_name": "StackExchange" }
Q: Implementing sticky headers inside a FlatList in React Native I tried to implement sticky headers inside a FlatList and encountered the following error: undefined is not an object (evaluating '_this3.state.stickyHeaderIndices') Code Link (Snack): https://snack.expo.io/@cmcodes/forlorn-cake A: This error is due to the fact that this is limited to use in your Explore Screen class, since you are using functional component to render list, you have to pass the sticky header data as you have passed the data i.e via props. You can check the updated code at https://snack.expo.io/1JtMGGDd4
{ "pile_set_name": "StackExchange" }
Q: When would you rehash a chaining hash table? When inserting to in chaining hash table, when would you rehash? Would it be better to rehash when alpha = 1? (alpha = # of elements stored / size of hash table) A: With chaining, you'll typically want to resize when any bucket contains more than a set number of items. For example, you might decide that it's okay for a bucket to contain up to 5 items. The first time you insert the sixth item into a bucket, you re-size the table. Or, you might decide that the ideal number is 10, or 3. It's up to you how you want to balance retrieval performance with resize time. The smaller your bucket size, the faster your average lookup will be, but you'll have to resize the table more often. With a larger bucket size, you won't have to resize as often, but your average lookup time will be longer. Worst case lookup time with a bucket size of 10 will be five times slower than with a bucket size of 2. But it will still be a whole lot faster than a sequential scan of a list, and you could get a 5x reduction in the number of times you have to re-hash. You should experiment with the optimum bucket size for your application. One thing you can do to improve lookup time with larger bucket sizes is, on lookup, move the item that was just referenced to the head of the list in its bucket. The theory here is that some items are looked up much more often than others, so if you always move the most recently referenced thing to the head of the list, you're more likely to find it faster. This optimization doesn't do any good if items are referenced uniformly. With chaining, you can often get good performance with load factors of 150% or 200%; sometimes even higher. Contrast that with re-hashing, which starts to degrade quickly at a load factor or 70% or 75%.
{ "pile_set_name": "StackExchange" }
Q: Usage of italics in writing In which cases is a word, or a group of words written in italics? Is italics used in specific contexts, or it is quite normal to write words in italics? A: The Wikipedia page on Italic type gives a pretty good overview, along with some examples. Emphasis: "Smith wasn't the only guilty party, it's true". The titles of works that stand by themselves, such as books (including those within a larger series), albums, plays, or periodicals: "He wrote his thesis on The Scarlet Letter". Works that appear within larger works, such as short stories, poems, or newspaper articles, are not italicized, but merely set off in quotation marks. The names of ships: "The Queen Mary sailed last night." Foreign words, including the Latin binomial nomenclature in the taxonomy of living organisms: "A splendid coq au vin was served"; "Homo sapiens". Using a word as an example of a word rather than for its semantic content (see use-mention distinction): "The word the is an article". Using a letter or number mentioned as itself: John was annoyed; they had forgotten the h in his name once again. When she saw her name beside the 1 on the rankings, she finally had proof that she was the best. Introducing or defining terms, especially technical terms or those used in an unusual or different way: "Freudian psychology is based on the ego, the super-ego, and the id."; "An even number is one that is a multiple of 2." Sometimes in novels to indicate a character's thought process: "This can't be happening, thought Mary." Algebraic symbols (constants and variables) are conventionally typeset in italics. Symbols for physical quantities and mathematical constants: "The speed of light, c, is approximately equal to 3.00×108 m/s." I've seen all of these usage cases between my reading of fiction and non-fiction texts. In particular, I've seen several authors switch to italics for the length of one or even multiple paragraphs to represent the thoughts of a character. Within such paragraphs, text that is normally italicised is put in regular/upright (Roman) type. (See also this About.com page, though it says very similar things to the Wiki page.) Hope that helps. A: Off the top of my head, italics are used for: book titles foreign words Latin names of species In the first and second case, you could just as well enclose the word(s) in quotes (without using italics). The third one seems to be set in stone.
{ "pile_set_name": "StackExchange" }
Q: Из каких стран чаще всего скачивают платные (~1-3$) android приложения? Решаю, на какие языки переводить своё приложение. Хотел следовать по этому списку, но учитывая, что там в топе китайский, арабский, хинди, бенгальский из индии, китая и африки - стран, в которых бедность развита на высшем уровне, следовать этому списку явно не стоит. Так-что помогайте, где найти top покупающих языков (понимаю что звучит не по русски, но думаю смысл понятен :) ) A: USA - 21% Korea - 11% Japan - 6% India - 6% Источник Но это средняя температура по больнице. Сильно отличается по категориям приложений. Скажем у меня Google Play показывает по категории "Tools", немного другую статистику: USA - 24% Japan - 11% Korea - 10% Germany - 4% Russia - 3% Но в реальности у меня статистика такая: Russia - 34% USA - 18% Italy - 12% Germany - 5% Netherlands - 3% Korea - 3% Как я и говорил - сильно зависит от качества перевода, моды, локальных трендов и проч. Так что думайте сами - решайте сами, переводить или не переводить.
{ "pile_set_name": "StackExchange" }
Q: Different behavior across compilers for std::enable_if (dependent on Outer class template parameters) I have a nested (Inner) class, for which I want to enable_if a constructor, depending on how many template parameters (Args) the enclosing class (Outer) has. I came up with the code below, only to find out that it compiles fine on some compilers, and on some not. #include <tuple> #include <type_traits> template <typename... Args> struct Outer { struct Inner { Inner(const Outer* out, Args... vals) : outer(out) , values(vals...) {} // This ctor should be enabled only if Args are non-empty template <typename = std::enable_if_t<(sizeof...(Args) > 0)>> Inner(const Outer* out) : outer(out) {} const Outer* outer; std::tuple<Args...> values; }; }; int main() { Outer<int, int> o1; Outer<int, int>::Inner i1(&o1, 1, 2); Outer<int, int>::Inner i11(&o1); Outer<> o2; Outer<>::Inner i2(&o2); Outer<>::Inner i21(nullptr); } Shown on Godbolt: https://godbolt.org/z/lsivO9 The funny part are the results: GCC 8.2 -std=c++17 - FAIL to compile GCC trunk -std=c++17 - OK MSVC 19.14 /std:c++17 /permissive- - OK MSVC 19.16 /std:c++17 /permissive- - OK clang 7 -std=c++17 - FAIL to compile clang trunk -std=c++17 - FAIL to compile So, the questions: Are the Args... of the Outer class in the immediate context of the Inner class? Is the above example well-formed? Which compiler is right? Why GCC started to behave differently with trunk? A: You need to make std::enable_if dependent on the constructor template parameter template <std::size_t N = sizeof...(Args), std::enable_if_t<(N > 0), bool> = true> Inner(const Outer* out) : outer(out) {}
{ "pile_set_name": "StackExchange" }
Q: Remove "or drag files here" text I've figured out how to disable drag and drop functionality on my document list. The problem is, it still says "or drag files here" text beside the +new document link. I want to keep the +new document, just get rid of the rest. A: This is a real ugly solution as the text could still be visible if you use markup. Add a script editor to the same page as the document library and add this. <style type="text/css"> .ms-soften, .ms-soften:link, a.ms-soften:visited, .ms-soften:hover, .ms-soften:active { color: #fff; cursor: default; } </style>
{ "pile_set_name": "StackExchange" }
Q: create folder with microsoft graph api I'm try to create folder, using microsoft graph API. In microsoft graph explorer, all work fine, but my php code return an error: $name = 'newFolder'; $access_token = '123..'; $link = 'https://graph.microsoft.com/v1.0/me/drive/root/children'; $data = array( "name" => $name, "folder" => array() ); $curl=curl_init(); curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); curl_setopt($curl,CURLOPT_URL,$link); curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST'); curl_setopt($curl,CURLOPT_HEADER,false); curl_setopt($curl,CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$access_token, 'Content-Type: application/json')); curl_setopt($curl,CURLOPT_POSTFIELDS, $data); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0); curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0); $out = curl_exec($curl); $codeCurl = curl_getinfo($curl,CURLINFO_HTTP_CODE); curl_close($curl); this is response of '$out': 400 BadRequest, Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format. I'm can't understand, what wrong? json data is correct, headers too.. A: The microsoft graph API documentation shows this example request for create folder: POST /me/drive/root/children Content-Type: application/json { "name": "New Folder", "folder": { }, "@microsoft.graph.conflictBehavior": "rename" } To get this part of the request : "folder": { } you could either put "folder" => new stdClass() in your $data array or keep this "folder" => array() and use json_encode($data, JSON_FORCE_OBJECT). If you use JSON_FORCE_OBJECT, all arrays will be encoded as objects. I had the same problem, but error in the response was a bit different: Property folder in payload has a value that does not match schema. I am using "folder" => new stdClass() and it works fine.
{ "pile_set_name": "StackExchange" }
Q: UIAlertController code runs, but doesn't present an alert I am trying to make an in-app popup alert using swift and I have run into an error that I know nothing about. Here is the code I use to present my alert: let welcomeAlert = UIAlertController(title: "Welcome!", message: “message here”, preferredStyle: UIAlertControllerStyle.Alert) welcomeAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(welcomeAlert, animated: true, completion: nil) println("welcome alert displayed!") The error I'm getting back says this: Warning: Attempt to present <UIAlertController: 0x7b89a950> on <MyApp.RootClientViewController: 0x7aea8fb0> whose view is not in the window hierarchy! This is immediately followed by a printed statements stating welcome alert displayed!. So my code is certainly running, but for some reason, it won't display the alert... What am I doing wrong? A: The error message tells you the answer: "view is not in the window hierarchy!" means self.view is not on screen when the call is made (technically it means UIApplication.sharedApplication().keyWindow is not an ancestor of self.view). Usually this happens when presenting a view controller in viewDidLoad() or viewWillAppear(animated: Bool). Wait for viewDidAppear(animated: Bool), present from UIApplication.sharedApplication().delegate.window.rootViewController or present from UIApplication.sharedApplication().keyWindow.rootViewController.
{ "pile_set_name": "StackExchange" }
Q: Automatic cut mains power on a thunderstorm I am a software engineer with only a basic experience with electric/electronic engineering. I live in a rural area subject to thunderstorms, my house is the end of the line from street poles. It's common to receive lightning strikes by energy line. I have grounding, surge protectors, etc, but somehow sometimes a surge is capable to hit and damage my UPS. It's a common recommendation to unplug sensible/expensible eletronics on thunderstorms. I am wondering if it's possible to automate this process. With an Arduino it's not so difficult to make a "lightning detector". This could cut-off mains power from some equipment on a thunderstorm and turn it back on when it stops. I am not sure circuit breakers, relays or contactors are able to isolate a lightning strike because of the small air gap between contacts when they are off. In other hand, if you consider that a lightning is capable enough to jump from a cloud in sky to the ground, even if you unplug an equipment from the wall, a strike could jump from the wall to the disconnected plug. If you imagine, for a very small probabillty, that NO ONE is safe. So, I ask, there is some kind of relay appropriate to isolate a lightning strike? A: You don't unplug electrical equipment to protect it from a direct lightning strike. You unplug it to raise its damage threshhold, to increase the likelyhood of its surviving a nearby strike. As such, opening any contactor or relay would be beneficial. I live in one of a row of houses. A few years ago, another house in the row was struck by lightning. Let's call this house zero. They lost all their electrical equipment, and had to be rewired. House one next door lost all their electrical equipment. House two lost only electronic equipment, simple electricals with motors and dumb switches still worked. In house three, I lost my ADSL. House four survived with no damage. So there's plenty of scope for a small break in the wiring to reduce the scope of your loss with a close, but not direct, strike.
{ "pile_set_name": "StackExchange" }
Q: Magento extension giving problem at time of install I am using extension in magento "J2TRememberMe", but at installation it's giving me problems. It's showing a message like: "Failed to download magento-community/J2TRememberMe within preferred state "stable", latest release is version 1.0, stability "beta", use "channel://connect.magentocommerce.com/community/J2TRememberMe-1.0" to install Cannot initialize 'channel://connect.magentocommerce.com/community/J2TRememberMe', invalid or missing package file Install Errors Package "channel://connect.magentocommerce.com/community/J2TRememberMe" is not valid PEAR ERROR: install failed" Does anyone have any idea how to resolve it ? Thanks A: in the tab settings, change the preferred state from "stable" to "beta"
{ "pile_set_name": "StackExchange" }
Q: Why does my Firemonkey app open a terminal window on OSX but not on Win32? I created a simple testbed app in Delphi XE2, and compiled both a Win32 and OSX version of the application. I zipped up the OSX version, along with a copy of the libcgunwind dylib runtime file and copied this files to a Mac i have access to. When I unzipped the file, the mac recognized my OSX application and I double clicked it. This, in turn, opened up a terminal window for some unknown reason along with my simple app's form. The application itself ran and behaved just fine, but I'm curious why a terminal window would open up on the Mac? A: There is a free tool available for Delphi XE2 that will create the OSX deployment app bundle for you, from Windows, without the need for PAServer. http://enesce.com/delphiosx_bundler Check the readme for instructions.
{ "pile_set_name": "StackExchange" }
Q: What does "vana" mean? In Spiral Knights, someone just bailed out of my party because he couldn't "make it to vana". I also heard someone in the arcade say "guess we're back to vana running for today". What's vana? A: Chances are, they're referring to Lord Vanaduke, who is a boss down in the Firestorm Citadel down in tier 3. The party member who bailed probably didn't want to spend his energy without making to a boss. The others were probably lamenting that they had to work their way to vana instead of being able to catch a ride with a party that was almost there already.
{ "pile_set_name": "StackExchange" }
Q: Front camera and flash in Red laser SDK I wanted to know whether do we have an option to scan the bar code using front camera in red laser android sdk? also how to turn on the flash? Is any document or sample app is available for the above requirement? A: Both of these features have been added to the 3.0 version of the Android RedLaser SDK. The RLSample app, included in the SDK package, demos both of these features. A: Which version of the Android RedLaser SDK are you using? try Updating/Downloading the most recent stable version. It works fine with me.
{ "pile_set_name": "StackExchange" }
Q: DokuWiki: Highlight Part in code Block? I want to highlight/emphasize a part in a code block in dokuwiki. I could not find a hint in the docs: https://www.dokuwiki.org/wiki:syntax#code_blocks But maybe I am missing something. Background: I am not searching for syntax highlighting. I want to emphasize a part. A: That's not possible. There are alternative highlight plugins (code2 seems to be popular) that might be able to do that.
{ "pile_set_name": "StackExchange" }
Q: AS3 Dispatch Custom Event from class to class I want to dispatch a custom event from the Country() sto the MenuButton(); CountryEvent package { import flash.events.Event; public class CountryEvent extends Event { public static const COUNTRY_HOVERED:String = "onCountryOver"; private var _countryName:String = ""; public function CountryEvent(type:String, countryName:String, bubbles:Boolean=true, cancelable:Boolean=false) { super(type, bubbles, cancelable); _countryName = countryName; } public function get countryName():String { return _countryName; } public override function clone():Event { return new CountryEvent(type,countryName,bubbles,cancelable); } } } Country Class package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.events.Event; public class Country extends MovieClip { private var countryEvent:CountryEvent; public function Country() { this.addEventListener(MouseEvent.MOUSE_OVER,onMouseOver); this.addEventListener(MouseEvent.MOUSE_OUT,onMouseOut); } private function onMouseOver(e:MouseEvent):void { countryEvent = new CountryEvent("onCountryOver",this.name); dispatchEvent(countryEvent); } } private function onMouseOut(e:MouseEvent):void { } } } MenuButton Class package { import flash.display.MovieClip; import flash.events.MouseEvent; import CountryEvent; public class MenuButton extends MovieClip { public var countryName:String = ""; public function MenuButton() { this.buttonMode = true; this.addEventListener(MouseEvent.MOUSE_OVER,onMouseOver); this.addEventListener(MouseEvent.MOUSE_OUT,onMouseOut); this.addEventListener(CountryEvent.COUNTRY_HOVERED,onCountryOver); } private function onCountryOver(e:CountryEvent):void { if(e.countryName == countryName) { this.gotoAndPlay(2); } } private function onMouseOver(e:MouseEvent):void { this.gotoAndPlay(2); } private function onMouseOut(e:MouseEvent):void { this.gotoAndPlay(11); } } } When a country is hovered a custom event is dispatched which I want the MenuButton to listen and if the parameter passed is the same as its name to get highlighted. The Country Class is the Base Class for my countries movieclips I have on stage and the MenuButton the Base Class for the menu button It seems that the event never gets through Thanks in advance A: You have to make two modifications: First, set your event bubbles property to true, so when a Country clip dispatches an event it will go up to the top level. Then your MenuButtons should listen to stage, not to themselves. So when a Country dispatches an event it goes up to stage and can be caught by the buttons. If you want to listen to the stage you have to do a slight change in your code: public function MenuButton() { this.buttonMode = true; this.addEventListener(MouseEvent.MOUSE_OVER,onMouseOver); this.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut); this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage); } private function onAddedToStage(e:Event):void { removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); stage.addEventListener(CountryEvent.COUNTRY_HOVERED,onCountryOver); }
{ "pile_set_name": "StackExchange" }
Q: DNN clear cache for a user after locking it out There is a problem with DNN 9.1. After locking out a user (from code), the DNN cache doesn't refresh. Scenario User entered his/her password more than Membership.MaxInvalidPasswordAttempts; so, the user is locked out. Logging by 'host' (superuser account), and searching for the locked user, the DNN doesn't display the user as locked. (actually, I was searching for the 'Unlock User' option) Q Is there any way to let the DNN know after locking a user from the code? How much time, should I wait till the DNN cache refresh? A: You can clear the cache programatically in DNN. DotNetNuke.Common.Utilities.DataCache.ClearModuleCache(TabId); DotNetNuke.Common.Utilities.DataCache.ClearTabsCache(PortalId); DotNetNuke.Common.Utilities.DataCache.ClearPortalCache(PortalId, false); But I doubt this solves your issue since the lockout is not managed by DNN but by ASP.NET Membership. The lockout is real-time. If you go to Admin > User Accounts > Edit User Account you will see that "lockedout = true" on the Manage Account tab. At the bottom is a button to unlock a user.
{ "pile_set_name": "StackExchange" }
Q: angularjs consume asp.net web service Good Day, i am new to angularjs and started playing around mostly on the pulling of data trough web service. my web service returns a list of latitude and longitude from my database here is the code [WebMethod] public List<friendlyforces> get_friendly(string regionid , string type) { List<friendlyforces> friendlies = new List<friendlyforces>(); List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@regid", regionid)); parameters.Add(new SqlParameter("@type", type)); SqlDataReader readers = SqlHelper.ExecuteReader(connection, "friendlyforces", parameters.ToArray()); while (readers.Read()) { friendlies.Add(new friendlyforces()); friendlies[(friendlies.Count - 1)].unit_name = readers["unit_name"].ToString(); friendlies[(friendlies.Count - 1)].address = readers["adrress"].ToString(); friendlies[(friendlies.Count - 1)].latitude = readers["latitude"].ToString(); friendlies[(friendlies.Count - 1)].longitude = readers["longitude"].ToString(); friendlies[(friendlies.Count - 1)].icon = readers["icon"].ToString(); } return friendlies; } now on my angularjs enabled page i am trying to display the data given by the web service here is the code var app = angular.module('Services', []); app.controller('latController', function ($scope, $http) { var url = "Services/datapull.asmx/get_friendly"; $http({ method: 'POST', url: url, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: JSON.stringify({ regionid: "7", type: "pnp" }) }).success(function (data) { var myjson = JSON.parse(data); $scope.locations = JSON.parse(myjson); }); }) now when the web service is invoked it returns an error stating that i am missing a parameter the regionid i tried $.param : ({regionid : "7" , type : "pnp" }) andparam : JSON.stringify ({regionid : "7" , type : "pnp"}) but it retruns the same error parameter is missing any suggestions? thank you A: From the content type you provide 'Content-Type': 'application/x-www-form-urlencoded', it seems you want to send your data as url param. However, By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". Try add transformRequest in your request. $http({ method: 'POST', url: url, headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); }, data: { regionid: "7", type: "pnp" } }).success(function () {});
{ "pile_set_name": "StackExchange" }
Q: Magento2 - How to add remove all wishlist button on the wishlish page? on the wishlist's page we have remove wishlist's button for each item, and we want to add a button that can remove all wish-list item all at once thank you A: I create my own module with a specific route to solve this problem, and I am thinking another best way to extend the action like do it from a plugin or something else, here are the code <?php namespace XXX\RemoveAllWishList\Controller\Index; use Magento\Framework\App\Action; use Magento\Framework\Data\Form\FormKey\Validator; use Magento\Framework\Controller\ResultFactory; use Magento\Wishlist\Controller\WishlistProviderInterface; class Index extends \Magento\Wishlist\Controller\AbstractIndex { /** * @var WishlistProviderInterface */ protected $wishlistProvider; /** * @var Validator */ protected $formKeyValidator; /** * @param Action\Context $context * @param WishlistProviderInterface $wishlistProvider * @param Validator $formKeyValidator */ public function __construct( Action\Context $context, WishlistProviderInterface $wishlistProvider, Validator $formKeyValidator ) { $this->wishlistProvider = $wishlistProvider; $this->formKeyValidator = $formKeyValidator; parent::__construct($context); } /** * Remove item * @return \Magento\Framework\Controller\Result\Redirect * @throws \Exception */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $wishlistId = (int)$this->getRequest()->getParam('item'); if (!$wishlistId) { throw new NotFoundException(__('Page not found.')); } if($wishlistId) { $wishlist = $this->wishlistProvider->getWishlist($wishlistId); $wishlistCollection = $wishlist->getItemCollection(); foreach ($wishlistCollection as $item) { $item->delete(); } $wishlist->save(); } $resultRedirect->setUrl($this->_redirect->getRefererUrl()); $request = $this->getRequest(); $refererUrl = (string)$request->getServer('HTTP_REFERER'); $url = (string)$request->getParam(\Magento\Framework\App\Response\RedirectInterface::PARAM_NAME_REFERER_URL); if ($url) { $refererUrl = $url; } if ($request->getParam(\Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED) && $refererUrl) { $redirectUrl = $refererUrl; } else { $redirectUrl = $this->_redirect->getRedirectUrl($this->_url->getUrl('*/*')); } $resultRedirect->setUrl($redirectUrl); return $resultRedirect; } } Here is the main method to delete all the wishlist item foreach ($wishlistCollection as $item) { $item->delete(); } $wishlist->save(); Thank You.
{ "pile_set_name": "StackExchange" }
Q: What type of grant is adequate for a React application? I'm little confused because I don't know what type of grant I should use for my specific scenario. I've a front-end React application with a back-end using Spring Boot. Additionally, there is a standalone Spring OAuth2 authorization server. The React application will be a normal public web application where authentication requires username and password credentials. What type of grant should I use? Is the resource owner password credentials grant a good choice? A: There's a lot of things that can influence the best way to approach this; based on the provided information it's possible to showcase applicable options and do some recommendations, but the definitive choice is hard to make without having all the context. TL;DR On a browser-based application where end-users are issued username/password credentials and the applications needs to make calls to an API on behalf of the users you can either use the implicit grant or the resource owner password credentials grant (ROPC). The use of ROPC should be further restricted to client applications where there is an high degree of trust between the application and the entity that controls the user's credentials. The use of client credentials is completely out of scope and the authorization code grant may not present any benefit over the implicit grant for what a browser-based application is concerned so by a process of elimination we have two eligible grants. Resource owner password credentials grant (check Auth0 ROPC Overview for full details on the steps) This grant was primarily introduced in OAuth 2.0 as a way to provide a seamless migration path for application that were storing username/password credentials in order to have access to user resources without constantly asking the user to provide the credentials. As you can imagine, storing passwords in plain text is a big no no, so having a way to stop doing that with a very simple migration path (exchange the stored credentials with tokens using this grant) would be a big improvement. However, access tokens expire so the way to keep obtaining new tokens for access was through the use of refresh tokens. Keeping refresh tokens in storage is better than passwords, but they are still usually long-lived credentials so the act of storing those type of tokens has additional security considerations. Because of this, it's not usually recommended to keep/use refresh tokens in browser-based applications. If you choose this grant you need to decide what will happen when the access tokens expire. Implicit grant (check Auth0 Implicit Grant Overview for full details on the steps) This grant is a simplified version of the authorization code grant specifically aimed at applications implemented within a browser environment so it does seem be a better fit to your scenario. An additional benefit is that obtaining new access tokens could happen transparently after the first user authentication, more specifically, by having the authorization server manage some concept of session any implicit grant request for a user that is already authenticated and that already consented to provide that authorization could be done automatically without requiring user interaction. Conclusion (aka opinion based on what I know which may not be sufficient) As a general recommendation I would choose the implicit grant over the ROPC grant.
{ "pile_set_name": "StackExchange" }
Q: Finding all positive real functions satisfying $xf(y)+f(f(y))\leq f(x+y)$ Find function $f: \mathbb{R}_{> 0}\rightarrow \mathbb{R}_{> 0}$ such that: $xf(y)+f(f(y))\leq f(x+y)$ for all positive $x$ and $y$? That problem made me think a lot. This is the first time I solve functional inequality. Please show me the way to solve such problems. From the inequality, can we prove that $f$ is injective or surjective? A: $f(f(y))-f(x+y)\leq -xf(y)$. As $xf(y)>0$, $f(f(y))-f(x+y)<0$. Now, if $f(y_0)>y_0$ for some $y_0>0$, then we can put $x=f(y_0)-y_0$ and $y=y_0$ which yields $f(f(y_0))-f(f(y_0))<0$ which is clearly wrong. Therefore, $$f(y)\leq y$$ Now, as $f(f(y))>0$, $xf(y)<f(x+y)\leq x+y$ $x(f(y)-1)<y$ $\forall$ $x,y>0$. If $f(y)>1$ for any finite $y>0$, by making $x$ arbitrarily large, we obtain a contradiction. Thus, $$f(y)\leq 1$$ As $f(f(y))>0$, $f(x+y)\leq 1$ and $xf(y)+f(f(y))\leq f(x+y)$, $$xf(y)<1$$ As $f(y)>0$, by making $x$ arbitrarily large, we obtain another contradiction. Therefore, there exists no function $f:\mathbb{R}_{>0}\to \mathbb{R}_{>0}$ such that $xf(y)+f(f(y))\leq f(x+y)$.
{ "pile_set_name": "StackExchange" }
Q: asp.net vs. xcode button click I just started learning objective c and iphone development. Coming from an asp.net and web development, I am so lost with xcode. In asp.net, you create a button, then you can simply click on it and it takes you right to the button event. Vs. Xcode, you create a button, then you will have to create an outlet in the header file, property, IBaction. Then in the implementation (.m) file, you create the click event method for that button. After that, you have to create an outlet reference of that button touch to that event by draging... Just out of curiosity, is there any shortcuts or easier way to do this like asp.net? Without having to create outlet, property, etc. If there are any ways to eliminate some steps would be helpful. A: If you want to perform action only click button you don't need to declare UIButton IBOutlet. Just simply drag UIButton object on your view then declare & implement IBAction method in your class. Then make connection between action and button. There is not shortcut in xcode for this if you want to interact with interface objects in your controller class you need to declare them as property and implement using @synthesize
{ "pile_set_name": "StackExchange" }
Q: Pair javascript objects and assign same color Is it possible to find a better/ modular way to assign the same color to paired rather than hard-coding them as I currently implement? If objects fname matches, then assign the same color. The following is a subset of javascript objects. data[0] = [{ "value": 29, "series": 1, "category": "Men", "fname": "NY", "valueColor": "red" }, data[1] = [{ "value": 19, "series": 4, "category": "Women", "fname": "NY", "valueColor": "red" }, data[2] = [{ "value": 9, "series": 3, "category": "LG", "fname": "NY", "valueColor": "red" }, Here is the full implementation in FIDDLE First I assume, all objects are different and assign a different color, then I will check if there are any paired objects, if yes, then assign the same color. Therefore it would be nice to generate colorSpectrum based on a number of objects in exists in datasets rather than assigning common colors such as red, green, yellow, etc.. because you cannot guess in advance how many different objects you would get. I might get around maybe 10 objects, maybe around 100 objects. Therefore, I am looking for a modular way to handle this difficulty. Here is the colorSpectrum method implementation in COLOR SPECTRUM FIDDLE A: You can do something like this. function colorSpectrum(N) { var colorMap = [], inc = 50, start = 1000; for (i = start; i < start+N*inc; i+=inc) { var num = ((4095 * i) >>> 0).toString(16); while (num.length < 3) { num = "0" + num; } colorMap.push("#" + num); } return colorMap; } function process(data){ var map = {}, colorMap = colorSpectrum(data.length); data.forEach(function(item, index){ if(!map.hasOwnProperty(item.fname)){ map[item.fname] = colorMap[index]; } data[index].valueColor = map[item.fname]; }); return data; } data = process(data); Here is a demo http://jsfiddle.net/dhirajbodicherla/fm79hsms/7/
{ "pile_set_name": "StackExchange" }
Q: is my understanding for aws auto-scale up and load balancer wrong? Actually I am still a bit confused with aws auto scale up and load balancer I am wondering if someone can help me clarify if my logic of understand is right and if so, would it be possible to combine the usage of auto-scale up and load balancer? As for auto-scale up let's say I can setup a cloudalarm that if my main instance reaches to cpu > 90% for a minute then a new instance will spin up and the new instance will share the burden with the main instance to lower the cpu usage. (after spin up, aws will do the rest for us)this is as if I set the setting to spin up 1 instance up to 5 max If this is correct for my understanding, does the new instance need to have the exactly the same settings of the server? If so, that means I need to create an image of the main instance and each time if I update the main instance I will have to create a new image then change the cloudalarm / auto-scale up to launch the new image right? If the above is right, is there a better way of doing this? or else, it seems like I have to keep on creating image and change settings if the main instance get changes everyday. As for load balancer, I read through the documentation and played around. Spin up three instances, registered them all to load balancer. All 3 are healthy, and if I reload the page, it keeps on changing between the three instances. If one instance is down, the other two will be running. If this is also correct for my understanding, does this mean I need to have 2+ the same instances running and each time when I do deployment I need to do it to all the instances? Wouldn't this be a lot of work if I have lots of servers and want all of them to use load balancer in case the server suddenly becomes unhealthy? If both of my understanding are correct, is it possible to somehow use auto-scale up with cloudalarm that if somehow main instance is unhealthy create image of the instance then register to the load-balancer? Sorry for the trouble for the readings, but I do wondering if I am understanding them wrong or I am over thinking and getting myself confused. Thanks for any advice and help. A: When you are using Auto Scaling and Load Balancing, you want all your EC2 instances to be identical. So they are all (a) rooted on the same AMI image, and (b) proceed through the same initialization steps to end up with the same code and assets on them. This way, they will all respond the same with the same input from your HTTP client. To accomplish this, do not attempt to update your EC2 instances manually. When you're scaling up and down, your work will be lost. When you need to deploy a new version of your code, you should do one (or more) of the following patterns. Pattern 1: Deploy your code to a "gold" EC2 instance and is not part of your Auto Scaling group. Create an AMI of this "gold" instance. Update your Auto Scaling group to use this new AMI image. Delete old EC2 instances (that use the old AMI) and replace them with new EC2 instance (that use the new AMI) Pattern 2: Base your Auto Scaling group from a "basic" AMI image When your EC2 instances launch for the first time, they download the source code from some common location (like S3) When you deploy new code, terminate old instances and launch new ones to get the new code Pattern 3: Do Pattern 2, but Use an automated tool to deploy your new code to your existing EC2 instance rather than terminating them There are other patterns, but these are some common ones that work. If you're new to Auto Scaling and Load Balancing, I highly recommend you take a serious look at Elastic Beanstalk. It will manage all of the above for you, making deployments and updates much easier. Some additional notes: Depending on your application, it may be valid to use 1 EC2 instance behind a Load Balancer. You may not need 2+ instances. You can scale up from 1 instance as your load increases. You simply lose the high availability.
{ "pile_set_name": "StackExchange" }
Q: javascript method partition INTRODUCTION : I have a function(callback) that receives a object as an argument, inside this function I have a method(or function I'm note sure what is it) which then partitions that object. Now I'll add some code to add some clarification to introduction part. Result.getListCallback = function(obj) { Result.complexObject = obj.data; var objectPartitioner = Result.complexObject.partition( function(n){ return n.case.id == Result.selectedData.case.id; }); } What I want to do is to modify this "objectPartitioner" to return couple of things for me not just case.id , how can I do that , perhaps using several returns ? thank you A: Why not return an object? In this case, you can pack what you want. Note that if you want to return something like a small array it is anyhow an object in Javascript.
{ "pile_set_name": "StackExchange" }
Q: I want to use Stack Overflow code on my server with my content I would like to use the code Stack Overflow has on its sites with my site and my content. Is that possible? A: We don't release the entire codebase and we don't currently provide a white-labeling service for creating privately hosted sites. However, there are various clones of our system out there, so one may fit your needs. Good luck.
{ "pile_set_name": "StackExchange" }
Q: How to use different yarn registry regardless of registry in the yarn.lock file? My yarn.lock file looks like: [email protected]: version: "x.x.x" resolved: "http://registry.yarnpkg.com/package/-/xxxx" But the CI is in intranet and the registry is http://99.12.xx.xx/xxx How to use intranet registry in CI build regardless of the internet registry in the yarn.lock file? A: This is an old issue on yarn's github repository as you can see here I solved this issue by running a sed command to substitute the registry link before installing packages: sed -i -e "s#https://registry.yarnpkg.com/#{YOUR_CI_REGISTRY}#g" yarn.lock hope that helps.
{ "pile_set_name": "StackExchange" }
Q: How can i parse objects in arrays in arrays from json I've been trying to parse the objects from this object that is inside an array inside another array. I made two loops because there are multiple objects that i'm trying to make a list from. This is what the json looks like { "type": "FeatureCollection", "metadata": { "generated": 1522105396000, "url": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson", "title": "USGS Magnitude 4.5+ Earthquakes, Past Day", "status": 200, "api": "1.5.8", "count": 7 }, "features": [{ "type": "Feature", "properties": { "mag": 4.7, "place": "106km SW of Hihifo, Tonga", "time": 1522100348420, "updated": 1522102052040, "tz": -720, "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us1000d9c6", "detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us1000d9c6.geojson", "felt": null, "cdi": null, "mmi": null, "alert": null, "status": "reviewed", "tsunami": 0, "sig": 340, "net": "us", "code": "1000d9c6", "ids": ",us1000d9c6,", "sources": ",us,", "types": ",geoserve,origin,phase-data,", "nst": null, "dmin": 3.738, "rms": 0.85, "gap": 66, "magType": "mb", "type": "earthquake", "title": "M 4.7 - 106km SW of Hihifo, Tonga" }, "geometry": { "type": "Point", "coordinates": [-174.4796, -16.604, 175.39] }, "id": "us1000d9c6" }, { "type": "Feature", "properties": { "mag": 4.8, "place": "West Chile Rise", "time": 1522025174820, "updated": 1522026587040, "tz": -360, "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us1000d90k", "detail": "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/us1000d90k.geojson", "felt": null, "cdi": null, "mmi": null, "alert": null, "status": "reviewed", "tsunami": 0, "sig": 354, "net": "us", "code": "1000d90k", "ids": ",us1000d90k,", "sources": ",us,", "types": ",geoserve,origin,phase-data,", "nst": null, "dmin": 9.665, "rms": 0.87, "gap": 192, "magType": "mb", "type": "earthquake", "title": "M 4.8 - West Chile Rise" }, "geometry": { "type": "Point", "coordinates": [-86.6644, -41.0452, 10] }, "id": "us1000d90k" } ], "bbox": [-178.6721, -56.8886, 10, 151.396, 56.3364, 541.02] } I just need the place, magnitude and time from both arrays but i can't seem to pick the right array to get the object from. ex:(features.properties.place) List<String> allPlaces = new ArrayList<>(); JSONArray JA = new JSONArray(data); JSONArray features = JA.getJSONArray(2); // JSONArray properties = features.getJSONArray(1); for (int i = 0; i < features.length(); i++){ JSONArray properties = (JSONArray) features.get(i); for (int j = 0; j < properties.length(); j++){ JSONObject JO = (JSONObject) features.get(i); String place = JO.getString("place"); singlePlace = "place: " + place; dataPlace = "" + singlePlace; allPlaces.add(place); } edit1: to be clear, i am able to get information from the first array, so the value of type, but not anything inside of features, A: A problem is that you are parsing the properties as a JSONArray but in fact it's a JSONObject. So, you should try this loop to parse needed data: JSONObject root = new JSONObject(data); //Where `data` is your raw json string JSONArray features = root.getJSONArray("features"); for (int i = 0; i < features.length(); i++) { JSONObject properties = features.getJSONObject(i).getJSONObject("properties"); double mag = properties.getDouble("mag"); String place = properties.getString("place"); long time = properties.getLong("time"); }
{ "pile_set_name": "StackExchange" }
Q: Can VB.NET catch exceptions without defining a local exception variable? In C# you can do this: try { // some code here } catch (MyCustomException) { // exception code here } catch (Exception) { // catches all other exceptions } Notice the catch (Type) instead of catch (Type myVariable). Is this possible with VB.NET, or do you always have to declare a variable when you catch exception types, like so: Try ... Catch var As NullReferenceException ... Catch var As Exception ... End Try A: Gotta be declared in vb.net. In fact when you type in try your ide should put in the exception type and format it. like so: Try Catch e As Exception End Try
{ "pile_set_name": "StackExchange" }
Q: Problem with PHP MYsql Delete syntax with timestamp comparison All I am trying to do is delete rows in a column that have a timestamp more than 2 days old. I have tried a lot of things I have seen on here, but none of them seem to be working. This is the code: $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()); These are the errors I am getting on that line: Warning: Unexpected character in input: ''' (ASCII=39) state=1 in... Parse error: syntax error, unexpected T_STRING in... This should be really easy but I can't figure out what I am doing wrong. A: you forgot the closing quote $delquery = $tapeDB->query('DELETE FROM newsItems WHERE news_date < TIMESTAMPADD(DAY,-2,NOW()');
{ "pile_set_name": "StackExchange" }
Q: query for identifying long rows Is there a query that can help identify tables whos rows potentially are longer than 8060 bytes in MSSQL 2008? I understand that this is the maximum size of a data row. eg. create table a ( a varchar(4000), b varchar(4000), c varchar(4000) ) A: A quick and dirty one. SELECT OBJECT_NAME(object_id),SUM(max_length) FROM sys.columns WHERE is_computed=0 and OBJECTPROPERTY(object_id,'IsUserTable')=1 GROUP BY object_id HAVING SUM(max_length) > 8060 or MIN(max_length)=-1 /*MAX datatype*/ Dropped and altered columns can still consume wasted space. This is visible through sys.system_internals_partition_columns You might be better off looking at sys.dm_db_partition_stats to determine which objects actually have off row pages allocated.
{ "pile_set_name": "StackExchange" }
Q: VueJS, Vuetify, data-table - expandable, performance problem I've got a problem with my VueJS and Vuetify project. I wanna create a table with expandable rows. It'll be a table of orders with possibility to see bought products for each one. For one page it should show at least 100 rows of orders. For this, I used <v-data-table> from the Vuetify framework. What is the problem? After preparing everything I realized that it works, but for expansion for each row, I have to wait a few seconds (it's too long - it must be a fast system). And for expanding all visible records it is necessary to wait more than 20 seconds with whole page lag. What I've tried? I started with standard Vuetify <v-data-table> with a show-expand prop and with an expanded-item slot - it was my first try - the slowliest. Secondly, I tried to create on my own - but with Vuetify: <v-data-table> <template v-slot:item="{item}"> <td @click="item.expanded = !item.expanded">expand / hide</td> <!--- [my table content here - too long to post it here] --> <tr v-if="item.expanded"> <td :colspan="headers.length"> <v-data-table> <!--- [content of the nested table - also too long to post it here] --> </v-data-table> </tr> </template> </v-data-table> What's interesting - I realized that v-if works faster than v-show, which is a weird fact, because I thought that changing display: none to nothing should be less problematic than adding/removing whole objects to DOM. This method was a little faster than first, but it is still too slow. I found a hint to set :ripple="false" for every v-btn in my tables and I did it - helped, but only a bit. Everything was tested on Chrome and Firefox, on three devices with Windows and Linux Fedora and two android smartphones. What should else I do? Thank you in advance! A: This excellent article suggests that the raw number of DOM nodes has the biggest impact on performance. That said, I didn't experience any real performance bottlenecks in the sample app that I built to learn more about your problem. The entire page with the table loaded in about 1.25s (from localhost), regardless of whether it was in dev mode or it was a production build. The JavaScript console timer reported that expanding or contracting ALL 100 rows simultaneously only took an average of about 0.3s. Bottom line, I think you can achieve the optimizations you're looking for and not have to give up the conveniences of Vuetify. Recommendations Consider displaying fewer rows at one time (biggest expected impact) Streamline your template to use as few elements as possible, only display data that's really necessary to users. Do you really need a v-data-table inside a v-data-table? Streamline your data model and only retrieve the bare minimum data you need to display the table. As @Codeply-er suggested, the size and complexity of your data could be causing this strain Testing Method Here's what I did. I created a simple Vue/Vuetify app with a VDataTable with 100 expandable rows. (The data was pulled from the random user API). I used this method to count DOM nodes. Here are some of the parameters/info: Rows: 100 Columns: 5 + the expansion toggler Expansion row content: a VSimpleTable with the user's picture and address Size of a single JSON record returned from the API: ~62 lines (about half the size of your sample object above) Vue v2.6.11 Vuetify v2.3.0-beta.0 (I realize this just came out, but I don't think you'd have different results using v2.2.x) App was built with vue create myapp and vue add vuetify VDataTable actually adds/removes the expansion rows from the DOM whenever the rows are expanded/contracted Here's some approximate stats on the result (these numbers fluctuated slightly in different conditions--YMMV): 773 (~7/row): number of DOM nodes in 100 rows/5 columns without expansion enabled 977 (+2/row): number of nodes with expansion enabled 24: number of nodes added to the table by expanding a single row 3378 (+26/row): total nodes with ALL rows expanded ~1.25s to load the entire page on a hard refresh ~0.3s to expand or contract ALL of the nodes simultaneously Sorting the columns with the built-in sorting tools was fast and very usable Here's code of the App.vue page of my app. The v-data-table almost the only component on the page (except the toggle button) and I didn't import any external components. <template> <v-app> <v-btn color="primary" @click="toggleExpansion" > Toggle Expand All </v-btn> <v-data-table :expanded.sync="expanded" :headers="headers" :items="items" item-key="login.uuid" :items-per-page="100" show-expand > <template #item.name="{ value: name }"> {{ name.first }} {{ name.last }} </template> <template #expanded-item="{ headers, item: person }"> <td :colspan="headers.length"> <v-card class="ma-2" max-width="500px" > <v-row> <v-col cols="4"> <v-img :aspect-ratio="1" contain :src="person.picture.thumbnail" /> </v-col> <v-col cols="8"> <v-simple-table> <template #default> <tbody> <tr> <th>Name</th> <td class="text-capitalize"> {{ person.name.title }}. {{ person.name.first }} {{ person.name.last }} </td> </tr> <tr> <th>Address</th> <td class="text-capitalize"> {{ person.location.street.number }} {{ person.location.street.name }}<br> {{ person.location.city }}, {{ person.location.state }} {{ person.location.postcode }} </td> </tr> <tr> <th>DOB</th> <td> {{ (new Date(person.dob.date)).toLocaleDateString() }} (age {{ person.dob.age }}) </td> </tr> </tbody> </template> </v-simple-table> </v-col> </v-row> </v-card> </td> </template> </v-data-table> </v-app> </template> <script> import axios from 'axios' export default { name: 'App', data: () => ({ expanded: [], headers: [ { text: 'Name', value: 'name' }, { text: 'Gender', value: 'gender' }, { text: 'Phone', value: 'phone' }, { text: 'Cell', value: 'cell' }, { text: 'Country', value: 'nat' }, { text: '', value: 'data-table-expand' }, ], items: [], }), created () { axios.get('https://randomuser.me/api/?seed=stackoverflow&results=100') .then(response => { this.items = response.data.results }) }, methods: { toggleExpansion () { console.time('expansion toggle') this.expanded = this.expanded.length ? [] : this.items console.timeEnd('expansion toggle') }, }, } </script> You can see a working demo in this codeply. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: SQL Server Insert Example I switch between Oracle and SQL Server occasionally, and often forget how to do some of the most trivial tasks in SQL Server. I want to manually insert a row of data into a SQL Server database table using SQL. What is the easiest way to do that? For example, if I have a USERS table, with the columns of ID (number), FIRST_NAME, and LAST_NAME, what query do I use to insert a row into that table? Also what syntax do I use if I want to insert multiple rows at a time? A: To insert a single row of data: INSERT INTO USERS VALUES (1, 'Mike', 'Jones'); To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update. INSERT INTO USERS (FIRST_NAME, LAST_NAME) VALUES ('Stephen', 'Jiang'); To insert multiple rows of data in SQL Server 2008 or later: INSERT INTO USERS VALUES (2, 'Michael', 'Blythe'), (3, 'Linda', 'Mitchell'), (4, 'Jillian', 'Carson'), (5, 'Garrett', 'Vargas'); To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so: INSERT INTO USERS (FIRST_NAME, LAST_NAME) SELECT 'James', 'Bond' UNION ALL SELECT 'Miss', 'Moneypenny' UNION ALL SELECT 'Raoul', 'Silva' Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here. A: Here are 4 ways to insert data into a table. Simple insertion when the table column sequence is known. INSERT INTO Table1 VALUES (1,2,...) Simple insertion into specified columns of the table. INSERT INTO Table1(col2,col4) VALUES (1,2) Bulk insertion when... You wish to insert every column of Table2 into Table1 You know the column sequence of Table2 You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once). INSERT INTO Table1 {Column sequence} SELECT * FROM Table2 Bulk insertion of selected data into specified columns of Table2. . INSERT INTO Table1 (Column1,Column2 ....) SELECT Column1,Column2... FROM Table2
{ "pile_set_name": "StackExchange" }
Q: Multinomial Coefficients Confusion As far as I know for binomial coefficients, we can express one as either $\binom {n} {k}$ or $\binom {n} {k,\ n-k}$. If I'm not wrong they both mean the same thing: $\frac{n!}{k!(n-k)!}$ What about multinomial coefficients? If I have an expression $\binom {n} {i,\ j}$, is it the same as $\binom {n} {i,\ j,\ n-i-j}$? Which one of the two is $\frac{n!}{i!j!n-i-j!}$ and which one's $\frac{n!}{i!j!}$? I'm confused. Thanks. A: You will get a more intuitive understanding by considering dividing people into labelled groups. If $10$ people are to be divided into two labelled groups $A$ and $B$ of, say, $7$ and $3$, we can use the binomial coefficient to write $\binom{10}7$ or the multinomial coefficient to write $\binom{10}{7,3}$ If we are to divide them into three groups of $5$, $3$, and $2$, we can write $\binom{10}{5,3}$ or $\binom{10}{5,3,2}$ because the last group gets formed automatically with the residue. The point is that the last part can always be left out of the expression, and conventionally it is left out when there are two groups, but is left to taste when more than two groups are there. In $\binom{n}{i,j} \equiv \binom{n}{i,j,n-i-j}$ the $RHS$ is the full expression for $3$ groups with the last group having $0$ members, and the LHS is the abridged form for the same grouping.
{ "pile_set_name": "StackExchange" }
Q: Use same app on multiple domains I'm creating a Social Media management webapp. This webapp will be used by our customers on there own sites (read, own domains). The webapp connects to a facebook app that we own, to allow them to manage there pages. I'm using the "Website" platform for the app. During development I've had the "Site URL" set to my localhost url, and the "App Domains" set to localhost. This has worked fine. However I now realise that this app will not always be run from localhost. It will be run from many differnt domains. I've read many posts about how its not possible to do this anymore, or at least the max is 5 domains by adding multiple platforms. So how am I supposed to do this? Will I need to create an app on my profile for each customer/site? Will I have to create an app on each customers facebook account and link its app ID to our webapp? A: The solution for this was not so bad. Since AccessTokens are portable, so you can generate them on a single domain, and then use them to access the API from any page. To do this, I have setup a single page on my own server (not customers server), whos domain is in my Apps Domains property. This page just has the facebook JS SDK, and some code to handle whether or not to show a login or a logout button. I embed this as an iFrame inside my webapp (that can run from any URL). I use FB.Event.subscribe('auth.authResponseChange' function {}); to look for status changes, then use the the JS postMessage method to send the result of this to the parent of the iFrame, who then sends it to the server. This AccessToken can then be used anywhere.
{ "pile_set_name": "StackExchange" }
Q: Optimal way to export JDK_HOME setting in openSUSE for use with PhpStorm? I'm trying out PHPStorm on openSUSE, and it requires the Sun Java JDK which doesn't come by default. I installed the Sun JDK based on directions here. I can run PHPStorm file as root user after that procedure but when I try to run it under my user account I get an error saying that Java is not found. The solution I'm using is to add the following to the top of the phpstorm.sh script: export JDK_HOME=/opt/java/64/jre1.6.0_30 I'm wondering if this is the best way to accomplish this or if there is a better/cleaner way to do it? A: If you want to affect this export for all system (not a just for particular user) please create appropriate file-script in /etc/profile.d folder. Example /etc/profile.d/java.sh export JDK_HOME=/opt/java/64/jre1.6.0_30
{ "pile_set_name": "StackExchange" }
Q: on C part of C++ project (VS10) I have a C++ VS2010 project. I want it to be pure C, so I will have a pure C library and a C++ file that will call that library. Is it possible? Will I have be able to pass data from the C part to C++? A: Yes. See how to mix c and c++. Of course, you could (probably) just compile the c code with a c++ compiler and save yourself a headache. If you want to link object files compiled by a c compiler, you'll need to use extern "C" { } to declare the functions, so that they aren't name mangled by the C++ compiler. It really depends on how you want to build your project. If you're more specific, you'll get better answers.
{ "pile_set_name": "StackExchange" }
Q: finding the area of mutual What I need to do is to find out the area of the shaded regions. And also how to get the area of the reason where three circle are mutually intersected. Do I have to make a triangle inside the mutual intersections? A: Hint: The area of the shaded region in the given picture is equal to the area of the shaded region in this picture.
{ "pile_set_name": "StackExchange" }
Q: Getting reCaptcha to work over Ajax with jQuery I have a form that validates and posts with Ajax, or more specifically, with $.post(). At one point, there is a reCaptcha. This form worked fine when I did not use $.post() but posted the old-fashioned way (with a page refresh), just for reference. Converting the form requires that I changed all $_POST's to $_REQUEST's. However, this doesn't remedy the reCaptcha problem, so I've left that intact. Here is the reCaptcha PHP code inside registerPost.php: require_once('recaptchalib.php'); $privatekey = "dropbeatsnotbombs"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly echo "Error"; } else { //post form } Here's the jQuery handling the form posting: $.post('php/registerPost.php', $('#registerPost').serialize(), function(data){ if(data == "Error") { $('#caErr').show(); } else { window.location.replace("//main page"); } }); Note: the reCaptcha seems to return as false, since the form will not submit when everything is filled in correctly. What I want to do is show an error if the reCaptcha was entered wrong, and post if it was entered right, all asynchronously. Any help? A: Hmm. I need to go read the API documentation for $.post(), but my first guess is that since the form is not really submitted, the $_POST array is not being populated, so when you use values like $_POST["recaptcha_challenge_field"], it's just an empty field. Again, I need to go verify that, but that is my hunch. EDIT: Looks like I was wrong. I compared what you have to both the API and an older script I had, and what you are doing should be fine. The only difference I see is that you are passing this as data: $('#registerPost').serialize() whereas my script was passing this: $('#form').serializeArray() It could be as simple as that...
{ "pile_set_name": "StackExchange" }
Q: Java EL expressions: "property (num1|str) not readable on type (int|String)" I am trying to use EL expressions to create a predicate for filtering arbitrary objects using provided strings to describe the filter. It works for primitive types, but for some reason it tries to access the POJOs I supply as if they were the type they were trying to receive. For example, the filter: "item.num1 > item.num2" applied to the POJO: private class TestClass { private String str; private int num1, num2; public String getStr() { return str; } public void setStr(String str) { this.str = str; } // getters/setters continue below here } produces this Exception: javax.el.PropertyNotFoundException: Property 'num1' not readable on type int at javax.el.BeanELResolver$BeanProperty.read(BeanELResolver.java:267) at javax.el.BeanELResolver$BeanProperty.access$000(BeanELResolver.java:216) at javax.el.BeanELResolver.getValue(BeanELResolver.java:62) at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:55) at org.apache.el.parser.AstValue.getValue(AstValue.java:183) at org.apache.el.parser.AstGreaterThan.getValue(AstGreaterThan.java:38) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185) at com.<redacted>.filters.ELPredicate.apply(ELPredicate.java:78) at com.google.common.collect.Iterators$7.computeNext(Unknown Source) at com.google.common.collect.AbstractIterator.tryToComputeNext(Unknown Source) at com.google.common.collect.AbstractIterator.hasNext(Unknown Source) at com.google.common.collect.Lists.newArrayList(Unknown Source) at com.google.common.collect.Lists.newArrayList(Unknown Source) at com.<redacted>.common.el.ELPredicateTest.pojoTest(ELPredicateTest.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) The predicate I put together is this: public class ELPredicate<T extends Object> implements Predicate<T> { private String expression; private String radix; /** * @param expression * expression * @param radix * string to be replaced with value in expression */ public ELPredicate(String expression, String radix) { this.expression = String.format("${%s}", expression); this.radix = radix; } @Override public boolean apply(final T input) { final Map<String, T> map = ImmutableMap.of(radix, input); ELContext context = new ELContext() { @Override public VariableMapper getVariableMapper() { // TODO Auto-generated method stub return null; } @Override public FunctionMapper getFunctionMapper() { // TODO Auto-generated method stub return null; } @Override public ELResolver getELResolver() { return new CompositeELResolver() { { this.add(new AttributeELResolver((Map<String, Object>) map)); this.add(new BeanELResolver(true)); this.add(new MapELResolver(true)); this.add(new ListELResolver(true)); this.add(new ArrayELResolver(true)); } }; } }; return (boolean) ExpressionFactory.newInstance().createValueExpression(context, expression, boolean.class).getValue(context); } } The AttributeELResolver is an in-house piece of code that I can't paste here, but it just resolves strings in the expression to their values in the map, it lets me define what 'item' is. A: Found the solution! As it turns out, it was an access issue, not a type compatibility issue like I first thought. Changing the private inner class (TestClass) to public made everything work as expected.
{ "pile_set_name": "StackExchange" }
Q: start broadcastreceiver Here I am trying to read the message and toast it I have seen various examples where there is a separate class that extends BroadcastReceiver but they have not mentioned how to start this class(do we use startactivity() or somthing else). I have posted the code that I dowladed through a link from O'Reilly's cookbook. I've tried to sms from ddms but it doesn't show toast of message. Any help is appreciated as this is my first time with BroadcastReceiver. invitationSMSreciever.java package com.SMS; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.sax.StartElementListener; import android.telephony.SmsMessage; import android.util.Log; import android.widget.Toast; public class invitationSMSreciever extends BroadcastReceiver { final String TAG = "BombDefusalApp"; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String message = ""; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); message = msgs[i].getMessageBody(); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); if (msgs[i].getMessageBody().equalsIgnoreCase("Invite")) { // Intent myIntent = new Intent(MainMenu.this, // com.bombdefusal.ReceivedSMSActivity.class); Intent myIntent = new Intent(); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); myIntent.setAction("com.example.helloandroid.INVITE"); context.startActivity(myIntent); } } } } } MainMenu package com.SMS; import com.SMS.R; import android.app.Activity; import android.os.Bundle; public class MainMenu extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } ReceivedSMSActivity package com.SMS; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import com.SMS.R; public class ReceivedSMSActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startService(new Intent ("com.android.PLAY")); setContentView(R.layout.invite); } public boolean onKeyDown(int keyCode, KeyEvent service) { stopService(new Intent("com.bombdefusal.START_AUDIO_SERVICE")); finish(); return true; } } manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.SMS" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.RECEIVE_SMS"/> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainMenu" android:label="@string/app_name"> <intent-filter> <action android:name="com.SMS" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.SMS.ReceivedSMSActivity" android:label="@string/app_name"> <intent-filter> <action android:name="com.example.helloandroid.INVITE"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <receiver android:name="com.SMS.invitationSMSreciever" android:enabled="true"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </receiver> </application> </manifest> A: You have two options to do this: Register you broadcast receiver statically in the AndroidManifest file. Thus, it will be called automatically. Register you broadcast receiver dynamically in your code using registerReceiver() method. In this case, this method should be paired with unregisterReceiver() where you unregister your receiver. Usually, if broadcast receiver is implemented as a separate class then it usually registered statically in AndroidManifest file. I guess in you case you should just add the following lines to your file: <receiver android:name=".invitationSMSreciever" android:exported="true" > <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
{ "pile_set_name": "StackExchange" }
Q: GraphQL: Creating and Returning an Object in a Resolver? I've got a mutation resolver that I call directly from the server like this: import {graphql} from "graphql"; import {CRON_JOB_TO_FIND_USERS_WHO_HAVE_GONE_OFFLINE_MUTATION} from "../../query-library"; import AllResolvers from "../../resolvers"; import AllSchema from "../../schema"; import {makeExecutableSchema} from "graphql-tools"; const typeDefs = [AllSchema]; const resolvers = [AllResolvers]; const schema = makeExecutableSchema({ typeDefs, resolvers }); const {data, errors} = await graphql( schema, CRON_JOB_TO_FIND_USERS_WHO_HAVE_GONE_OFFLINE_MUTATION, {}, {caller: 'synced-cron'}, {timeStarted: new Date().toISOString().slice(0, 19).replace('T', ' ')} ) The mutation resolver is called and runs correctly. I don't need it to return anything, but GraphQL throws a warning if it doesn't, so I'd like it to return an object, any object. So I'm trying it like this: SCHEMA cronJobToFindUsersWhoHaveGoneOffline(timeStarted: String): myUserData QUERY // note -- no gql. This string is passed directly to function graphql() // where it gets gql applied to it. const CRON_JOB_TO_FIND_USERS_WHO_HAVE_GONE_OFFLINE_MUTATION = ` mutation ($timeStarted: String){ cronJobToFindUsersWhoHaveGoneOffline(timeStarted: $timeStarted){ id, }, } `; RESOLVER cronJobToFindUsersWhoHaveGoneOffline(parent, args, context) { return Promise.resolve() .then(() => { // there is code here that finds users who went offline if any return usersWhoWentOffline; }) .then((usersWhoWentOffline) => { // HERE'S WHERE I HAVE TO RETURN SOMETHING FROM THE RESOLVER let myUserDataPrototype = { __typename: 'myUserData', id: 'not_a_real_id' } const dataToReturn = Object.create(myUserDataPrototype); dataToReturn.__typename = 'myUserData'; dataToReturn.id = 'not_a_real_id'; return dataToReturn; <==GRAPHQL IS NOT HAPPY HERE }) .catch((err) => { console.log(err); }); }, } GraphQL throws this warning: data [Object: null prototype] { cronJobToFindUsersWhoHaveGoneOffline: [Object: null prototype] { id: 'not_a_real_id' } } errors undefined I have tried all kinds of different ways to fix this, but I haven't figured out the correct syntax yet. What is a good way to handle this? A: That doesn't appear to be a warning. That looks like you're writing the result to the console somewhere.
{ "pile_set_name": "StackExchange" }
Q: How to edit HTML with CSS? As I'm having my website edited in one of the web editors, I'm unable to access some of the files to edit the HTML myself. I read lots of topics on how to alter HTML with CSS, but in this case those didn't work. This is the HTML generated with Chrome's inspector (again, I can't access this HTML in the editor): <table id="wsite-com-checkout-list"> <thead> <tr> <th class="wsite-com-checkout-list-item" colspan="2">Items</th> <th class="wsite-com-checkout-list-price">Price</th> <th class="wsite-com-checkout-list-quantity">Quantity</th> <th class="wsite-com-checkout-list-total wsite-align-right">Total</th> </tr> </thead> </table> So I'd like to have words Items, Price, Quantity and Total translated to another language, how do I do it? One another example I need help about: <a class="wsite-com-continue-shopping" href="/"> <span class="caret">◀</span> Continue Shopping</a> I'd like to have the word "Continue Shopping" translated to another language here. A: Short Answer: CSS isn't really designed for that sort of thing, you should probably look into a different solution. It is technically possible though. You can actually set the content of CSS elements, but only :before and :after elements that are applied to the element. Therefore, if you have an element like <td id="HelloText">Hello</td> You can have it "translated" to Spanish with #HelloText { font-size: 0; // hides existing text } #HelloText:after { font-size: 14px; content: "Hola"; } This isn't really ideal though, because this adds more bloat to your CSS and HTML (your page is loading the English and other language text), and this won't really work well for large blocks of text, or formatted text, eg text with <span> tags or <a> tags. Not to mention that this is really bad for SEO. A search engine crawler normally just looks at a page's HTML (and sometimes Javascript) to index the page, never at what is in the CSS files attached to the page. You definitely want to talk to the programmers that have access to the HTML to see if you can implement a server-side or Javascript solution for translation.
{ "pile_set_name": "StackExchange" }
Q: Return true (1), if a joined data entry exists, else false (0) in MS-SQL I have an SQL statement that joins to two different tables in a 1 to 1 relationship each. For each of those joins, I want to return a BIT value (0 or 1), if the join was successful or not. Let's say, we have a base table Base and the tables A and B, which are joined together via a LEFT JOIN on a common ID. I want to return the ID, as well as a field IsA and a field IsB. What would be the best-practice solution to do this in Microsoft SQL Server most efficiently? By the way, my current approach is this: CAST(ISNULL(A.ID, 0) AS BIT) AS IsA, CAST(ISNULL(B.ID, 0) AS BIT) AS IsB A: You can use the following, using CASE WHEN instead of ISNULL: SELECT Base.*, A.id, B.id, CAST(CASE WHEN A.id IS NULL THEN 0 ELSE 1 END AS BIT) AS IsA, CAST(CASE WHEN B.id IS NULL THEN 0 ELSE 1 END AS BIT) AS IsB FROM Base LEFT JOIN A ON Base.id = A.base_id LEFT JOIN B ON Base.id = B.base_id demo on dbfiddle.uk This solution, compared to your current approach, has the same efficiency. But also see this answer (check multiple columns for NULL values). There you can see the ISNULL solution is less efficient. In your case it makes no big difference. Also be careful: The ISNULL can also return 0 in case the column values is 0. So with your current approach you would get False in such a case.
{ "pile_set_name": "StackExchange" }
Q: Deserialize JSON to list in C# json - http://pastebin.com/Ss1YZsLK I need to get market_hash_name values to list. I can receive first value so far: using (WebClient webClient = new System.Net.WebClient()) { WebClient web = new WebClient(); var json = web.DownloadString(">JSON LINK<"); Desc data = JsonConvert.DeserializeObject<Desc>(json); Console.WriteLine(data.rgDescriptions.something.market_hash_name); } public class Desc { public Something rgDescriptions { get; set; } } public class Something { [JsonProperty("822948188_338584038")] public Name something { get; set; } } public class Name { public string market_hash_name { get; set; } } How can I get all if them? A: Since there is no array inside the rgDescriptions but some randomly named looking properties I think you would need a custom JsonConverter. The following console application seems to be working and displaying the market_hash_names correctly: class Program { static void Main(string[] args) { string json = File.ReadAllText("Sample.json"); Desc result = JsonConvert.DeserializeObject<Desc>(json); result.rgDescriptions.ForEach(s => Console.WriteLine(s.market_hash_name)); Console.ReadLine(); } } public class Desc { [JsonConverter(typeof(DescConverter))] public List<Something> rgDescriptions { get; set; } } public class Something { public string appid { get; set; } public string classid { get; set; } public string market_hash_name { get; set; } } class DescConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(Something[]); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var descriptions = serializer.Deserialize<JObject>(reader); var result = new List<Something>(); foreach (JProperty property in descriptions.Properties()) { var something = property.Value.ToObject<Something>(); result.Add(something); } return result; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } Output: Genuine Tactics Pin Silver Operation Breakout Coin Operation Phoenix Challenge Coin Operation Bravo Challenge Coin
{ "pile_set_name": "StackExchange" }
Q: Android back stack - Go back to a certain activity in back stack I have activities A -> B -> C -> D. How can I open the existing B from activity D clearing C and D? I would end up with A -> B. I don't want to recreate a new B. A: I think you must use FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP. According to the doc: consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B. The currently running instance of activity B in the above example will either receive the new intent you are starting here in its onNewIntent() method, or be itself finished and restarted with the new intent. If it has declared its launch mode to be "multiple" (the default) and you have not set FLAG_ACTIVITY_SINGLE_TOP in the same intent, then it will be finished and re-created; for all other launch modes or if FLAG_ACTIVITY_SINGLE_TOP is set then this Intent will be delivered to the current instance's onNewIntent().
{ "pile_set_name": "StackExchange" }
Q: Is this site for experts, or not? On the one hand, this question here about what RPG.SE is, and this answer here about answering FATE questions, specify "[this site] is a collection of expert knowledge" and "Expert questions to be answered by Experts". On the other hand, the help page states Anybody can ask a question Anybody can answer and this answer has several newbie-friendly nuggets of wisdom. This question is encouraging, too. In the question about FATE, one bit of an answer stated: It seems like people are so bogged down with non-expert fate questions that the first instinct is to give an answer suited for a beginner in the system and not an expert. This points out that there are non-experts asking questions, that they are many (how are they bogging down people otherwise?), and that they aren't really welcome (at least, not by the answerer): they ask the "wrong" sort of questions. So which is it? I ask because I'm not an expert on D&D 4E, 2E, Numenera or Fiasco. I just play and GM them. I have very limited time and chances to play, often having dry spells of months between 4-hour sessions. I enjoy rereading my corebooks and splats, but without actual playtime, my questions and answers will never actually be of "expert level". The help page is inclusive, and makes me feel I can actually ask questions here. The first answers and comments cited don't, they make me feel that I can at best lurk and check from time to time if something interesting shows up. In the end, I feel I'm almost restating this question, though not exactly. Return to FAQ Index A: If you play RPGs, you're an expert and welcome. The line "Asking Expert questions, getting expert answers" has a particular history dating to when it was just the original three sites. "Expert questions" was important because they didn't want to teach askers the basics of how to program. Being an expert meant that you already knew how to program and what programming meant. The parallel here isn't perfect, so those words aren't so meaningful here. In practice we're OK fielding a question that is asking to be taught what RPGs are, so long as we don't get too many of them. We're not interested in teaching every comer how to RPG, so mostly we end up closing them as unclear or duplicates of the two or three existing questions about getting started. But we have them. So what does that say about where we draw the line between expert and non-expert? All it takes to be an expert is actual experience playing RPGs If you're new to RPGs, all it takes to be accepted is knowing enough to be able to ask a coherent question about how to learn more. So the bar for "expert" here is extremely low. Which makes sense, because it's such a niche hobby that if you even know it exists enough to ask a meaningful question, you probably actually know quite a bit of the basics already. A: (This answer is not about the linked post(s), it is in general) The "expert" terminology is from an earlier rev of Stack Exchange, where Stack Overflow and the other sites tended to talk about "expert" users, and have since moved to terminology like "professional and enthusiast" or similar. So no, you don't have to be an expert to use the site. Asking To ask a question, you should however have tried to get understanding on your own. "I don't want to read the rulebook, read it to me" is unacceptable and off topic. Look at the downvote tooltip, it says: This question does not show any research effort; it is unclear or not useful We have a couple placeholder questions to help orient the "I likey the RPGs where do I start" folks that show up, but we don't want a huge amount of that on the site. Read the book, watch a YouTube video, then bother other people to give you more handholding. Doing it prior to that is frankly rude and answering them is just feeding their general personality problem of lack of ability to learn. See https://meta.stackoverflow.com/questions/257868/can-we-please-have-the-lacks-minimal-understanding-close-reason-back for the SO discussion, "close as Unclear" is the consensus. Answering To answer a question, basically, you should be knowledgable enough to be qualified to answer it. If you haven't read that game, you're not qualified to answer a rules question. If it's a subjective question, if you haven't played that game and done that thing, you're not qualified. But you don't have to be a game designer or have played for 20 years. You should also generally have paid a day worth of attention to how RPG.SE works and have perused the Tour before you ask or answer. "Expert" means different things to different people. I think "basically know what you're doing" is more the bar. A: Yes, and No. As has been stated, the "expert" term came from the past and isn't super relevant today. Generally speaking, the criteria for if you belong here are fairly simple: Do you play or want to play RPGs, or games that fall under our umbrella (like LARPs)? Do you have questions about one or more of those games that you can't answer by reading that section of the rules? (If you have read it and the rules are confusing you, that qualifies.) Do you have answers to other people's questions about one or more of those games? If you answer yes to #1, then you belong here. If you answer yes to #2, ask away! If you answer yes to #3, answer away! Some of our questions are pretty beginner oriented, as you noticed. That applies to FATE, but also to systems like D&D. We get lots of 3.5 and Pathfinder questions that don't require what I'd call "expert" knowledge to answer, but that anybody who has played for a while can answer. Then we get harder questions that do require a lot of experience and research. Some questions don't really even have "experts". What does an expert GM/DM/Storyteller/Whatever look like? I have no idea. Questions about how to run a game are wide open to anybody with experience doing it. If you've done it, you're probably just as much of an "expert" on the subject as I am.
{ "pile_set_name": "StackExchange" }
Q: Pen tablet input for FPS So in my FPS camera look code, I have something like this: window->camera->stepYaw( getMouseDx()*speed ) ; // mouseDx is mouse change since last frame window->camera->stepPitch( getMouseDy()*speed ) ; This works fine on a normal mouse. But with pen input, its very very janky and radical. How should one control an FPS camera from pen tablet input instead of traditional mouse? A: On Windows from C++ // usFlags is ALWAYS ABSOLUTE, see if( raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE ) { // its a 0 flag so // this is am real mouse // lLastX and lLastY are relative to last pos } else if( raw->data.mouse.usFlags | MOUSE_MOVE_ABSOLUTE ) { // its a tablet or positioning device // 1 .. 65537, ACROSS THE DESKTOP // get the relative change in position // to turn it into a pixel count, // you have to have the old values of lLastX // and lLastY (in the last call to this fcn). }
{ "pile_set_name": "StackExchange" }
Q: undefined method error for :string I have this code... foo = opt_source.downcase.camelize "#{foo}".new.start_check this should call a class and the method start_check, but I am getting an undefined method error undefined method `start_check' for "Abcd":String (Abcd is the class that foo represents) Any suggestions on how what I am doing wrong? A: You need to convert that string into a constant. Historically this was done with eval but this leads to security issues in your code -- never eval user-supplied strings. The correct way to do this (in Rails) is via String#constantize: foo = opt_source.downcase.camelize foo.constantize.new.start_check For ruby, use Kernel#const_get: foo = opt_source.downcase.camelize Kernel.const_get(foo).new.start_check Don't forget to check for errors before calling your methods.
{ "pile_set_name": "StackExchange" }
Q: AVQueuePlayer volume not changed I wanted to change volume settings with a UISlider. I used currentItem inside AVQueuePlayer. ps0 is an AVQueuePlayer. I have no error and same sound level when I use my UISlider: - (IBAction)volumeSliderMoved:(UISlider *)sender { AVMutableAudioMixInputParameters *audioInputParams = [AVMutableAudioMixInputParameters audioMixInputParameters]; AVPlayerItem *av = [ps0 currentItem]; CMTime currentTime = [av currentTime]; float volume = [sender value]; [audioInputParams setVolume:volume atTime:currentTime]; AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix]; audioMix.inputParameters = [NSArray arrayWithObject:audioInputParams]; av.audioMix = audioMix; [ps0 replaceCurrentItemWithPlayerItem: av]; } EDITED : I tried another solution from Apple to change volume settings. As you can see in this solution, it create a new playerItem and a new player. But my playerItem is a copy of the current one because I just want to change the sound (not the item). And it is automatically related to the old player. When I try to use their solution. I have an error message saying: An AVPlayerItem cannot be associated with more than one instance of AVPlayer Any suggestion? EDITED again To change playback with AVQueuePlayer I have an array with every mp3 name “textMissingTab” I have an array with AVPlayerItem “soundItems” Creation : textMissingTab = [[NSArray alloc] initWithObjects:@"cat",@"mouse",@"dog",@"shark",@"dolphin", @"eagle", @"fish", @"wolf", @"rabbit", @"person", @"bird", nil]; for (NSString *text in textMissingTab) { NSURL *soundFileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:text ofType:@"mp3"]]; AVPlayerItem *item = [AVPlayerItem playerItemWithURL:soundFileURL]; [soundItems addObject:item]; } Init : NSURL *soundFileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"dog" ofType:@"mp3"]]; ps0 = [[AVQueuePlayer alloc] initWithURL:soundFileURL]; Change playItem : text is NSString int index = [textMissingTab indexOfObject:text]; [ps0 setActionAtItemEnd:AVPlayerActionAtItemEndNone]; CMTime newTime = CMTimeMake(0, 1); [ps0 seekToTime:newTime]; [ps0 setRate:1.0f]; [ps0 replaceCurrentItemWithPlayerItem:[soundItems objectAtIndex:(index)]]; [ps0 play]; A: I had several problems using AVQueuePlayer and changing playback parameters. If your goal is to use a slider for volume adjustment, I would replace the UISlider with a blank UIView in your storyboard and then instantiate an MPVolumeView within that view. This works reliably for me. Note that MPVolumeView does not show up on the simulator.
{ "pile_set_name": "StackExchange" }
Q: How to refactor the pervasive if statement for type check I'm work with a legacy system which has been around ten years, in it one of the basic data structure is defined like below: [Serializable()] public class DataClass { private Array _values; private readonly Type _valueType; public DataClass(Array tmpArray, Type tmpType) { _values = tmpArray; _valueType = tmpType; } public Array GetValues() { return _values; } public Type ValueType { get { return _valueType; } } public void SetValues(Array newValues, int fromIndex) { // 1. type check, if _values and newValues don't share same data type, throws an exception // 2. length check if (fromIndex + newValues >= _values.Length) throws new InvalidDataException(); // 3. set values for (var i = fromIndex; i < newValues.Length; i++) _values.SetValue(newValues.GetValue(i - fromIndex), i); } ...blahblah } I believe the initiative was they want to support different data types using only one class, e.g. new DataClass(new int[]{1,2,3,4}, typeof(int)); new DataClass(new float[]{1f,2f,3f,4f}, typeof(float)); Now I want to init the DataClass with default values, after profiling I found that the API SetValues is quite slow for longer arrays (boxing and unboxing I believe) and makes the program less responsive, I decided to use Generic and lots of if else statement for speeding up, e.g.: void InitValues(DataClass data) { if (data.ValueType == typeof(int)) InitWith(data, -1); else if (data.ValueType == typeof(double)) InitWith(data, -9.99d); ...blahblah } void InitWith<T>(DataClass data, T defaultValue) { // much faster var array = (T[])data.GetValues(); for (var i = 0; i < array.Length; i++) array[i] = defaultValue; } Yet I got plenty of performance critical methods like InitValues.Since there are so many value types that DataClass supports, it's irritating to write and maintain such code. Given the fact that I don't own the source code of DataClass, I can't make any change to the DataClass. I wonder whether there is a way to refactor, so that I can deal with all the if statements of type check in one place? A: Given that your are not allowed to change the DataClass, we need to make the consumers of the DataClass efficient. One way to do that would be to use Dictionaries to map the Types to the Actions/Methods. We would need to initialize these dictionaries only once. Here is an example to such a class. class ConsumerClass // the one which uses DataClass objects { // All the Mappings required by this consumer class readonly Dictionary<Type, Action<DataClass>> InitMap = new Dictionary<Type, Action<DataClass>>(); readonly Dictionary<Type, Action<DataClass>> DoSomethingAMap = new Dictionary<Type, Action<DataClass>>(); readonly Dictionary<Type, Action<DataClass>> DoSomethingBMap = new Dictionary<Type, Action<DataClass>>(); // Constructor public ConsumerClass() { // Initialize all the mappings for all the required types for this consumer class here. // This is a one time overhead, but will definitely speedup the methods within this class // You could move this part further up the hierarchy of inheritance, to avoid repetitions in every other consumer class. // For int InitMap.Add(typeof(int), data => InitWith(data, -1)); DoSomethingAMap.Add(typeof(int), DoSomethingA<int>); DoSomethingBMap.Add(typeof(int), DoSomethingB<int>); // For double InitMap.Add(typeof(double), data => InitWith(data, -9.99d)); DoSomethingAMap.Add(typeof(double), DoSomethingA<double>); DoSomethingBMap.Add(typeof(double), DoSomethingB<double>); // other types, if needed by this consumer } void InitValues(DataClass data) { // This takes care of your if s InitMap[data.ValueType].Invoke(data); } void InitWith<T>(DataClass data, T defaultValue) { // much faster var array = (T[])data.GetValues(); for (var i = 0; i < array.Length; i++) array[i] = defaultValue; } void DoSomethingA(DataClass data) { DoSomethingAMap[data.ValueType].Invoke(data); } void DoSomethingA<T>(DataClass data) { var array = (T[])data.GetValues(); // do something } void DoSomethingB(DataClass data) { DoSomethingBMap[data.ValueType].Invoke(data); } void DoSomethingB<T>(DataClass data) { var array = (T[])data.GetValues(); // do something } } There is some redundant code in the constructor, so there could still be a better way to write this mechanism. But you should get an idea of how you could clean up your ifs and still improve the performance.
{ "pile_set_name": "StackExchange" }
Q: How to combine columns of two tables I have three temporary columns, @Pid (PartyId bigint) which contains All Partyid @t PartyID bigint,PartyName varchar(50)SaleQty decimal(18,2)) it contains Sale history of All parties of financial year 15-16. @ty PartyID bigint,PartyName varchar(50)SaleQty decimal(18,2)) it contains Sale history of All parties of financial year 16-17. I want to combine two temporary table @t and @ty such a way that record of any party id of both financial record should be in one row. And also if any partyid does not have entry in anyone of the table @t and @ty then the saleQty should be zero of in that financial year. I have done following query to solve this. select A.PartyName,isnull(SUM(A.SaleQty),0) as TotalSale,isnull(SUM(B.SaleQty),0) as TotalSaleB from @t A left join @ty B ON B.PartyId=A.PartyID inner join @Pid P on P.PartyID=A.PartyID and B.PartyID=P.PartyID where PartyName like'%Jain' group by A.PartyID,A.PartyName My Output is PartyName TotalSale(15-16) TotalSale(16-17) JAIN TRADERS (DHAMPUR) 16682.00 9699.00 My Desired Result should be PartyName TotalSale(15-16) TotalSale(16-17) JAIN TRADERS (DHAMPUR) 389.00 139.00 Sourav Traders 3899.00 0.00 Tickrej Traders 0.00 0.00 But i am unable to get the desired result. Please Help me some one here. A: Try this: declare @Pid table (PartyId bigint) insert into @Pid values (1) insert into @Pid values (2) insert into @Pid values (3) insert into @Pid values (4) declare @t table (PartyID bigint, PartyName varchar(50), SaleQty decimal(18,2)) insert into @t values(1, 'a', 10) insert into @t values(1, 'c', 5) insert into @t values(2, 'b', 10) insert into @t values(4, 'b', 20) declare @ty table(PartyID bigint,PartyName varchar(50), SaleQty decimal(18,2)) insert into @ty values(1, 'a', 10) insert into @ty values(2, 'c', 15) insert into @ty values(2, 'b', 10) select c.PartyID as PartyID, ISNULL(sum(A.SaleQty), 0) as TotalSale15_16 into #A from @t A right join @Pid c on A.PartyID = c.PartyId group by C.PartyID select c.PartyID as PartyID,ISNULL(sum(B.SaleQty), 0) as TotalSale16_17 into #B from @ty B right join @Pid c on B.PartyID = c.PartyId group by C.PartyID select A.PartyID, ISNULL(a.TotalSale15_16, 0) as TotalSale16_17, ISNULL(b.TotalSale16_17, 0) as TotalSale16_17 from #A a join #B b on a.PartyID = b.PartyID drop table #A drop table #B result: PartyID TotalSale16_17 TotalSale16_17 1 15.00 10.00 2 10.00 25.00 3 0.00 0.00 4 20.00 0.00
{ "pile_set_name": "StackExchange" }
Q: Откуда взялся зазор между Toolbar и RelativeLayout внутри LinearLayout? Есть такая разметка: <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".cityActivity"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.Base.AppBarOverlay"> <include layout="@layout/toolbar"/> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".cityActivity" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:paddingLeft="5dp" android:paddingRight="5dp" android:background="?attr/colorPrimary" android:id="@+id/searchLayout"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/etSearch" android:drawableLeft="@android:drawable/ic_menu_search" android:hint="Название города" android:background="@drawable/rounded_edittext" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textSize="15dp" android:focusableInTouchMode="true"/> </RelativeLayout> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/list" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:choiceMode="singleChoice" android:layout_below="@+id/searchLayout" android:divider="@color/divider" android:dividerHeight="1dp" android:focusableInTouchMode="true"> </ListView> </LinearLayout> <android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_city2" app:menu="@menu/activity_city2_drawer" /> </android.support.v4.widget.DrawerLayout> </LinearLayout> </android.support.design.widget.CoordinatorLayout> В предпросмотре видим зазор между тулбаром и RelativeLayout с EditText'ом: На устройстве зазор еще больше. Исследовал все что мог, без вашей помощи не обойтись. UPD А в следующем активити, там, где я не использую шторку или CoordinatorLayout, или виджет AppBarLayout все нормально: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="ru.qwerq.qwerq.sferaActivity" android:focusableInTouchMode="true"> <include layout="@layout/toolbar"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:orientation="horizontal" android:paddingLeft="5dp" android:paddingRight="5dp" android:background="?attr/colorPrimary"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/etSearch" android:drawableLeft="@android:drawable/ic_menu_search" android:hint="Название категории" android:background="@drawable/rounded_edittext" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textSize="15dp" /> </RelativeLayout> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/list" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:choiceMode="singleChoice" android:divider="@color/divider" android:dividerHeight="1dp"> </ListView> </LinearLayout> A: Для android.support.design.widget.AppBarLayout Используйте app:elevation="0dp" вместо android:elevation="0dp"
{ "pile_set_name": "StackExchange" }