_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d101
train
Some backend Prolog compilers, such as SWI-Prolog when running on Windows, down-case file names when expanding file paths into absolute file paths. This caused a failure in the Logtalk compiler when going from the file argument in the compilation and loading predicates to an absolute file path and its components (directory, name, and extension). A workaround have been found and committed to the current git version. Thanks for the bug report.
unknown
d102
train
The docs say that I have to import java.lang.Object for both, and I imported java.lang* Any documentation that tells you that you have to import classes in java.lang is blatantly wrong. The classes in java.lang are implicitly imported. In fact, I suspect that your problem is that you need to add the JAR files containing those two classes (ADSTool and PPM) to the build path of your Eclipse project. If the classes are not available on the build path, the Eclipse compiler won't find them. A: check Project->Properties->Java Build Path did you include JRE System Library in Libraries Tab? A: Import java.lang.*, not java.lang*. The second dot matters; without it, the compiler can get confused about what you're actually trying to import.
unknown
d103
train
I think the problem lies in your views.py. Try getting request.user before saving the form. A: i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:- if request.method == 'POST': Inven_form=InventoryForm(data=request.POST) if Inven_form.is_valid(): user=Inven_form.save() #in between add this Inven_form.updated_by=request.user.username user.save() A: I would use the 'commit=False' argument which will create a new object and assign it without saving to your database. You can then set the user attribute and call save() with no arguments. For example, this is how I assigned the user attribute to my blog app. in views.py if form.is_valid(): # Create a new entry and assign to new_article. new_article = form.save(commit=False) # Set the new article attribute to the current user. new_article.user = request.user # Save to database now the object has all the required data. new_article.save() Here is the full code for the add_article view if this helps. @login_required def add_article(request): """ Add a new article. """ if request.method != 'POST': # No data submitted, create a blank form. form = AddArticleForm() else: # POST data submitted, process data. form = AddArticleForm(request.POST, request.FILES) if form.is_valid(): new_article = form.save(commit=False) new_article.author = request.user new_article.save() return back_to_blog_page() context = {'form': form} return render(request, 'add_article.html', context)
unknown
d104
train
I think you need to change this: $(this).parent().prepend('<span class="sub-nav-toggle"></span>'); to this: $(this).prev().addClass('sub-nav-toggle');
unknown
d105
train
wsgi.py is imported by your Python application server, e.g. gunicorn. Management commands are executed directly and bypass importing wsgi.py. You should use some mechanism, e.g. django-dotenv to load environment variables from a .env file both in your manage.py script and wsgi.py application initializer.
unknown
d106
train
You might have: <h:form id="form1"> ..... <h:form id="form2"> ... </h:form> ... </h:form> I got the same error, I remove the nested Form. I removed Form2 and it worked fine.
unknown
d107
train
You can write something like this: read -p "Enter the answer in Y/N: " value if [[ "$value" = [yY] ]] || [[ "$value" = [yY][eE][sS] ]]; then echo 0; # Operation if true else echo 1; # Operation if false fi A: you can fix this issue in many ways. use this code on awk to fix your problem. #!/bin/bash read -p "choose your answer [Y/N]: " input awk -vs1="$input" 'BEGIN { if ( tolower(s1) == "yes" || tolower(input) == "y" ){ print "match" } else{ print "not match" } }'
unknown
d108
train
Why don't you do something like that: function echoBasedOnDay($date) { if ($date === date('Y-m-d', strtotime("+7 days"))) { echo "Tadarus"; } elseif($date === date('Y-m-d', strtotime("+14 days"))){ echo "Kajian"; } elseif($date === date('Y-m-d', strtotime("+7 days"))){ echo "Edukasi"; } elseif($date === date('Y-m-d', strtotime("+7 days"))){ echo "Umum"; } } echoBasedOnDay(date('2019-09-27')); // You can pass any date you want in here as the function's parameter
unknown
d109
train
You didn't provide any pictures. So, I used css styles. You can remove the background color and add your pic urls. div.image { position: relative; } img#profile { width: 250px; height: 250px; background: blue; border-radius: 50%; z-index: 100; left: 10px; top: 10px; position: absolute; } img#frame { width: 270px; height: 270px; background: tomato; border-radius: 50%; z-index: -1; } JSFIDDLE A: You need to fix it yourself whenever you change the size. div.image { position: fixed; margin: 100px; } img#profile { width: 250px; height: 250px; background: skyblue; border-radius: 100%; z-index: 100; position: absolute; } img#frame { width: 270px; height: 270px; background: orange; border-radius: 100%; z-index: -1; position: absolute; top:-10px; left:-10px; }
unknown
d110
train
Simply use this: cd <specific_dir> git checkout . It will restore all files and directories in current directory which were tracked by git. Be aware that this will overwrite uncommitted changes to other files in current directory.
unknown
d111
train
First, you need to assign names to the entries in your vector (each entry will get the corresponding file name), as follows: > library(tools) > names(rlist) <- basename(file_path_sans_ext(rlist)) Then, to get a list in the format that you specified, you can simply do: rlist2 <- as.list(rlist) This is the output: > rlist2 $image1 [1] "C:/imagery/Landsat/image1.img" $image2 [1] "C:/imagery/Landsat/image2.img" $image3 [1] "C:/imagery/Landsat/image3.img" And you can access individual entries in the list, as follows: > rlist2$image1 [1] "C:/imagery/Landsat/image1.img" You can read more about the as.list function and its behavior here.
unknown
d112
train
In order to persist information across requests, you would use sessions. Django has very good session support: # view1: store value request.session['query_naissance'] = query_naissance # view2: retrieve vlaue query_naissance = request.session['query_naissance'] # or more robust query_naissance = request.session.get('query_naissance', None) You need 'django.contrib.sessions.middleware.SessionMiddleware' in your MIDDLEWARE_CLASSES.
unknown
d113
train
Are you looking for an explanation between the approach where you load in all users at once: # Loads all users into memory simultaneously @users = User.all @users.each do |user| # ... end Where you could load them individually for a smaller memory footprint? @user_ids = User.connection.select_values("SELECT id FROM users") @user_ids.each do |user_id| user = User.find(user_id) # ... end The second approach would be slower since it requires N+1 queries for N users, where the first loads them all with 1 query. However, you need to have sufficient memory for creating model instances for each and every User record at the same time. This is not a function of "DB memory", but of application memory. For any application with a non-trivial number of users, you should use an approach where you load users either individually or in groups. You can do this using: @user_ids.in_groups_of(10) do |user_ids| User.find_all_by_id(user_ids).each do |user| # ... end end By tuning to use an appropriate grouping factor, you can balance between memory usage and performance. A: Can you give a snipet of actual ruby on rails code, our pseudo code is a little confusing? You can avoid the n+1 problem by using eager loading. You can accomplish this by using :includes => tag in your model.find method. http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
unknown
d114
train
In your .tsv file the last column team is not separated from the previous column by a tab, but rather through two spaces. If you look at the data passed to the d3.tsv callback I think you will find that you have one date team column instead of a date and team column. This means that the field d.team is undefined and ordinal(undefined) will just return the first value from the range.
unknown
d115
train
Unless you want to write your own animation system for Unity, which would be probably slower due to Unity's optimizations. You can't do anything about it except tweaking the animation yourself. * *Use fewer bones *Remove redundant curves *Ensure that any bones that have colliders attached also have rigidbodies.
unknown
d116
train
Something is probably going on wrong with the pixels size. Try set the '500px' instead of '500' or percentage ('20%') Hope this helps
unknown
d117
train
Just create two instance method in Your typing indicator cell one for start animation and another for resetAnimation class TypingCell: UITableViewCell { fileprivate let MIN_ALPHA:CGFloat = 0.35 @IBOutlet weak var dot0: UIView! @IBOutlet weak var dot1: UIView! @IBOutlet weak var dot2: UIView! private func startAnimation() { UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: [.repeat, .calculationModeLinear], animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1666, animations: { self.dot0.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.16, relativeDuration: 0.1666, animations: { self.dot0.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 0.33, relativeDuration: 0.1666, animations: { self.dot1.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.49, relativeDuration: 0.1666, animations: { self.dot1.alpha = 1 }) UIView.addKeyframe(withRelativeStartTime: 0.66, relativeDuration: 0.1666, animations: { self.dot2.alpha = MIN_ALPHA }) UIView.addKeyframe(withRelativeStartTime: 0.83, relativeDuration: 0.1666, animations: { self.dot2.alpha = 1 }) }, completion: nil) } func resetAnimation() { dot0.layer.removeAllAnimations() dot1.layer.removeAllAnimations() dot2.layer.removeAllAnimations() DispatchQueue.main.async { self.startAnimation() } } } Reset your animation on tableView(_: willDisplay: cell: forRowAt:) func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let cell = cell as? TypingCell { cell.resetAnimation() } }
unknown
d118
train
Normally, what you expect to find is the default behaviour of CouchDB. I think it could depend on how the API is used however. For example, following sample scenario works fine (on CouchDB 1.5) All commands are given in bash syntax, so you can reproduce easily (just make sure to use correct document id and revision numbers). Create 10M sample file for upload dd if=/dev/urandom of=attach.dat bs=1024 count=10240 Create test DB curl -X PUT http://127.0.0.1:5984/attachtest Database expected data_size is about few bytes at this point. You can query it as follows, and look for data_size attribute. curl -X GET http://127.0.0.1:5984/attachtest which gives in my test: {"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":2,"purge_seq":0,"compact_running":false,"disk_size":8287,"data_size":407,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":2} Create sample document curl -X POST -d '{"hello": "world"}' -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest This command gives an output with document id and revision, which are then should be used hereafter Now, attach sample file to the document; command should use id and revision as logged in the output of the previous one: curl -X PUT --data-binary @attach.dat -H "Content-Type: application/octet-stream" http://127.0.0.1:5984/attachtest/DOCUMENT-ID/attachment\?rev\=DOCUMENT-REVISION-1 Last command output denotes that revision 2 have been created, so the document was updated indeed. One can check the database size now, which should be around 10000000 (10M). Again, looking for data_size in the following command's output: curl -X GET http://127.0.0.1:5984/attachtest Now, geting the document back from DB. It will be used then to update it. Important to have in it: * *the _rev in the document, to be able to update it *attachment stub, to denote that attachment should not be deleted, but kept intact curl -o document.json -X GET http://127.0.0.1:5984/attachtest/DOCUMENT-ID Update document content, not changing the attachment itself (keeping the stub there). Here this will simply change one attribute value. sed -i 's/world/there/' document.json and update document in the DB curl -X PUT -d @document.json -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest/DOCUMENT-ID Last command output denotes that revision 3 have been created, so we now that the document is updated indeed. Finally, now we can verify the database size! Expected data_size is still around 10000000 (10M), not 20M: curl -X GET http://127.0.0.1:5984/attachtest And this should work fine. For example, on my machine it gives: {"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":8,"purge_seq":0,"compact_running":false,"disk_size":10535013,"data_size":10493008,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":8} So, still 10M. A: It means that each time you're modifying the document (not the attachment, just one field of the document), it will duplicate the 100 MB attachment. In my testing I found the opposite - the same attachment is linked through multiple revisions of the same document with no loss of space. Please can you retest to be certain of this behaviour?
unknown
d119
train
You can find the option in the android lint menu: Once "Skip Library Project Dependencies" is checked, that should skip appcompat lint warnings when you are checking your project
unknown
d120
train
Your most obvious way in a stateful app is to assume that any hit on a non-login page without being logged in implies that the session has expired. A: use the Session_End event in Global.asax. Keep in mind this event does not fires when sessions are persisted outside of the process (in SQL for example)
unknown
d121
train
Yes they have their values inside. But you can't print them out on the host. For this you will need to copy your data back using cudaMemcpy((void *) array_host_2, (void *) array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost); And then you can print the values of array_host_2. A bit more explanation: Your array_device_* lives on the GPU and from your CPU (that is printing your output) you do not have direct access to this data. So you need to copy it back to your CPUs memory first before printing it out. A: Example of copying array with data to device, altering values in kernel, copy back to host and printing the new values: // Function to run on device by many threads __global__ void myKernel(int *d_arr) { int idx = blockIdx.x * blockDim.x + threadIdx.x; d_arr[idx] = d_arr[idx]*2; } int main(void) { int *h_arr, *d_arr; h_arr = (int *)malloc(10*sizeof(int)); for (int i=0; i<10; ++i) h_arr[i] = i; // Or other values // Sends data to device cudaMalloc((void**) &d_arr, 10*sizeof(int)); cudaMemcpy(d_arr, h_arr, 10*sizeof(int), cudaMemcpyHostToDevice); // Runs kernel on device myKernel<<< 2, 5 >>>(d_arr); // Retrieves data from device cudaMemcpy(h_arr, d_arr, 10*sizeof(int), cudaMemcpyDeviceToHost); for (int i = 0; i<10; ++i) printf("Post kernel value in h_arr[%d] is: %d\n", i,h_arr[i]); cudaFree(d_arr); free(h_arr); return 0; } A: The code snippet you provided seems correct, other than the first few lines as leftaroundabout pointed out. Are you sure the kernel is correct? Perhaps you are not writing the modified values back to global memory. If you make another set of host arrays and copy the GPU arrays back before running the kernel, are they correct? From what you have, the values inside array_host_* should have been copied to array_device_* properly. A: You can use a kernel function to directly print values on GPU memory. Use can use something like: __global__ void printFunc(int *devArray){ printf("%d", devArray[0]); } Hope it helps.
unknown
d122
train
You can escape new lines in VBA with _. so your solution might look like filename = Array("file1", _ "file2", _ "file3") See How to break long string to multiple lines and If Statement With Multiple Lines If you have 100's of names, however, you might be better off storing them in a worksheet and reading them in, rather than hard-coding them. A: Should you strings in the array be actually "buildable" following a pattern (like per your examples: "file1", "file2", ...,"file600") then you could have a Function define them for you, like follows: Function GetFileNames(nFiles As Long) As String() Dim iFile As Long ReDim filenames(1 To nFiles) As String For iFile = 1 To nFiles filenames(iFile) = "file" & iFile Next GetFileNames = filenames End Function which you'd call in your "main" code as follows Sub main() Dim filenames() As String filenames = GetFileNames(600) '<--| this way'filenames' array gets filled with 600 hundred values like "file1", "file2" and so on End Sub A: The amount of code that can be loaded into a form, class, or standard module is limited to 65,534 lines. A single line of code can consist of up to 1023 bytes. Up to 256 blank spaces can precede the actual text on a single line, and no more than twenty-four line-continuation characters ( _) can be included in a single logical line. From VB6's Help. A: when programming, you don't build an array this big mannually, never. either you store each multiline-string inside a Cell, and at the end you buid the array like this : option Explicit Sub ArrayBuild () Dim Filenames() 'as variant , and yes i presume when using multi files, the variable name should have an "s" With Thisworkbook.sheets("temp") 'or other name of sheet Max = .cells(.rows.count,1).end(xlup).row '=max number of rows in column 1 Filenames = .range( .cells(1,1) , .cells(Max,1)).value2 ' this example uses a one column range from a1 to a[max] , but you could also use a multi column by changing the second .cells to `.cells(Max, ColMax)` end with 'do stuff erase Filenames 'free memory End Sub An other way is to build an array like you build a house by adding one brick at a time, like this : Dim Filenames() as string 'this time you can declare as string, but not in the previous example Dim i& 'counter For i=1 to Max 'same max as in previous example, adapt code plz... redim Preserve Filenames (1 to ubound(filenames)+1) 'this is an example for unknown size array wich grows, but in your case you know the size (here Max, so you could declare it `Dim Filenames (1 to Max)` from the start, just wanted to show every option here. Filenames(i) = Cells (i,1).value2 'for example, but can be anything else. Also i'm beeing lazy and did not reference the cell to its sheet, wich i'd never do in actual coding... next i EDIT i did re-read your Question, and it is even easier (basically because you ommited the bracets in your post and corrected it as comment...), use user3598756 's code plz. I thought File1 is a variable, when it should be written as "File1" . EDIT 2 why bother build and array where Filename(x)="Filex" anyway? you know the result beforehand
unknown
d123
train
Define $.fn.findSelf = function(selector) { var result = this.find(selector); this.each(function() { if ($(this).is(selector)) { result.add($(this)); } }); return result; }; then use $.findSelf(selector); instead of $find(selector); Sadly jQuery does not have this built-in. Really strange for so many years of development. My AJAX handlers weren't applied to some top elements due to how .find() works. A: $('selector').find('otherSelector').add($('selector').filter('otherSelector')) You can store $('selector') in a variable for speedup. You can even write a custom function for this if you need it a lot: $.fn.andFind = function(expr) { return this.find(expr).add(this.filter(expr)); }; $('selector').andFind('otherSelector') A: The accepted answer is very inefficient and filters the set of elements that are already matched. //find descendants that match the selector var $selection = $context.find(selector); //filter the parent/context based on the selector and add it $selection = $selection.add($context.filter(selector); A: You can't do this directly, the closest I can think of is using .andSelf() and calling .filter(), like this: $(selector).find(oSelector).andSelf().filter(oSelector) //or... $(selector).find('*').andSelf().filter(oSelector); Unfortunately .andSelf() doesn't take a selector, which would be handy. A: If you want the chaining to work properly use the snippet below. $.fn.findBack = function(expr) { var r = this.find(expr); if (this.is(expr)) r = r.add(this); return this.pushStack(r); }; After the call of the end function it returns the #foo element. $('#foo') .findBack('.red') .css('color', 'red') .end() .removeAttr('id'); Without defining extra plugins, you are stuck with this. $('#foo') .find('.red') .addBack('.red') .css('color', 'red') .end() .end() .removeAttr('id'); A: In case you are looking for exactly one element, either current element or one inside it, you can use: result = elem.is(selector) ? elem : elem.find(selector); In case you are looking for multiple elements you can use: result = elem.filter(selector).add(elem.find(selector)); The use of andSelf/andBack is pretty rare, not sure why. Perhaps because of the performance issues some guys mentioned before me. (I now noticed that Tgr already gave that second solution) A: I know this is an old question, but there's a more correct way. If order is important, for example when you're matching a selector like :first, I wrote up a little function that will return the exact same result as if find() actually included the current set of elements: $.fn.findAll = function(selector) { var $result = $(); for(var i = 0; i < this.length; i++) { $result = $result.add(this.eq(i).filter(selector)); $result = $result.add(this.eq(i).find(selector)); } return $result.filter(selector); }; It's not going to be efficient by any means, but it's the best I've come up with to maintain proper order. A: I was trying to find a solution which does not repeat itself (i.e. not entering the same selector twice). And this tiny jQuery extention does it: jQuery.fn.findWithSelf = function(...args) { return this.pushStack(this.find(...args).add(this.filter(...args))); }; It combines find() (only descendants) with filter() (only current set) and supports whatever arguments both eat. The pushStack() allows for .end() to work as expected. Use like this: $(element).findWithSelf('.target') A: For jQuery 1.8 and up, you can use .addBack(). It takes a selector so you don't need to filter the result: object.find('selector').addBack('selector') Prior to jQuery 1.8 you were stuck with .andSelf(), (now deprecated and removed) which then needed filtering: object.find('selector').andSelf().filter('selector') A: I think andSelf is what you want: obj.find(selector).andSelf() Note that this will always add back the current node, whether or not it matches the selector. A: If you are strictly looking in the current node(s) the you just simply do $(html).filter('selector') A: Here's the right (but sad) truth: $(selector).parent().find(oSelector).filter($(selector).find('*')) http://jsfiddle.net/SergeJcqmn/MeQb8/2/
unknown
d124
train
It would look somthing like this: SoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener(){ @override onLoadComplete(SoundPool soundPool, int sampleId, int status) { // show button and play intro sound here }}); You should read the android guide for developers. And more specificly for this problem: SoundPool Edit - Corrected a typo, "listner" to "listener"
unknown
d125
train
I suspect what you really need is perhaps more involved but the simple answer to the question you asked is to use the const storage class. For example: /* * File: main.c * Author: dan1138 * Target: dsPIC33EP256MC506 * Compiler: XC16 v1.61 * IDE: MPLABX v5.45 * * Created on February 19, 2021, 11:56 PM */ #pragma config ICS = PGD2, JTAGEN = OFF, ALTI2C1 = OFF, ALTI2C2 = OFF, WDTWIN = WIN25 #pragma config WDTPOST = PS32768, WDTPRE = PR128, PLLKEN = ON, WINDIS = OFF #pragma config FWDTEN = OFF, POSCMD = NONE, OSCIOFNC = ON, IOL1WAY = OFF, FCKSM = CSECMD #pragma config FNOSC = FRCDIVN, PWMLOCK = OFF, IESO = ON, GWRP = OFF, GCP = OFF #include "xc.h" const uint16_t ConfDiskImage[] = { /*AOUT*/ 0x01E0,0x0004,0x3333,0x4053, /* 1*/ 0x01E1,0x0012,0x0005,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120, /* 2*/ 0x01E2,0x0012,0x0006,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120, /* 3*/ 0x01E3,0x0012,0x0007,0x0000,0x0000,0x0000,0x4120,0x0000,0x0000,0x0000,0x4120, /*EOD */ 0x0000,0x0000 }; int main(void) { const uint16_t *pData; pData = ConfDiskImage; /* point to the start of the image */ /* * Walk the image */ for(;;) { if((!*pData) && (!*pData+1)) { /* At end of image point to the start */ pData = ConfDiskImage; } pData++; /* skip record type */ pData += 1+*pData/2; } return 0; }
unknown
d126
train
You are looking for something like this, I guess: import java.awt.Cursor; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; public class TestTreeSelection { protected void initUI() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); fillTree(root, 5, "Some tree label"); final DefaultTreeModel model = new DefaultTreeModel(root); final JTree tree = new JTree(model); tree.addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { boolean inside = false; TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path != null) { Rectangle pathBounds = tree.getPathBounds(path); inside = pathBounds.contains(e.getPoint()); } if (inside) { tree.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } else { tree.setCursor(Cursor.getDefaultCursor()); } } }); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new JScrollPane(tree)); f.setSize(400, 600); f.setLocationRelativeTo(null); f.setVisible(true); } private void fillTree(DefaultMutableTreeNode parent, int level, String label) { for (int i = 0; i < 5; i++) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(label + " " + i); parent.add(node); if (level > 0) { fillTree(node, level - 1, label); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TestTreeSelection().initUI(); } }); } } A: This code works: tree_object.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { TreePath tp = ((JTree)e.getSource()).getPathForLocation(e.getX(), e.getY()); if(tp != null) { ((JTree)e.getSource()).setCursor(new Cursor(Cursor.HAND_CURSOR)); } else { ((JTree)e.getSource()).setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } });
unknown
d127
train
OK, just solved it:) The answer was to impersonate a room account and then simple decline the invitation. hope it will help to someone...
unknown
d128
train
DOM manipulations should be done in the link phase and not in the controller. See $compile The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put. Detailed explanation: The problem lies in the the angular FormController. At intialization it will look for a parent form controller instance. As the sub form was created in the controller phase - the parent form initialization has not been finished. The sub form won't find it's parent controller and can't register itself as a sub control element. FromController.js //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; function FormController(element, attrs, $scope, $animate, $interpolate) { var form = this, controls = []; var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl; Plunker A: As Michael said, the correct place to do any DOM manipulations is the link function and not the controller function of the directive. Some extra information on why what you already have does / does not work depending on the use of $timeout: According to the Angular documentation of the $compile service for directive definitions the controller is instantiated before the pre-linking phase while the link function is executed after the template has been cloned You can observe this yourself if you include a link function in your directive and write two console.log statements, one in the controller function and one in the link function. The link function is always executed after the controller. Now, when you include addForm(); in your controller this will be executed at the time the controller is instantiated, ie. before the linking phase, at which time, as it is mentioned in the documentation it is not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. On the other hand, if you call the addForm() function in the $timeout, this will actually be executed after the linking phase, since a $timeout call with a zero timeout value causes the code in the timeout to be called in the next digest cycle, at which point the linking has been performed and the DOM transformation is performed correctly (once again you can see the timing of all these calls by adding console.logs in appropriate places). A: Usually altering dom elements inside of a controller is typically not ideal. You should be able achieve what you are looking for without the need for '$compile' and make things a bit easier to handle if you introduce a second directive an array of items to use 'ng-repeat'. My guess is that $timeout() is working to signal angular about the new elements and causes a digest cycle to handle the correct validation. var app = angular.module('app',[]); app.directive('childForm', function(){ return{ restrict: 'E"', scope:{ name:"=" }, template:[ '<div ng-form name="form2">', '<div>Dynamically added sub form</div>', '<input type="text" name="input1" required ng-model="name"/>', '<button ng-click="name=\'\'">CLEAR</button>', '</div>' ].join('') } }); app.directive('myTest', function() { return { restrict: 'E', scope: {}, controller: function ($scope, $element, $compile, $timeout) { $scope.items = []; $scope.items.push({ name:'myname' }); $scope.name = 'test'; $scope.onClick = function () { console.log("SCOPE:", $scope, $childScope); }; $scope.addItem = function(){ $scope.items.push({name:''}); } }, template: [ '<div>', '<div>Parent Form</div>', '<div ng-form name="form1">', '<div class="form-container">', '<div ng-repeat="item in items">', '<child-form/ name="item.name">', '</div>', '</div>', '<div>Existing sub form on parent scope</div>', '<div ng-form name="form3">', '<input type="text" name="input2" required ng-model="name"/>', '<button ng-click="name=\'\'">CLEAR</button>', '</div>', '</div>', '<button ng-click="addItem()">Add Form</button>', '<button ng-click="onClick()">Console Out Scopes</button>', '</div>' ].join('') }; }); Updated plunkr
unknown
d129
train
Please follow the following steps: * *Go to Settings -> Permissions -> Install via USB: Uncheck your App if it's listed. *Go to Settings -> Additional Settings -> Privacy: Check the Unknown Sources option. *Finally go to Settings -> Additional Settings -> Developer options: Check the Install via USB option.
unknown
d130
train
May be on .done function you will get the view in the response, you need to take that response and bind it to your control A: You call the controller via AJAX, and sure it hits the controller action method, and the controller returns a view but this is your code that deals with whatever is returned from the AJAX call (from the controller): .done(function (response, status, jqxhr) {}) You are doing absolutely nothing, so why would it navigate anywhere. A better question you need to ask yourself, instead of fixing this, is why would you use AJAX and then navigate to another page. If you are navigating to a whole new page, new URL, then simply submit a form regularly (without AJAX) or do it via a link (which the user will click). Use AJAX post if you want to stay on the same page and refresh the page's contents. A: @yas-ikeda , @codingyoshi , @code-first Thank you for your suggestions. Here are the modifications that I had to make to resolve the problem(please feel free to suggest improvements): Basically, I had to end up creating 2 separate Action methods to resolve the problem. In the jquery/Javascript code below, it is important to note the first action method '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) { console.log(resultCodeTable_ID); $.ajax({ url: '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList', type: 'POST', dataType: 'json', contentType: "application/json;charset=utf-8", data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}", cache: false, }).done(function (response, status, jqxhr) { window.location.href = response.Url; }) .fail(function (jqxhr, status, error) { // this is the ""error"" callback }); } The purpose of the 1st action method called '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' is to retrieve a url within a Json object. [HttpPost] public ActionResult RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg) { var redirectUrl = new UrlHelper(Request.RequestContext).Action("NavigateToAParticularResultCodeAssociatedReasonForArrearsList", "Admin", new { resultCodeTable_IDArg = resultCodeTable_IDArg }); return Json(new { Url = redirectUrl }); } The purpose of the 2nd action method is to ultimately navigate to the ASP.NET MVC View that I want to show. public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg) { AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel(); aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg; aParticularResultCodeAssociatedReasonForArrearsListViewModel.RFACodeList = actionCodeResultCodeBusinessService.GetSpecificResultCodeRFACodeList(resultCodeTable_IDArg); return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel); } However, I Dislike the fact that I have to use 2 action methods to navigate to the desired asp.net mvc view, therefore, please feel free to suggest improvements or even a totally different better solution.
unknown
d131
train
I use Python, but the main idea is the same. If you directly do cvtColor: bgr -> gray for img2, then you must fail. Because the gray becames difficulty to distinguish the regions: Related answers: * *How to detect colored patches in an image using OpenCV? *Edge detection on colored background using OpenCV *OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(饱和度) channel in HSV color space. For HSV, refer to https://en.wikipedia.org/wiki/HSL_and_HSV#Saturation. Main steps: * *Read into BGR *Convert the image from bgr to hsv space *Threshold the S channel *Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners. This is the first result: This is the second result: The Python code(Python 3.5 + OpenCV 3.3): #!/usr/bin/python3 # 2017.12.20 10:47:28 CST # 2017.12.20 11:29:30 CST import cv2 import numpy as np ##(1) read into bgr-space img = cv2.imread("test2.jpg") ##(2) convert to hsv-space, then split the channels hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) h,s,v = cv2.split(hsv) ##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV) ##(4) find all the external contours on the threshed S cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] canvas = img.copy() #cv2.drawContours(canvas, cnts, -1, (0,255,0), 1) ## sort and choose the largest contour cnts = sorted(cnts, key = cv2.contourArea) cnt = cnts[-1] ## approx the contour, so the get the corner points arclen = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.02* arclen, True) cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA) cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA) ## Ok, you can see the result as tag(6) cv2.imwrite("detected.png", canvas) A: In OpenCV there is function called dilate this will darker the lines. so try the code like below. private Mat edgeDetection(Mat src) { Mat edges = new Mat(); Imgproc.cvtColor(src, edges, Imgproc.COLOR_BGR2GRAY); Imgproc.dilate(edges, edges, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10, 10))); Imgproc.GaussianBlur(edges, edges, new Size(5, 5), 0); Imgproc.Canny(edges, edges, 15, 15 * 3); return edges; }
unknown
d132
train
So there is two ways to pass values from fragment/activity to dialog fragment:- * *Create dialog fragment object with make setter method and pass value/argument. *Pass value/argument through bundle. Method 1: // Fragment or Activity @Override public void onClick(View v) { DialogFragmentWithSetter dialog = new DialogFragmentWithSetter(); dialog.setValue(header, body); dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter"); } // your dialog fragment public class MyDialogFragment extends DialogFragment { String header; String body; public void setValue(String header, String body) { this.header = header; this.body = body; } // use above variable into your dialog fragment } Note:- This is not best way to do Method 2: // Fragment or Activity @Override public void onClick(View v) { DialogFragmentWithSetter dialog = new DialogFragmentWithSetter(); Bundle bundle = new Bundle(); bundle.putString("header", "Header"); bundle.putString("body", "Body"); dialog.setArguments(bundle); dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter"); } // your dialog fragment public class MyDialogFragment extends DialogFragment { String header; String body; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { header = getArguments().getString("header",""); body = getArguments().getString("body",""); } } // use above variable into your dialog fragment } Note:- This is the best way to do. A: as a general way of working with Fragments, as JafarKhQ noted, you should not pass the params in the constructor but with a Bundle. the built-in method for that in the Fragment class is setArguments(Bundle) and getArguments(). basically, what you do is set up a bundle with all your Parcelable items and send them on.in turn, your Fragment will get those items in it's onCreate and do it's magic to them. the way shown in the DialogFragment link was one way of doing this in a multi appearing fragment with one specific type of data and works fine most of the time, but you can also do this manually. A: Using newInstance public static MyDialogFragment newInstance(int num) { MyDialogFragment f = new MyDialogFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } And get the Args like this @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = getArguments().getInt("num"); ... } See the full example here http://developer.android.com/reference/android/app/DialogFragment.html A: I used to send some values from my listview How to send mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Favorite clickedObj = (Favorite) parent.getItemAtPosition(position); Bundle args = new Bundle(); args.putString("tar_name", clickedObj.getNameTarife()); args.putString("fav_name", clickedObj.getName()); FragmentManager fragmentManager = getSupportFragmentManager(); TarifeDetayPopup userPopUp = new TarifeDetayPopup(); userPopUp.setArguments(args); userPopUp.show(fragmentManager, "sam"); return false; } }); How to receive inside onCreate() method of DialogFragment Bundle mArgs = getArguments(); String nameTrife = mArgs.getString("tar_name"); String nameFav = mArgs.getString("fav_name"); String name = ""; // Kotlin upload val fm = supportFragmentManager val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog var args: Bundle? = null args?.putString("title", model.title); dialogFragment.setArguments(args) dialogFragment.show(fm, "Sample Fragment") // receive override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (getArguments() != null) { val mArgs = arguments var myDay= mArgs.getString("title") } } A: Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too: so you have to create a companion objet to create new newInstance function you can set the paremter of the function whatever you want. using val args = Bundle() you can set your args. You can now use args.putSomthing to add you args which u give as a prameter in your newInstance function. putString(key:String,str:String) to add string for example and so on Now to get the argument you can use arguments.getSomthing(Key:String)=> like arguments.getString("1") here is a full example class IntervModifFragment : DialogFragment(), ModContract.View { companion object { fun newInstance( plom:String,type:String,position: Int):IntervModifFragment { val fragment =IntervModifFragment() val args = Bundle() args.putString( "1",plom) args.putString("2",type) args.putInt("3",position) fragment.arguments = args return fragment } } ... override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fillSpinerPlom(view,arguments.getString("1")) fillSpinerType(view, arguments.getString("2")) confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))}) val dateSetListener = object : DatePickerDialog.OnDateSetListener { override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) { val datep= DateT(year,monthOfYear,dayOfMonth) updateDateInView(datep.date) } } } ... } Now how to create your dialog you can do somthing like this in another class val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position) like this for example class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>() { ... override fun onBindViewHolder(holder: ViewHolder, position: Int) { ... holder.btn_update!!.setOnClickListener { val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position) val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction() dialog.show(ft, ContentValues.TAG) } ... } .. } A: In my case, none of the code above with bundle-operate works; Here is my decision (I don't know if it is proper code or not, but it works in my case): public class DialogMessageType extends DialogFragment { private static String bodyText; public static DialogMessageType addSomeString(String temp){ DialogMessageType f = new DialogMessageType(); bodyText = temp; return f; }; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final String[] choiseArray = {"sms", "email"}; String title = "Send text via:"; final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(title).setItems(choiseArray, itemClickListener); builder.setCancelable(true); return builder.create(); } DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case 0: prepareToSendCoordsViaSMS(bodyText); dialog.dismiss(); break; case 1: prepareToSendCoordsViaEmail(bodyText); dialog.dismiss(); break; default: break; } } }; [...] } public class SendObjectActivity extends FragmentActivity { [...] DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend); dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType"); [...] }
unknown
d133
train
Try this... SELECT definition AS Check_Expression ,name AS ConstraintName FROM sys.check_constraints WHERE Parent_object_ID = OBJECT_ID('TableName')
unknown
d134
train
This seems like a frail solution (but you know your constraints). For eg right now this sql will be invalid because when you append the param strings you forgot to put a leading white space. And maybe you'll need to have different comparators in the future, not only =. Criteria API seems like a better tool for the job
unknown
d135
train
You'll have to identify the span in some way; that could look something like this: WebElement patientButton = driver.findElement(By.xpath("//span/span[child::img[@class='btnRowIcon']]")); Depending on the structure of your site this may or may not work. Once you have the element however you can click it with patientButton.click(). A: A better alternative to blalasaadri's answer, would be to use CSS selectors. They are faster, cleaner, and just.. better. WebElement image = driver.findElement(By.cssSelector("span#addPat img.btnRowIcon")); // now you can perform what you want to on the image. image.getAttribute("src")... A: I agree with sircapsalot, you can also wait for presence of element using implicit or explicit waits.. Here is an example using explicit wait : WebDriverWait image = new WebDriverWait(driver,60); image.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span#id img.btnRowIcon"))); image.click(); The above code will wait for 60 secs for the image to be visible, * *Image will be clicked if found before 60, else an exception will be thrown..
unknown
d136
train
I'm sorry for making a wrong assumption before. The behavior you described is how it should work. The current version is not working as they implemented it wrong, so ver 12 won't work. Detail: https://github.com/primefaces/primeng/issues/10697 But the new version is working as expected. I just forked the link from the homepage and make some changes. You can see the forked link here: https://stackblitz.com/edit/primeng-tablevirtualscroll-demo-p2j757?file=src/app/app.component.ts Your original code also missed the part where you need to listen for the select/click event on the header. If you wanted to "fix" the issue in the old version, you can just copy the patch from the new version. The code is under updateCheckedState
unknown
d137
train
Your loop which build the vertices seems to end too early, because you have n+1 vertices each row/column. It fills the array only to the forelast column, which leads to a shift in the vertices. For cX = 0 To map_size.X 'Rows For cY = 0 To map_size.Y 'Columns 'VERTEX k = cX * (map_size.X + 1) + cY gVertices(k) = New CustomVertex.TransformedColored(cX * tile_size.X, cY * tile_size.Y, 0, 1, Color.Blue.ToArgb) Next cY Next cX
unknown
d138
train
account_sid = "{{ account_sid }}" # Your Account SID from www.twilio.com/console This does not mean place the value in the {{ }}. It means replace that entire string with your value.
unknown
d139
train
Use something like this: if(window.addEventListener){ sNode.options[x+1].addEventListener('click', fixDayList, false); } else if (window.attachEvent){ sNode.options[x+1].attachEvent('onclick', fixDayList); } else { sNode.options[x+1].onclick = fixDayList; } Update: In Safari, unless the option elements are visible and not displayed as a dropdown list, they will never trigger a click event. But, if you add size=10 or whatever to your select element, Safari will then trigger click events on the option elements. Your best bet will be to listen for the change event on the select element instead of trying to use click on the options.
unknown
d140
train
The JSONObject was successfully being created. The problem was in the way I was accessing the value. The image was built by me. The whole response is a TJSONObject, JSONObject.GetValue('result') is a TJSONArray. If I loop through the array It will loop only once and retrieve a TJSONValue which its value is the string I wanted Qk02... The code is like that vJSONObject := RESTResponse1.JSONValue as TJSONObject; if vJSONObject <> nil then begin vJSONArray := vJSONObject.GetValue('result') as TJSONArray; for vJSONValue in vJSONArray do begin memo.Text := vJSONValue.Value; // This is the string I wanted: Qk02.. end; end; A: You can parse your string into a JsonObject. To do this, you have to convert your string into bytes and then convert it into a JsonObject as following : var MyObject : TJSONObject; MyObject := TJSONObject.ParseJSONValue( TEncoding.ASCII.GetBytes(RESTResponse1.Content), 0) as TJSONObject; You don't have to use TEncoding.ASCII. You can also use TEncoding.UTF8/Unicode/Etc depending on your encoding.
unknown
d141
train
I suppose you have a routine/method which is continuously checking for updates to the Data Source. Once you receive the update, you would need to call the DataBind() method again on the grid. UPDATE: GridView control will show what's is in DataSource, so you need to modify the DataSource. One of the possible way could be using asynchronous calls from your Server Side C# code and on the Callback you can reset the DataSource Property. If you are flexible then you can also try Knockout binding using MVVM pattern, have a HTML table bound to knockout Observable Array in View Model.
unknown
d142
train
You need to bind the row click events with .on method as well. $(document).ready(function() { $(document).on("click", ".myTable .row", function() { $(this).toggleClass("activeRow"); }); $(document).on('click', '#addButton', function() { $(".myTable tbody").append(" <tr class='row'> <td>New</td> <td>This</td> <td>is</td> <td>great</td> </tr>"); }); }); .activeRow { background-color: #B0BED9; } .myTable { border-collapse: collapse; width: 80%; clear: both; margin-top: 0; border-spacing: 0; table-layout: fixed; border-bottom: 1px solid #000000; } .myTable tbody, .myTable thead { display: block; width: 100%; } .myTable tbody { overflow: auto; height: 300px; } .myTable th, td { width: 450px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="myTable"> <thead> <tr id="headRow"> <th>alo</th> <th>salam</th> <th>kissa</th> <th>chissa</th> </tr> </thead> <tbody class="bodyRows"> <tr class="row"> <td>Microsoft</td> <td>Saber</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Huawei</td> <td>20.3</td> <td>30.5</td> <td>23.5</td> </tr> <tr class="row"> <td>Google</td> <td>50.2</td> <td>40.63</td> <td>45.23</td> </tr> <tr class="row"> <td>Apple</td> <td>25.4</td> <td>30.2</td> <td>33.3</td> </tr> <tr class="row"> <td>IBM</td> <td>20.4</td> <td>15.6</td> <td>22.3</td> </tr> </tbody> </table> <button id="addButton" class="tableButton">Add Row</button> A: You're adding the toggleClass behaviour to the existing rows, not the newly created ones. You need to add the event when you create new rows: $(document).ready(function () { $(".row").on('click', function (ev) { $(this).toggleClass("activeRow"); }); $('#addButton').on('click', function (ev) { $(".myTable tbody").append(' <tr class="row"> <td>New</td> <td>This</td> <td>is</td> <td>great</td> </tr>'); $(".row").off('click').on('click', function (ev) { // off, to avoid overloading listeners on click event $(this).toggleClass("activeRow"); }); }); });
unknown
d143
train
My guess is that your VB6 app is attempting to open an write-able recordset (rather than a read-only recordset) and because of something in your FROM clause, SQL Server cannot make this write-able. That being said, help us help you by including: * *the code that's failing in VB6 along with relevant "setup" code (i.e. the code used to create your connection and your recordset object variables, etc.) *the SQL statement you are trying to execute A: Consider setting the compatibility mode for the database to SQL Server 2000. The option is available from Database properties in SQL Server Management Studio. A: Take a look at the ODBC data source in Administrative Tools\Data Sources (ODBC) -- if you are positive this is what the application is using. Can you test the connection from there? Is it using the IP address or maybe a server name?
unknown
d144
train
If you're most comfortable with C#, why not build it in Silverlight? Will be a lot easier than building and deploying ActiveX controls. A: How about a Windows Forms app launched from Clickonce or Java web start? You cannot run a 64bit ActiveX from a 32bit IE.
unknown
d145
train
You have to provide your own (infrastructure) maven project which just packages all the mentioned dependencies and all your JBoss projects depend on this infrastructure project with scope provided. But shouldn't you compile just against the specification jars instead of the concrete implementation? Like <dependency> <groupId>org.jboss.spec</groupId> <artifactId>jboss-javaee-6.0</artifactId> <version>1.0.0.Final</version> <type>pom</type> <scope>provided</scope> </dependency> Jump to the first occurrence of "Java EE 6 API" on http://arquillian.org/guides/getting_started/. A: You won't like this answer, but as the libraries are provided at run-time by JBoss, other than using a provided scope, it is not really your affair. The classes of any unstated transitive dependency will be loaded by a different class loader (presumably), and live nicely together with the application classes. For the not so nice coupled classes, what @MichalKalinowski said is true.
unknown
d146
train
My suggestion would be to push this problem down to your database. PostgreSQL, for example, has great support for this kind of problem as documented in this blog post: On 7th of December, Tom Lane committed patch by Jeff Davis that adds general exclusion constraints: Log Message: Add exclusion constraints, which generalize the concept of uniqueness to support any indexable commutative operator, not just equality. Two rows violate the exclusion constraint if "row1.col OP row2.col" is TRUE for each of the columns in the constraint....This could be used for example for making sure that given room is only reserved by 1 user at any give point in time. as well as a handy "Temporal" extension (see here for a slide-deck from PgCon 2012 discussing some of its features).
unknown
d147
train
As is, this requires RSelenium since data is rendered after the page loads and not with reading pre-defined html page. Refer here on how to launch a browser (either Chrome, Firefox, IE etc..) with the object as remdr The below snippet opens Firefox but there are other ways to launch any other browser selCommand <- wdman::selenium(jvmargs = c("-Dwebdriver.chrome.verboseLogging=true"), retcommand = TRUE) shell(selCommand, wait = FALSE, minimized = TRUE) remdr <- remoteDriver(port = 4567L, browserName = "firefox") Sys.sleep(format(runif(1,10,15),digits = 1)) remdr$open() You might have to login to LinkedIn since it won't allow viewing profiles without signing up. You will need to use the RSelenium clickElement and sendKeys functions to operate the webpage. remdr$navigate(url = 'https://www.linkedin.com/') # navigate to the link username <- remdr$findElement(using = 'id', value = 'session_key') # finding the username field username$sendKeysToElement(list('your_USERNAME')) password <- remdr$findElement(using = 'id', value = 'session_password') # finding the password field password$sendKeysToElement(list('your_PASSWORD')) remdr$findElement(using = 'xpath', value = "//button[@class='sign-in-form__submit-button']")$clickElement() # find and click Signin button Once the page is loaded, you can get the page source and use rvest functions to read between the HTML tags. You can use this extension to easily get xpath selectors for the text you want to scrape. pgSrc <- remdr$getPageSource() pgData <- read_html(pgSrc[[1]]) experience <- pgData %>% html_nodes(xpath = "//div[@class='text-body-medium break-words']") %>% html_text(trim = TRUE) Output of experience: > experience [1] "Chief Scientist at RStudio, Inc."
unknown
d148
train
I'm not sure this solution is perfect but this works for my case. There are two key principles working here. 1) Create a delay that is based on requestAnimationFrame: const waitRAF = () => new Promise(resolve => requestAnimationFrame(resolve)); 2) Make the animation I am testing run very fast: In my case the animation I was waiting on has a configurable duration which is set to 1 in my props data. Another solution to this could potentially be running the waitRaf method multiple times but this will slow down tests. You may also need to mock requestAnimationFrame but that is dependant on your setup, testing framework and implementation My example test file (Vue app with Jest): import { mount } from '@vue/test-utils'; import AnimatedCount from '@/components/AnimatedCount.vue'; const waitRAF = () => new Promise(resolve => requestAnimationFrame(resolve)); let wrapper; describe('AnimatedCount.vue', () => { beforeEach(() => { wrapper = mount(AnimatedCount, { propsData: { value: 9, duration: 1, formatDisplayFn: (val) => "£" + val } }); }); it('renders a vue instance', () => { expect(wrapper.isVueInstance()).toBe(true); }); describe('When a value is passed in', () => { it('should render the correct amount', async () => { const valueOutputElement = wrapper.get("span"); wrapper.setProps({ value: 10 }); await wrapper.vm.$nextTick(); await waitRAF(); expect(valueOutputElement.text()).toBe("£10"); }) }) }); A: So, I found the solution myself. I really needed to override window.requestAnimationFrame and window.cancelAnimationFrame. The problem was, that I did not include the mock module properly. // mock_requestAnimationFrame.js class RequestAnimationFrameMockSession { handleCounter = 0; queue = new Map(); requestAnimationFrame(callback) { const handle = this.handleCounter++; this.queue.set(handle, callback); return handle; } cancelAnimationFrame(handle) { this.queue.delete(handle); } triggerNextAnimationFrame(time=performance.now()) { const nextEntry = this.queue.entries().next().value; if(nextEntry === undefined) return; const [nextHandle, nextCallback] = nextEntry; nextCallback(time); this.queue.delete(nextHandle); } triggerAllAnimationFrames(time=performance.now()) { while(this.queue.size > 0) this.triggerNextAnimationFrame(time); } reset() { this.queue.clear(); this.handleCounter = 0; } }; export const requestAnimationFrameMock = new RequestAnimationFrameMockSession(); window.requestAnimationFrame = requestAnimationFrameMock.requestAnimationFrame.bind(requestAnimationFrameMock); window.cancelAnimationFrame = requestAnimationFrameMock.cancelAnimationFrame.bind(requestAnimationFrameMock); The mock must be imported BEFORE any module is imported that might call requestAnimationFrame. // mock_requestAnimationFrame.test.js import { requestAnimationFrameMock } from "./mock_requestAnimationFrame"; describe("mock_requestAnimationFrame", () => { beforeEach(() => { requestAnimationFrameMock.reset(); }) test("reqest -> trigger", () => { const order = []; expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); requestAnimationFrame(t => order.push(1)); expect(requestAnimationFrameMock.queue.size).toBe(1); expect(order).toEqual([]); requestAnimationFrameMock.triggerNextAnimationFrame(); expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([1]); }); test("reqest -> request -> trigger -> trigger", () => { const order = []; expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); requestAnimationFrame(t => order.push(1)); requestAnimationFrame(t => order.push(2)); expect(requestAnimationFrameMock.queue.size).toBe(2); expect(order).toEqual([]); requestAnimationFrameMock.triggerNextAnimationFrame(); expect(requestAnimationFrameMock.queue.size).toBe(1); expect(order).toEqual([1]); requestAnimationFrameMock.triggerNextAnimationFrame(); expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([1, 2]); }); test("reqest -> cancel", () => { const order = []; expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); const handle = requestAnimationFrame(t => order.push(1)); expect(requestAnimationFrameMock.queue.size).toBe(1); expect(order).toEqual([]); cancelAnimationFrame(handle); expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); }); test("reqest -> request -> cancel(1) -> trigger", () => { const order = []; expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); const handle = requestAnimationFrame(t => order.push(1)); requestAnimationFrame(t => order.push(2)); expect(requestAnimationFrameMock.queue.size).toBe(2); expect(order).toEqual([]); cancelAnimationFrame(handle); expect(requestAnimationFrameMock.queue.size).toBe(1); expect(order).toEqual([]); requestAnimationFrameMock.triggerNextAnimationFrame(); expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([2]); }); test("reqest -> request -> cancel(2) -> trigger", () => { const order = []; expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); requestAnimationFrame(t => order.push(1)); const handle = requestAnimationFrame(t => order.push(2)); expect(requestAnimationFrameMock.queue.size).toBe(2); expect(order).toEqual([]); cancelAnimationFrame(handle); expect(requestAnimationFrameMock.queue.size).toBe(1); expect(order).toEqual([]); requestAnimationFrameMock.triggerNextAnimationFrame(); expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([1]); }); test("triggerAllAnimationFrames", () => { const order = []; expect(requestAnimationFrameMock.queue.size).toBe(0); expect(order).toEqual([]); requestAnimationFrame(t => order.push(1)); requestAnimationFrame(t => order.push(2)); requestAnimationFrameMock.triggerAllAnimationFrames(); expect(order).toEqual([1,2]); }); test("does not fail if triggerNextAnimationFrame() is called with an empty queue.", () => { requestAnimationFrameMock.triggerNextAnimationFrame(); }) }); A: Here solution from the jest issue: beforeEach(() => { jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => cb()); }); afterEach(() => { window.requestAnimationFrame.mockRestore(); }); A: Here is my solution inspired by the first answer. beforeEach(() => { jest.useFakeTimers(); let count = 0; jest.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => setTimeout(() => cb(100*(++count)), 100)); }); afterEach(() => { window.requestAnimationFrame.mockRestore(); jest.clearAllTimers(); }); Then in test mock the timer: act(() => { jest.advanceTimersByTime(200); }); Directly call cb in mockImplementation will produce infinite call loop. So I make use of the Jest Timer Mocks to get it under control. A: My solution in typescript. I figured by making time go very quickly each frame, it would make the animations go very (basically instant) fast. Might not be the right solution in certain cases but I'd say this will help many. let requestAnimationFrameSpy: jest.SpyInstance<number, [callback: FrameRequestCallback]>; beforeEach(() => { let time = 0; requestAnimationFrameSpy = jest.spyOn(window, 'requestAnimationFrame') .mockImplementation((callback: FrameRequestCallback): number => { callback(time+=1000000); return 0; }); }); afterEach(() => { requestAnimationFrameSpy.mockRestore(); }); A: The problem with previous version is that callbacks are called directly, which does not reflect the asynchronous nature of requestAnimationFrame. Here is a mock which uses jest.useFakeTimers() to achieve this while giving you control when the code is executed: beforeAll(() => { jest.useFakeTimers() let time = 0 jest.spyOn(window, 'requestAnimationFrame').mockImplementation( // @ts-expect-error (cb) => { // we can then use fake timers to preserve the async nature of this call setTimeout(() => { time = time + 16 // 16 ms cb(time) }, 0) }) }) afterAll(() => { jest.useRealTimers() // @ts-expect-error window.requestAnimationFrame.mockRestore() }) in your test you can then use: yourFunction() // will schedule a requestAnimation jest.runAllTimers() // execute the callback expect(....) // check that it happened This helps to contain Zalgo.
unknown
d149
train
Typically this pattern is used to either hide the implementation of the underlying classes it is presenting an interface for, or to simplify the underlying implementation of something that may be complex. A facade may present a simple interface to the outside world, but under the hood do things like create instances of other classes, manage transactions, handle files or TCP/IP connections -- all stuff that you can be shielded from by the simplified interface. A: In your particular context, this is not really a Facade. What you have in that code is basically a DAO (Data Access Object). A DAO can be seen as a Facade for DB operations, but this is not its main purpose. It mainly intends to hide the DB internals. In your example, if you're switching the underlying storage system to XML files or to some key-value store like HBase, you can still use the methods defined in that "Facade" and no change is required in the client code. A (traditional) Facade deals with complex designs that need to be hidden from the clients. Instead of exposing a complex API and complex flows (get this from this service, pass it to this converter, get the result and validate it with this and then send it to this other service), you just encapsulate all that in a Facade and simply expose a simple method to clients. This way, along with the fact that your API is a lot easier to use, you are also free to change the underlying (complex) implementation without breaking your clients code. A: Facade is a design pattern. A pattern, a software pattern, is a set of rules in order to organize code and provide a certain structure to it. Some goals can be reached by using a pattern. A design pattern is used when designing the application. The Facade pattern allows programmers to create a simple interface for objects to use other objects. Consider working with a very complex group of classes, all implementing their own interfaces. Well, you want to provide an interface to expose only some functionality of the many you have. By doing so, you achieve code simplicity, flexibility, integration and loose-coupling. Facade, in your example, is used in order to manage coupling between many actors. It is a design issue. When you have many components interacting together, the more they are tied the harder it will be to maintain them (I mean code maintenance). Facade allows you to reach loose coupling, which is a goal a programmer should always try to reach. Consider the following: public class MyClass1 implements Interface1 { public void call1() {} public call call2() {} } public class MyClass2 implements Interface2 { public void call3() {} public void call4() {} } public class MyClass { private MyClass1 a; private MyClass2 b; //calling methods call1 call2 call3 and call4 in other methods of this class ... ... } If you had to change business logic located in a class used by call1 or call2... by not changing the interface, you would not need to change all these classes, but just the class inside the method used by one of the interface methods of the first two classes. Facade lets you improve this mechanism. I am sorry but I realize that it does not look so wonderful. Design patterns are heavily used in the software industry and they can be very useful when working on large projects. You might point out that your project is not that large and that may be true, but Java EE aims to help business and enterprise-level application programming. That's why sometimes the facade pattern is used by default (some IDEs use it too).
unknown
d150
train
Typo: Unity does not have an InputActions Type, but it has a InputAction Type. See how you spelled the type different in your example. InputActions does not exist so you can't use it. Change InputActions to InputAction.
unknown
d151
train
Create a BlockingCollection of work items. The thread that creates jobs adds them to this collection. Create a fixed number of persistent threads that read items from that BlockingCollection and process them. Something like: BlockingCollection<WorkItem> WorkItems = new BlockingCollection<WorkItem>(); void WorkerThreadProc() { foreach (var item in WorkItems.GetConsumingEnumerable()) { // process item } } Multiple worker threads can be doing that concurrently. BlockingCollection supports multiple readers and writers, so there's no concurrency problems that you have to deal with. See my blog post Simple Multithreading, part 2 for an example that uses one consumer and one producer. Adding multiple consumers is a very simple matter of spinning up a new task for each consumer. Another way to do it is to use a semaphore that controls how many jobs are currently being processed. I show how to do that in this answer. However, I think the shared BlockingCollection is in general a better solution. A: The .NET thread pool isn't really designed for a fixed number of threads. It's designed to use the resources of the machine in the best way possible to perform multiple relatively small jobs. Maybe a better solution for you would be to instantiate a fixed number of BackgroundWorkers instead? There are some reasonable BW examples.
unknown
d152
train
You can use the following command to output the "History" between a date range, but this will get you a lot more than the comments. tf history "$/Project/Main" /format:detailed /noprompt /recursive /v:D"13 Jun 2013 00:00"~D"01 Jun 2013 00:00" You could use the Brief format, but this is limited in it's width, and will truncate longer comments. Once you have your "Log" you will have to parse it yourself. TFS does not have a format like git does. You could create a console App that reads the history from Console.In.ReadToEnd() and then parses it into just comments and just pipe the results of your tf history into it. You could also query the TFS API for this information using the VersionControlServer.QueryHistory Method, and just get the comments and output those.
unknown
d153
train
$.post("input.php", { question: questionForm.question.value , detail: questionForm.detail.value }, function(data) { //add the id to question input, or any other input element you want $("#question").val(data); }); //and your input.php, echo the $id while ($row = mysql_fetch_assoc($result)){ $id=$row['id']; } echo $id;
unknown
d154
train
A simple hack would be to split the string by letter and count. let occurances = chosenWord.split(guessLowerCase).length - 1 Or you could use regular expression to search for all occurances: let occurances = [...chosenWord.matchAll(new RegExp(guessLowerCase, 'g'))].length
unknown
d155
train
If you have a mixin which is doing something "hacky" with the font size, then you will probably need to reset the font size as you have noticed. I suggest the following: * *Create a Sass partial to record your projects config variables. I suggest _config.sass. *Define your base font-size in _config.sass: $base-font-size: 16px *Add @import _config.sass at the top of your main sass file(s). *Update the mixin to reset the font-size to your $base-font-size: @mixin foo nav font-size: 0 // this is the hacky part > li font-size: $base-font-size // reset font-size Note: If you are using the SCSS syntax, you'll need to update the examples here. A: There's no way to tell the computed value of a property until the styles are actually applied to a document (that's what jQuery examines). In the stylesheet languages, there's no "current" value except the initial value or the value you specify. Save the font size whenever you change it, and pass that seems best, and @BeauSmith has given a good example. This variant lets you pass a size or fallback to a defined global: =block-list($font-size: $base-font-size) font-size: 0 > li font-size: $font-size
unknown
d156
train
You are using jQuery 1.x. Try using jQuery 2.x or 3.x. Source: https://github.com/Dogfalo/materialize/issues/4593 E: The way to do this in your setup would be to change the line //= require jquery to //= require jquery2. A: Looks like a few issues to me: Rails is magic, and it does something called "turbolinks." Basically, pages are dynamically replaced instead of actually changing pages. It makes your site faster, but doesn't always issue the same Javascript events. You'll also need JQuery 2 (I've updated my answer after advice from Dmitry). Change the first few lines of your application JS to: //= require jquery2 //= require turbolinks //= require materialize-sprockets Secondly, I found a second bug that exists in the materialize library. Basically, it wouldn't define updateTextFields() until turbo links loaded a page. To fix this, I've submitted a PR, but in the meantime, I would money-patch this by copy/pasting the method from the source to your code (inside $(document).ready). Use something like this to let your code get updated once they fix the bug (pretty much a polyfill). Materialize.updateTextFields = Materialize.updateTextFields || // code from forms.js
unknown
d157
train
Give something like this a shot: <div class="container-fluid"> <div class="row-fluid"> <div class="span9" id="maincontent"> <div class="row"> <div class="span2" style="float: left; width: 15%;">2</div> <div class="span8" style="float: left; width: 65%;">8</div> <div class="span2" style="float: left; width: 15%;">2</div> </div> </div> <div class="span3" id="sidebar"> <!-- sidebar elements go here --> sidebar </div> </div> </div> You'll want to tweak and play with the % to fit your needs, and eventually move those inline styles out into a stylesheet. You may need to slap !important on them to keep them from being overriden by the fluid twitter bootstrap classes. The reason they were stacking with your setup is that the fluid styles took over despite the non-fluid container/row classes you used, and changed them to float: none, width: 100%; display: block divs.
unknown
d158
train
I don't think you can accomplish this as a sass variable; however, it is possible to use a mixin to get the same result: @mixin bggradient() { -moz-linear-gradient( 90deg, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), -webkit-linear-gradient(left, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), -o-linear-gradient(left, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), linear-gradient(to right, rgb(32,40,0) 0%, rgb(56,72,0) 49%, rgb(84,111,0) 100%), } Then to call this mixin in your sass code: @include bggradient(); Here is more information about mixins: http://sass-lang.com/guide
unknown
d159
train
DoString will return what your script return. lua.DoString ("return 10+10")[0]; // <-- will return Double. 20 If you want to get your Lua function as LuaFunction object you need to return your function, or even better just use the [] operator to get the global value of hh. lua.DoString ("function hh() end"); var hh = lua["hh"] as LuaFunction; hh.Call (); Here is a example: https://github.com/codefoco/NLuaBox/blob/master/NLuaBox/AppDelegate.cs#L46 (but Using NLua instead LuaInterface) And remember to release your LuaFunction calling Dispose when you don't need the function anymore.
unknown
d160
train
Mobile Web Apps. U are relying on plugins to access native API's. Native Apps has the access to the API integrated in the native Language (java for android, objective c for iOS). Hybrid Apps: u can program the device dependant code in native. Mobile WEb, u need a plugin.
unknown
d161
train
You can use CROSS JOIN to generate tuples of (contracts, suppliers, contract requirement), then use LEFT JOIN to match contract requirements with supplier approvals: SELECT contract_requirement.contr, suppliers.vndno, COUNT(contract_requirement.reqmt) AS req_count, COUNT(supplier_approval.reqmt) AS app_count FROM contract_requirement CROSS JOIN ( SELECT DISTINCT vndno FROM supplier_approval ) AS suppliers LEFT JOIN supplier_approval ON suppliers.vndno = supplier_approval.vndno AND contract_requirement.reqmt = supplier_approval.reqmt GROUP BY contract_requirement.contr, suppliers.vndno HAVING COUNT(contract_requirement.reqmt) = COUNT(supplier_approval.reqmt) A: You can use a join and group by and then having to be sure that you have all requirements: select cr.contr from (select cr.*, count(*) over (partition by cr.contr) as cnt from contract_requirement cr ) cr join supplier_approval sa on sa.approvalid = cr.requirementid group by cr.contr, cr.cnt having cr.cnt = count(*)
unknown
d162
train
Itertools and list comprehensions are good for breaking stuff down like this. import itertools ["".join(x) for y in range(1, len(word) + 1) for x in itertools.permutations(word, y)]
unknown
d163
train
What you are asking for is not rounding away from zero, it is Ceiling for positive numbers and Floor for negative numbers. A: MidpointRounding.AwayFromZero Is a way of defining how the midpoint value is handled. The midpoint is X.5. So, 4.5 is rounded to 5, rather than 4, which is what would happen in the case of MidpointRounding.ToEven. Round is completely correct. If you want to write a function that rounds all non-integer values to the next highest integer then that operation is Math.Ceiling, not Round.
unknown
d164
train
While Zhengjie's answer might work. I found a more simple way to go about it: let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("imagetoupload")) let data = UIImagePNGRepresentation(image) data.writeToURL(fileURL!, atomically: true) uploadReq.body = fileURL A: First U should save the Image to Document Directory. then Post the URL. U can do like this : func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { let data = UIImagePNGRepresentation(image) // get the data let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true) as! [String] let path = paths[0] let fileName = "testimage.png" let filePath = path.stringByAppendingPathComponent(fileName) // get the file url to save var error:NSError? if !data.writeToFile(photoPath, options: .DataWritingAtomic, error: &error) {// save the data logger.error("Error write file: \(error)") } upload.body = NSURL(string: filePath) // used url to post to server }
unknown
d165
train
Considering how your constructors look I would suggest you to get rid of them and use a Builder pattern instead: class Tool { private Tool() { // Preventing direct instantiation with private constructor this.span = new Span(); } ... // Tool class code public static Builder builder() { return new Builder(); } public static class Builder { private final Tool tool = new Tool(); public Builder withId(String id) { tool.span.addAttribute(new Attribute(Attribute.ID, id)); return this; } ... // other methods in the same manner public Tool build() { // Add some validation if necessary return tool; } } } Usage: Tool tool = Tool.builder() .withId("id") .withClasses("classA, classB") .build(); A: Your basic problem is that constructors have a fixed name (that of the class), so they must be distinguished by parameter types, so you can't have multiple constructors with the same types but which interpret them differently. There's the builder pattern (see other answer) or this - the factory method pattern: // private constructor private Tool() { } // factory methods with same parameters but different names: public static Tool forId(String id) throws Exception { Tool tool = new Tool(); tool.span = new Span(); tool.span.addAttribute(new Attribute(Attribute.ID, id)); return tool; } public static Tool forClasses(String classes) throws Exception { Tool tool = new Tool(); tool.span = new Span(); tool.span.addAttribute(new Attribute(Attribute.CLASS, classes)); return tool; } // etc for other interpretations of a String You could refactor this to make it a little cleaner, but this shows the essence of the approach. A: What I've used in the past is something like this: public abstract class StringValue { private final String value; protected StringValue(String value) { this.value = value; } public String toString() { return value; } } public class Id extends StringValue { public Id(String id) { super(id); } } public class Classes extends StringValue { public Classes(String classes) { super(classes); } } This way, you get real, object-oriented types. This is particularly powerful if you have specific extra logic for each type (validation logic, conversion logic to represent the value in different ways for different systems integrated with, etc.) And if you don't have a need for extra logic, it's just a few lines of code to create and extra type. A: The best solution is to use static factory methods with different method names, as suggested in Bohemian's answer. Given the hypothetical requirement that overloading cannot be avoided, we must provide different method signatures; more accurately, different signatures under erasure. Therefore it is necessary to define and use custom types like your Id etc. One way is to have a method parameter just for overloading resolution, without caring for its value: public Tool(Id id, String value){...} new Tool( (Id)null, "hammer" ); It might look better with a constant for (Id)null public static final Id ID = null; new Tool(ID, "hammer"); If we require that the value must be carried in the parameter, you'll need wrapper types that wraps the values, as in Bolwidt's answer. In java8, we could also use lambda expression to define the wrapper: public interface Id extends Supplier<String>{} public Tool(Id id) { String attributeValue = id.get(); ... } new Tool((Id)()->"hammer"); new Tool((Id)"hammer"::toString);
unknown
d166
train
I feel bad getting points for such a quickie but if the question's going to remain I guess we may as well give some closure for future finders. So, DockPanel has its uses but in this scenario it's your culprit. As a DockPanel nested in a layout as such is basically the equivalent of attaching the VerticalAlignment="Top" property to your GridControl. Which interprets as it only consuming the space necessary for it from the top down of the parent row. By removing the DockPanel entirely (since in this scenario it's redundant) and applying the Row declaration directly to the GridControl it has the ability to act as a normal child to the parent Grid container and will consume the space provided by the Row's * declaration. Glad you got it sorted, got to love the quick 'n easy ones. Cheers :)
unknown
d167
train
The problem is that there is no hibernate session in the new asynchronous thread, and the default AsyncTaskExecutor is not logging the exception. You can verify this yourself by putting a try/catch block inside your @Async method and logging the exception yourself. The solution is to use Domain.withNewSession around the GORM code in your service method: import org.springframework.scheduling.annotation.Async class MyService { @Async void myAsyncMethod() { MyDomain.withNewSession { MyDomain m = new MyDomain(...) m.save() } } } If you have many asynchronous methods, you may consider creating your own AsyncTaskExecutor as in this SO answer.
unknown
d168
train
It is hard to say without knowing whole your code but perhaps there can be some help with diagnosing your issue. Create small test application (console is enough) which will use DataContractJsonSerializer directly. Once you have this helper tool you can try to deserialize captured JSON message to your data contracts (use Fiddler to capture JSON) or you can try to create data contract you expect and serialize it and compare serialized and incoming message (they must be same). A: I believe I found the answer to this question. I think the reason the parameter was null was because this: var data= { a: [1011,1012,1013], b: JSON.stringify(settings), c: "01/01/2011 23:59:59" }; should be this: var data = { settings: { a: [1011,1012,1013], b: JSON.stringify(settings), c: "01/01/2011 23:59:59" } } The data I wanted needed to be wrapped in a settings variable that matched the name of the parameter of the SaveSettings method. The service doesn't automatically put the data you send up into the settings parameter. It sounds blindingly obvious now I look back at it, but for some reason I missed this when I was creating the service originally. Edit: I believe I missed this because with the old asmx services, you could pass in the data in the same order as the parameters and the service automatically populated the parameters with the correct values. In WCF, however, that is not the case and you have to explicitly specify them.
unknown
d169
train
In ES6 you need to do the following to use a var in string `MATCH (productName) AGAINST ${txt}` IF you cannot use `` Just go for the old way with string concatanation, "MATCH (productName) AGAINST '" +txt + "'"
unknown
d170
train
Just run this inside the directory where you installed your project: composer install after php artisan make:controller PagesController A: composer update --no-scripts run this command after that add a env file to your folder
unknown
d171
train
You can cast a DateTime as a Time data type. For example: SELECT [day_shift_flag] FROM [company_working_time] WHERE CAST(GETDATE() AS TIME) BETWEEN CAST([start_time] AS TIME) AND CAST([end_time] AS TIME) A: By Following Way You can Ignore the day,month,year SELECT [day_shift_flag] FROM [company_working_time] WHERE DatePart(HH,GETDATE()) BETWEEN DatePart(HH,[start_time]) AND DatePart(HH,[end_time])
unknown
d172
train
There are several mistakes in your code, for example In your function you set startTime to Date.now() it's alright, BUT! at the very next moment you set elapsed to Date.now() - startTime so it will be always 0, because startTime equals Date.now(). Then you just do the same thing in the statement of your if section, it will be always true. SO basicly nothing changes, and that leads to an infinite loop etc.. Either you can set startTime in your main function, or pass it thru playLights() function. Finally you have to pass startTime to the callback function in setTimeout() you can do it like so: `setTimeout(function() {playLights(startTime);}, interval.toFixed());` so your code would look something like this: function playLights(startTime) { interval = (totalTimer-elapsed) * 0.026; lights[0].color(0, 91, 68, 3500, 0); lights[1].color(0, 91, 68, 3500, 0); setTimeout(function() { lights[0].color(0, 100, 100, 3500, 0); lights[1].color(0, 100, 100, 3500, 0); }, 300); elapsed = Date.now() - startTime; if (elapsed < 37000) { setTimeout(function(){playLights(startTime)}, interval.toFixed()); } console.log("Interval: "+interval+" ,Elapsed: "+elapsed); } And you can call it like this: playLights(Date.now());
unknown
d173
train
on an atomic object of type A is defined in the standard But we can call GCC will accept it. But on clang you'll get an error. is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic? No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 : 5 In the following synopses: * *An A refers to one of the atomic types. [...] And then all the functions are defined in terms of A, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 : C atomic_fetch_key(volatile A *object, M operand); Atomic type is a type with _Atomic.
unknown
d174
train
Your JSON is invalid correct JSON will look like this. { "error": false, "response": { "comdata": [ { "id": "35", "address": "Address" } ], "empdata": [ { "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" }, { "cid": "33", "comid": "35", "empname": "test", "empdob": "0000-00-00" } ] } } You can parse the JSON using below code. private void parseResponse(String result) { try { JSONObject jsonObject = new JSONObject(result); if (jsonObject.getBoolean("error")) { JSONObject response = jsonObject.getJSONObject("response"); JSONArray jsonArray1 = response.getJSONArray("comdata"); List<ComData> comdataList = new ArrayList<>(); for (int i = 0; i < jsonArray1.length(); i++) { ComData comData = new ComData(); comData.setId(jsonArray1.getJSONObject(i).getString("id")); comData.setAddress(jsonArray1.getJSONObject(i).getString("address")); comdataList.add(comData); } JSONArray jsonArray2 = response.getJSONArray("empdata"); List<EmpData> empdataList = new ArrayList<>(); for (int i = 0; i < jsonArray2.length(); i++) { EmpData empData = new EmpData(); empData.setCid(jsonArray2.getJSONObject(i).getString("cid")); empData.setComid(jsonArray2.getJSONObject(i).getString("comid")); empData.setEmpname(jsonArray2.getJSONObject(i).getString("empname")); empData.setEmpdob(jsonArray2.getJSONObject(i).getString("empdob")); empdataList.add(empData); } } } catch (JSONException e) { e.printStackTrace(); } } } Or you can easily parse JSON to POJO using GSON, refer César Ferreira's answer. A: Your JSON is invalid you should have it something like this: { "error": false, "response": { "comdata": [{ "id": "10", "username": null, "email": "[email protected]" }], "empdata": [{ "eid": "33", "empname": "test", "empdob": "0000-00-00", "empgender": "test", "empphoto": "" }], "someData": [{ "eid": "34", "empname": "test", "empdob": "0000-00-00", "empgender": "test", "empphoto": "" }] } } The property someData I had to add it so it would be a valid JSON, I don't know if it fits your requirements. You can use jsonschematopojo to generate a class like this: Comdatum class package com.example; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Comdatum { @SerializedName("id") @Expose private String id; @SerializedName("username") @Expose private Object username; @SerializedName("email") @Expose private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public Object getUsername() { return username; } public void setUsername(Object username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } Data class package com.example; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Data { @SerializedName("error") @Expose private Boolean error; @SerializedName("response") @Expose private Response response; public Boolean getError() { return error; } public void setError(Boolean error) { this.error = error; } public Response getResponse() { return response; } public void setResponse(Response response) { this.response = response; } } Empdatum Class import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import package com.example; public class Empdatum { @SerializedName("eid") @Expose private String eid; @SerializedName("empname") @Expose private String empname; @SerializedName("empdob") @Expose private String empdob; @SerializedName("empgender") @Expose private String empgender; @SerializedName("empphoto") @Expose private String empphoto; public String getEid() { return eid; } public void setEid(String eid) { this.eid = eid; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } public String getEmpdob() { return empdob; } public void setEmpdob(String empdob) { this.empdob = empdob; } public String getEmpgender() { return empgender; } public void setEmpgender(String empgender) { this.empgender = empgender; } public String getEmpphoto() { return empphoto; } public void setEmpphoto(String empphoto) { this.empphoto = empphoto; } } Response Class package com.example; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Response { @SerializedName("comdata") @Expose private List<Comdatum> comdata = null; @SerializedName("empdata") @Expose private List<Empdatum> empdata = null; @SerializedName("someData") @Expose private List<SomeDatum> someData = null; public List<Comdatum> getComdata() { return comdata; } public void setComdata(List<Comdatum> comdata) { this.comdata = comdata; } public List<Empdatum> getEmpdata() { return empdata; } public void setEmpdata(List<Empdatum> empdata) { this.empdata = empdata; } public List<SomeDatum> getSomeData() { return someData; } public void setSomeData(List<SomeDatum> someData) { this.someData = someData; } } SomeDatum Class package com.example; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class SomeDatum { @SerializedName("eid") @Expose private String eid; @SerializedName("empname") @Expose private String empname; @SerializedName("empdob") @Expose private String empdob; @SerializedName("empgender") @Expose private String empgender; @SerializedName("empphoto") @Expose private String empphoto; public String getEid() { return eid; } public void setEid(String eid) { this.eid = eid; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } public String getEmpdob() { return empdob; } public void setEmpdob(String empdob) { this.empdob = empdob; } public String getEmpgender() { return empgender; } public void setEmpgender(String empgender) { this.empgender = empgender; } public String getEmpphoto() { return empphoto; } public void setEmpphoto(String empphoto) { this.empphoto = empphoto; } } And Then you can just do something like this: String jsonString = "Your JSON String"; Gson converter = new Gson(); Data settingsdata = converter.fromJson(jsonString , Data.class);
unknown
d175
train
First of all, read the following SO post that is very helpful. Creating USDZ from SCN programmatically In SceneKit, there's the write(to:options:delegate:progressHandler:) instance method that does the trick (the only thing you have to do is to assign a file format for URL). let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("model.usdz") sceneView.scene.write(to: path) Converting OBJ to USDZ using SceneKit.ModelIO However, if you need to convert OBJ model into USDZ, you have to import SceneKit.ModelIO module at first. Then use the following code: let objAsset = MDLAsset(url: objFileUrl) let destinationFileUrl = URL(fileURLWithPath: "path/Scene.usdz") objAsset.exportToUSDZ(destinationFileUrl: destinationFileUrl) Terminal approach In Xcode 11/12/13/14, you can convert several popular input formats into USDZ via command line: obj, gltf, fbx, abc, usd(x). usdzconvert file.gltf In Xcode 10, only OBJ-to-USDZ, single-frame ABC-to-USDZ and USD(x)-to-USDZ conversion is available via command line: xcrun usdz_converter file.obj file.usdz Preparing files for RealityKit In Xcode 12+ you can use a Reality Composer software for converting any RC scene into usdz file format (right from UI). Also, there's a Reality Converter standalone app. And, of course, you can use Autodesk Maya 2020 | 2022 | 2023 with Maya USD plugin.
unknown
d176
train
The command is keytool, not store. Per the documentation, the command you need to run is: keytool -list -alias androiddebugkey -keystore <path_to_debug_keystore>.keystore -storepass android -keypass android In your specific case, for Ubuntu, this turns into: keytool -list -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android
unknown
d177
train
I am trying to fetch data from db and mapping it to a different entity but I get ArrayIndexOutOfBoundsException But in the following line, you are not doing that, you are trying to get the list of Student entity list. And what's your different Entity here? entityManager.createNamedQuery("findAll", Student.class); But as you provided another entity Generic, I assume you want your data to be loaded in that. There are different possible solutions to this problem. Lets figure out. Using the SELECT NEW keywords Update your Native query to this @NamedNativeQueries({ @NamedNativeQuery(name = "Student.findAll", query = "SELECT NEW Generic(a.student_id, a.student_code) FROM Student a") }) You have to define a Constructor in the Generic class as well that qualifies this call public void Generic(Long id, String code) { this.id = id; this.code = code; } And update the query execution in DAO as List<Generic> results = em.createNamedQuery("Student.findAll" , Generic.class).getResultList(); Note: You may have to place the fully qualified path for the Generic class in the Query for this Construct from List<Object[]> Alternatively the straight forward and simplest solution would fetch the result list as a list of Object[] and populate to any new Object you want. List<Object[]> list = em.createQuery("SELECT s.student_id, s.student_code FROM Student s") .getResultList(); for (Object[] obj : list){ Generic generic = new Generic(); generic.setId(((BigDecimal)obj[0]).longValue()); generic.setCode((String)obj[1]); }
unknown
d178
train
Since you mention PyQt yourself, you could perhaps just create a simple GUI using these tools, with your entire application made up of a QtWebKit module. Then just point to some files you created locally, and browse them using your appliction? But, this would not be any different compared to using a normal browser, so there's not really any point in doing this in my opinion... A: If it were Python-based but had nothing to do with Python, would you really care if it wasn't Python based? Anyways, yes, a project exists. A pretty big one too. It's called XULRunner. The project is maintained by Mozilla and is used for the GUI of every Mozilla program. It features an XML-based syntax (XUL): <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="main" title="My App" width="300" height="300" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myapp/content/main.js"/> <caption label="Hello World"/> <separator/> <button label="More >>" oncommand="showMore();"/> <separator/> <description id="more-text" hidden="true">This is a simple XULRunner application. XUL is simple to use and quite powerful and can even be used on mobile devices.</description> </window> And JavaScript: function showMore() { document.getElementById("more-text").hidden = false; } You can even embed Python scripts, it seems, into your code: http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html A: you could always use django, django templates support html, js, css, php etc.
unknown
d179
train
Okay I think the problem is this: 1) You use a Value Event to listen to the data (keep in mind that this listener is very active). 2) Then when you long click you update a certain value in the database. 3) Because the ValueEventListener is very active it will respond to the change, and re populate the list. Okay this is my analysis according to your code. Possible Solution: Try to listen once when you populate data. So instead of this in the (showList() method): NameRef.addValueEvent...... use this: NameRef.addListenerForSingleValueEvent(.....) Hope it helps fix the problem.
unknown
d180
train
Change: $username=$_POST['password']; With: $password=$_POST['password']; As the $password var is not set the print_r is not executed. A: You are validating $email but declaring $username and other error assigning $password if (isset($_POST['btnLogin'])){ if (isset($_POST['username']) && !empty($_POST['username'])){ $username=$_POST['username']; }else{ $errusername="Enter Username"; } if (isset($_POST['password']) && !empty($_POST['password'])){ $password=$_POST['password']; }else{ $errpassword="Enter Password"; } if (isset($username) && isset($password)) { $user = new User(); print_r($user); } } A: you can use echo "<pre>"; var_export( $user )
unknown
d181
train
If you open the file by double-clicking on it, are you able to read the data? Usually a special library like POI is required to write to excel so I would be surprised if it does. If your txt file has data in csv(comma separated) format, then changing the extension to .csv should work for you.
unknown
d182
train
Your existing code is a mashup of writing to internal storage and external storage. The line fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE); attempts to create a file in the app's private data directory, and you can only pass file names to this method, not a deeper path. That's where the crash is coming from, but it's not what you want. You started to create a path to external storage, but never actually used it. To write the file to that location on the external SD card, modify your code like so: FileOutputStream fOut = null; //Since you are creating a subdirectory, you need to make sure it's there first File directory = new File(Environment.getExternalStorageDirectory(), "AutoWriter"); if (!directory.exists()) { directory.mkdirs(); } try { //Create the stream pointing at the file location fOut = new FileOutputStream(new File(directory, "samplefile.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } OutputStreamWriter osw = new OutputStreamWriter(fOut); //...etc... Using the SD card allows the file to be accessed by anyone. A: openFileOutput() writes file in the internal memory and not sd card. So change fOut = openFileOutput(sdDir + "/AutoWriter/samplefile.txt",MODE_WORLD_READABLE); to fOut = openFileOutput("samplefile.txt", MODE_WORLD_READABLE); Also the file name can not contain path separators. See Android Developers Reference public abstract FileOutputStream openFileOutput (String name, int mode) Open a private file associated with this Context's application package for writing. Creates the file if it doesn't already exist. Parameters name The name of the file to open; can not contain path separators. The file can be then be accessed like this. FileInputStream fis = openFileInput("samplefile.txt"); Note: For files which are huge in size, it's better to save it in sd card. Here is the code snippet. if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { FileOutputStream fos = null; try { File rootPath = new File(Environment.getExternalStorageDirectory(), "AutoWriter"); if (!rootPath.exists()) rootPath.mkdirs(); File file = new File(rootPath, "samplefile.txt"); fos = new FileOutputStream(file); // ... more lines of code to write to the output stream } catch (FileNotFoundException e) { Toast.makeText(this, "Unable to write file on external storage", Toast.LENGTH_LONG).show(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) {} } } }
unknown
d183
train
I think that you are looking into this issue from the wrong angle. I suggest that you may build the angular app, and put yor ExtJS components inside that thing, not the opposite. Here, you have an approximated approach of what you are trying to do : https://www.sencha.com/blog/first-look-ext-js-bridge-to-angular-2/ I want to believe "The Bridge" is also compatible with new Angular versions.
unknown
d184
train
Just use a cumulative sum: select t.*, sum(isStart) over (order by start) as grp from t;
unknown
d185
train
You need to customize Identity Model and add navigation properties. public class ApplicationUser : IdentityUser { public virtual ICollection<ApplicationUserRole> UserRoles { get; set; } } and then add required configuration. protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>(b => { // Each User can have many entries in the UserRole join table b.HasMany(e => e.UserRoles) .WithOne(e => e.User) .HasForeignKey(ur => ur.UserId) .IsRequired(); }); modelBuilder.Entity<ApplicationRole>(b => { // Each Role can have many entries in the UserRole join table b.HasMany(e => e.UserRoles) .WithOne(e => e.Role) .HasForeignKey(ur => ur.RoleId) .IsRequired(); }); } and then you can use joins to query users with roles. More information on adding navigation proprieties can be found here
unknown
d186
train
import csv newest = ['x11;y11;z11', 'x12;y12;z12', 'x13;y13;z13', 'x14;y14;z14', 'x15;y15;z15', 'x16;y16;z16', 'x17;y17;z17', 'x18;y18;z18', 'x19;y19;z19', 'x20;y20;z20'] new = [] for i in newest: new.append(i.split(";")) with open("file.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerows(new) output:
unknown
d187
train
uint8_t array [sizeof(this) + sizeof(that) + ...]; uint8_t* ptr = array; memcpy(ptr, &this, sizeof(this)); ptr+=sizeof(this); memcpy(ptr, &that, sizeof(that)); ptr+=sizeof(that); ... Avoid making a struct. Although structs will make the code more readable, they also introduce padding, which will be an issue in this case.
unknown
d188
train
Here is an example you can use as a guide. The URL you use does not have a result list. I would suggest you use something like https://www.allkeyshop.com/blog/catalogue/search-game/. It appears, what comes after the hyphen is what is being searched. You may need to do a few complicated searches to see how the URL changes. This example uses Task. In the Task setOnSuccedded updates the TableView. Main import java.io.IOException; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * JavaFX App */ public class App extends Application { @Override public void start(Stage primaryStage) { TableView<JSoupData> tvMain = new TableView(); ObservableList<JSoupData> tableItems = FXCollections.observableArrayList(); tvMain.setItems(tableItems); TableColumn<JSoupData, String> tcTagName = new TableColumn<>("Tag Name"); tcTagName.setCellValueFactory(new PropertyValueFactory<>("tagName")); TableColumn<JSoupData, String> tcText = new TableColumn<>("Text"); tcText.setCellValueFactory(new PropertyValueFactory<>("text")); tvMain.getColumns().add(tcTagName); tvMain.getColumns().add(tcText); TextField tfUrl = new TextField("https://www.allkeyshop.com/blog/catalogue/search-game/"); tfUrl.setPromptText("Enter URL Here!"); Button btnProcess = new Button("Process URL"); btnProcess.setOnAction((t) -> { btnProcess.setDisable(true); Task<List<JSoupData>> task = scrapper(tfUrl.getText()); task.setOnSucceeded((WorkerStateEvent t1) -> { List<JSoupData> tempList = task.getValue(); tableItems.setAll(tempList); btnProcess.setDisable(false); }); Thread thread = new Thread(task); thread.setDaemon(true); thread.start(); }); VBox root = new VBox(tvMain, tfUrl, btnProcess); Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(); } public Task<List<JSoupData>> scrapper(String url) { Task<List<JSoupData>> scrapperTask = new Task<List<JSoupData>>() { @Override protected List<JSoupData> call() { List<JSoupData> jSoupDatas = new ArrayList(); try { System.out.println("url: " + url); Document document = Jsoup.connect(url).get(); System.out.println("Title: " + document.title()); Elements gamesNames = document.select(".search-results-row"); System.out.println("search-results-row"); for (Element element : gamesNames) { jSoupDatas.add(new JSoupData(element.tagName(), element.text())); System.out.println("Tag Name: " + element.tagName() + " - Text: " + element.text()); } } catch (IOException e) { System.out.println(e.toString()); } return jSoupDatas; } }; return scrapperTask; } } JSoupData * * @author sedrick (sedj601) */ public class JSoupData { private String tagName; private String text; public JSoupData(String tagName, String text) { this.tagName = tagName; this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("JSoupData{tagName=").append(tagName); sb.append(", text=").append(text); sb.append('}'); return sb.toString(); } } A: Usually, Platform.runLater() can be used to execute those updates on the JavaFX application thread. You can get more information from documentation here and an example from here
unknown
d189
train
Please add your Activity in your AndroidManifest.xml. like below code: <activity android:name=".activities.MainActivity"/> Also put the findViewById() after setContentView() so it can actually return something other than null. A: You can't initialize the textView before call "setContentView" method. I recommend you create a "init" method where initialize all layout's elements and call it after "setContentView"
unknown
d190
train
I haven't tried your code, but you seen to call the procedure p1(dno,name ); and insert name in it. But name can only be output becuase of the OUT, you need to use IN OUT in your procedure at least.
unknown
d191
train
OK, this is a massive simplification because SCD's are very challenging to correctly implement. You will need to sit down and think critically about this. My answer below only handles ongoing daily processing - it does not explain how to handle historical files being re-processed, which could potentially result in duplicate records with different EffectiveStart and End Dates. By definition, you will have an existing record source component (i.e., query from the database table) and an incoming data source component (i.e., a *.csv flatfile). You will need to perform a merge join to identify new records versus existing records. For existing records, you will need to determine if any of the columns have changed (do this in a Derived Column transformation). You will need to also include two columns for EffectiveStartDate and EffectiveEndDate. IncomingEffectiveStartDate = FileDate IncomingEffectiveEndDate = 12-31-9999 ExistingEffectiveEndDate = FileDate - 1 Note on 12-31-9999: This is effectively the Y10K bug. But, it allows users to query the database between date ranges without having to consciously add ISNULL(GETDATE()) in the WHERE clause of a query in the event that they are querying between date ranges. This will prevent the dates on the columns from overlapping, which could potentially result in multiple records being returned for a given date. To determine if a record has changed, create a new column called RecordChangedInd of type Bit. (ISNULL(ExistingColumn1, 0) != ISNULL(IncomingColumn1, 0) || ISNULL(ExistingColumn2, 0) != ISNULL(IncomingColumn2, 0) || .... ISNULL(ExistingColumn_N, 0) != ISNULL(IncomingColumn_N, 0) ? 1 : 0) Then, in your split condition you can create two outputs: RecordHasChanged (this will be an INSERT) and RecordHasNotChanged (this will be an UPDATE to deactivate the exiting record and an INSERT). You can conceivably route both inputs to the same INSERT destination. But, you will need to be careful suppress the update record's ExistingEffectiveEndDate value that deactivates the date.
unknown
d192
train
I think the CloseableHttpResponse will need to be closed manually every individual request. There are a couple ways of doing that. With a try/catch/finally block: import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class CloseableHttpClientWithTryCatchFinally { public static void main(String... args) throws Exception { URIBuilder uriBuilder = new URIBuilder("https://www.google.com/"); HttpGet httpGet = new HttpGet(uriBuilder.build()); CloseableHttpClient client = HttpClients.custom().build(); CloseableHttpResponse response = null; try { response = client.execute(httpGet); response.getEntity().writeTo(System.out); } catch (IOException e) { System.out.println("Exception: " + e); e.printStackTrace(); } finally { if (response != null) { response.close(); } } } } I think a better answer is to use the try-with-resources statement: import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.IOException; public class CloseableHttpClientTryWithResources { public static void main(String... args) throws Exception { URIBuilder uriBuilder = new URIBuilder("https://www.google.com/"); HttpGet httpGet = new HttpGet(uriBuilder.build()); CloseableHttpClient client = HttpClients.custom().build(); try (CloseableHttpResponse response = client.execute(httpGet)) { response.getEntity().writeTo(System.out); } catch (IOException e) { System.out.println("Exception: " + e); e.printStackTrace(); } } } In general, I have seen people just create one CloseableHttpClient for their application and then just reuse that instance throughout their app. If you are only going to be using one, or a few instances, over and over, then no, I don't think you should have to close them. However, if you are going to be creating new instances of CloseableHttpClient over and over, then yes, you will need to close them.
unknown
d193
train
Going through each month in a condition is unneeded, php has functions for that. <?php $firstname= (string)$_POST['firstname']; $lastname = (string)$_POST['lastname']; $month = $_POST['month']; if(in_array($month,range(01,12))===true){ $cont = TRUE; }else{ $cont = FALSE; } //If set, not empty, not swapped for month & greater or equals to 6 chars if(isset($firstname) && $firstname!="" && strlen($firstname) >=6 && in_array($month,range(01,12))===false){ $cont = TRUE; } //If set, not empty, not swapped for month & greater or equals to 6 chars if(isset($lastname) && $lastname!="" && strlen($lastname) >=6 && in_array($month,range(01,12))===false){ $cont = TRUE; } ?>
unknown
d194
train
You have to install mysql2 adapter for working mysql with RoR. Use this command to install the adapter. gem install mysql2 then create the project with rails new MyProject -d mysql this will create your project with MySQL as database. after that in database.yml file you can edit your username, password for MySQL. A: I don't think you need XAMPP to use MySQL with RoR. Put this in your gemfile: gem 'mysql2' Run bundle install on the console. And set up the credentials on database.yml file like this: development: adapter: mysql2 encoding: utf8 database: your_database_name_development username: username password: password And see if it works, run on the console: rake db:create rake db:migrate Hope I could help!
unknown
d195
train
Yes you can do use a listview and create custom adapter. set your map as header in listview and use your listview rows for data representation. Another thing which you can do is create listview and maps seperate. Align your listview just below to the map Here i am giving you a simple example the code below will create listview. You may need to I have created custom adapter for your purpose. public class my_map_activity extends Activity { ArrayList<String> name = null; ArrayList<String> gender = null; ArrayList<String> latitude = null; ArrayList<String> longitude = null; Context activity_context = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView user_listview = (ListView) findViewById(R.id.user_listview); name = new ArrayList<String>(); gender = new ArrayList<String>(); latitude = new ArrayList<String>(); longitude = new ArrayList<String>(); for (int i = 0; i < 10; i++) { name.add ("test user " + i); gender.add ("Male"); latitude.add (""+ i); longitude.add (""+ i); } custom_adapter list_adapter = new custom_adapter (this, android.R.layout.simple_list_item_1, name, gender, latitude, longitude); user_listview.setAdapter(list_adapter); } } Here is my main.xml file. Which will tell you how to create that layout. I am using Relative layout as my parent layout. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="250dp" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" /> <ListView android:id="@+id/user_listview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" > </ListView> </RelativeLayout> here i am posting you my custom adapter code which you can use for your listview purpose. public class custom_adapter extends ArrayAdapter<String>{ ArrayList<String> name = null; ArrayList<String> gender = null; ArrayList<String> latitude = null; ArrayList<String> longitude = null; Context activity_context = null; public custom_adapter(Context context, int resource, ArrayList<String> name , ArrayList<String> gender, ArrayList<String> latitude, ArrayList<String> longitude) { super(context, resource, name ); this.name = name; this.gender = gender; this.latitude = latitude; this.longitude = longitude; activity_context = context; } static class ViewHolder { public TextView txt_name; public TextView txt_gender; public TextView txt_latitude; public TextView txt_longitude; public ImageView img_view; } @Override public View getView (final int position, View convertView, ViewGroup parent) { View rowView = convertView; ViewHolder holder = null; if (rowView == null) { LayoutInflater inflater = (LayoutInflater)activity_context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.row_file, null, false); holder = new ViewHolder(); holder.txt_name = (TextView) rowView.findViewById(R.id.textView1); holder.txt_gender = (TextView) rowView.findViewById(R.id.textView2); holder.txt_latitude = (TextView) rowView.findViewById(R.id.textView3); holder.txt_longitude = (TextView) rowView.findViewById(R.id.textView4); holder.img_view = (ImageView) rowView.findViewById(R.id.imageView1); rowView.setTag(holder); } else { holder = (ViewHolder) rowView.getTag(); } if (holder != null) { holder.txt_name.setText(name.get(position)); holder.txt_gender.setText(gender.get(position)); holder.txt_latitude.setText(latitude.get(position)); holder.txt_longitude.setText(longitude.get(position)); } return rowView; } } Here is the layout which you can inflate in your custom adapter and set it on listview. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:contentDescription="TODO"/> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/imageView1" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@+id/textView1" android:layout_toRightOf="@+id/imageView1" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_alignParentRight="true" android:layout_below="@+id/textView2" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_alignParentRight="true" android:layout_below="@+id/textView3" android:text="Medium Text" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout> So i have given you all four files. Here i am explaining what every file will do. * *my_map_activity : This is the main activity which contains listivew and map both. I am using a big imageview. Instead of that imageview you can place your map. *main.xml : This is layout file which contains both listview and map. *custom_adapter : This is the custom adapter which i have created for you. I am extending array adapter. In this i am taking data from arraylist and inflating the row layout and the i am setting respective values. *row_layout : This is the row layout which will contain imageview for user, name, gender and all other thing. So i have created several things for you if you need any help then you can ask and try to get the concept of each file how i am using.
unknown
d196
train
I figured it out. In the lambda you need to throw an error with the response code you want parsed out. If you simply return it assumes correct execution.
unknown
d197
train
Two suggestions: * *Make sure you don't have any file or directory permissions problems for the installed eggs and files in the site-packages directory. *If you have installed another instance of Python 2.6 (besides the Apple-supplied one in /usr/bin/python2.6), make sure you have installed a separate version of easy_install for it. As is, your output indicates it was almost certainly installed using the Apple-supplied easy_install in /usr/bin which is for the Apple-supplied Python. The easiest way to do that is to install the Distribute package using the new Python. A: I had the same problem, I tried pip install mrjob, sudo easy_install mrjob. It looked like it installed successfully, but when I ran a simple example script, I got the import error. I got it to work by following the instructions at: http://pythonhosted.org//mrjob/guides/quickstart.html#installation. In a nutshell, I cloned the source code from github and ran python setup.py install. My problem might be different from yours, though. There was nothing in my site-packages directory for mrjob after running pip-install and easy_install. A: mrjob package can be installed by running following command: pip install mrjob After installation, the error will be solved. It worked in my case.
unknown
d198
train
TL;DR yes, is the same This cors() is from cors package. CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options. Basically is just a beautiful way to enable cors in routes with middleware. You can check in source code to see how it works, and check documentation other usage ways A: The second one allows you to set custom values for the allowed origin/methods/headers, but the CORS middleware actually supports this anyway - see the "Configuration Options" section on this page. To explain a bit what's going on here: * *app.use(cors()) means "use the cors() middleware for all methods and all paths". *app.options('*', cors()) means "use the cors() middleware for the OPTIONS method, for all paths (*)". *app.options('*', (req, res, next) => { /* ... */ }) means "use the provided function as a middleware for all OPTIONS requests, for all paths (*)".
unknown
d199
train
This problem is caused due to many possible reasons, like: * *You are behind the firewall and firewall block it. *Your internet is too slow. (Hope it is not the case) *You are using VPN or PROXY. (Not all VPN causes this error.) *You have both ipv4 and ipv6 enabled (Not sure about this case.) I cannot confirm about the main reason that is caused for you to not being able to create project from composer but you could try some methods like: * *Changing to different ISP. *Try running composer -vvv: This helps to check what actually is doing behind the scene and helps in further more debug. *Try updating composer to latest version. *Try creating some older version of Laravel or any other packages composer create-project laravel/laravel blog "5.1.*" *Try using some VPN. This is only for testing and doesn't have fully confirmed solution. If there is any other reason we could edit this solution. A: If are installing the composer make sure that,you must have to set environment variable for PHP. If your using xampp control panel ->go to xampp installed path->PHP. Then copy location and set in the environment location.Then try to install composer.
unknown
d200
train
UCallExpression.receiverType does what you want: public class CustomDetector extends Detector implements SourceCodeScanner { @Nullable @Override public List<Class<? extends UElement>> getApplicableUastTypes() { return Collections.singletonList(UCallExpression.class); } @Nullable @Override public UElementHandler createUastHandler(@NotNull JavaContext context) { return new UElementHandler() { @Override public void visitCallExpression(@NotNull UCallExpression node) { node.getReceiverType(); // PsiType:Button } }; } } To extract qualified name you can use the following method: ((PsiClassType) node.getReceiverType()).resolve().getQualifiedName() // android.widget.Button A: I found a solution which works for both static and non-static methods and for Kotlin top level functions. Not sure if it is the best way to do it but at least it works. override fun visitCallExpression(node: UCallExpression) { (node.resolve()?.parent as? ClsClassImpl)?.stub?.qualifiedName } A: /** * eg: android.util.Log * ps. imports was initialized in visitImportStatement */ private fun getClassNameWithPackage(node: UCallExpression): String { var className = node.resolve()?.containingClass?.qualifiedName if (className != null) { return className } className = getClassName(node) ?: return "" for (import in imports) { if (import.contains(className)) { return import } } return "$packageName.$className" } /** * eg: Log */ private fun getClassName(node: UCallExpression): String? { return node.receiver?.javaPsi?.text ?: when (val uExpression = (node.methodIdentifier?.uastParent as UCallExpression?)?.receiver) { is JavaUSimpleNameReferenceExpression -> { uExpression.identifier } is KotlinUSimpleReferenceExpression -> { uExpression.identifier } is UReferenceExpression -> { uExpression.getQualifiedName() } else -> null } }
unknown